简体   繁体   中英

Why does adding Okta Authentication/Authorization to ASP.Net Core WebAPI with React frontend throw a 500 error?

We have a React App for our frontend and are using ASP.Net Core Web API. We have implemented Okta for our authentication. We can successfully sign users in and out of the application. When we implement CORS in our API everything works as expected; the frontend app consumes the API resources successfully. But when we try to protect the API using Okta Authorization in our Staging environment it fails and returns a 500 server error.

We created a named CORS policy like so:

// Enable CORS
services.AddCors(c =>
{
    c.AddPolicy("AllowOrigin", options =>
    {
        options.WithOrigins("<<my staging url goes here>>")
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials();
    });
}); 

We added the following services (straight from the Okta documentation) to the ConfigureServices method (note: the actual values for the Okta configs are maintained in the appsettings.json):

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = OktaDefaults.ApiAuthenticationScheme;
    options.DefaultChallengeScheme = OktaDefaults.ApiAuthenticationScheme;
    options.DefaultSignInScheme = OktaDefaults.ApiAuthenticationScheme;
})
.AddOktaWebApi(new OktaWebApiOptions()
{
    OktaDomain = Configuration["Okta:OktaDomain"],
    AuthorizationServerId = Configuration["Okta:AuthorizationServerId"],
    Audience = Configuration["Okta:Audience"]
});

services.AddAuthorization();

We created a policy to apply the authorization to all endpoints:

services.AddMvc(o =>
{
    var policy = new AuthorizationPolicyBuilder()
      .RequireAuthenticatedUser()
      .Build();
    o.Filters.Add(new AuthorizeFilter(policy));
});

And then in the Configure pipeline:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseHttpsRedirection();
    app.UseRouting();
    app.UseCors("AllowOrigin");
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

In the React frontend, we are passing the Bearer token in the API request headers.

async function getData() {
    const accessToken = oktaAuth.getAccessToken();
    await axios
        .get(process.env.REACT_APP_GET_URL, {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
            params: {
                username: props.username
            }
        })
        .then((response) => {
            setData(response.data);
            setLoadingData(false);
        })
        .catch(error => { ... }

This works perfect in localhost, but fails with a 500 error when we deploy to Staging. We've even tried consuming the Staging API resources from the React app running in localhost (as suggested by Okta to try), but get the same error.

We've followed the quick start guides for creating a React App with Okta and the Protect Your API Endpoints with Okta, but we are obviously missing something (something important), but I do not know what it is. We are using the Authorization Code flow with PKCE and the default Authorization server.

I expect that if something was wrong with the Okta setup we would get a 401 - Unauthorized error (Okta has said that everything looks correct from what they can tell). The 500 error leads me to believe that it is a CORS issue, but CORS worked before implementing the API protection.

Anyone else have this issue and was able to resolve it? Or does someone know what I may be missing in my setup?

For anyone coming across this same issue later. Okta told us everything looked correct in our setup. We decided to meet with our third-party data center. We were able to track it down to a proxy server in the data center blocking the outbound request to Okta in order to validate the access token. Once this was figured out, the data center added whatever they needed to the proxy server and we were able to successfully validate the token and access our resources on our API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM