How do I avoid CORS problem when using OpenID Connect (AWS Cognito)?

Viewed 1891

I am setting up a web page using Vue.js together with a .net core Web API. Frontend and Backend are completely split.

I have configured my API to use openid connect with 'Authorization code grant' in AWS Cognito for authentication as follows:

services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddOpenIdConnect(options =>
        {
            options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.ResponseType = OpenIdConnectResponseType.Code;
            options.MetadataAddress = cognitoSettings.AuthorityUrl;
            options.ClientId = cognitoSettings.ClientId;
            options.SaveTokens = false;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true
            };
        });

This works fine in a browser when I request data from an [Authorized] Controller I get redirected to the Cognito Login Page and after I have entered my credentials, I can see the authorized data.

However if I request the same resource using ajax(axios) inside my Vue-App the backend returns a 302 and the ajax call fails due to Cross Origin Policy. (As the Cognito Login is on a different domain than my backend)

So my questions is: how can I get this scenario working?

  • Do I need to move the openid authentication into my frontend to make this work and let the backend only use Bearer tokens for authorization? But then I need all the openid info like name or email-address is in the backend and not in my Vue-App. How can I get them then?

  • Is it possible to change the response code from 302 to 401 so that the frontend can react to the unauthorized call and redirect the user? But where do I get the Login URL from as all the configuration (client_id, metadataaddress) are configured in my backend.

1 Answers

A couple of pointers for you: * Your API should not use openid connect - it should just validate access tokens * Your SPA should implement Open Id Connect using a Javascript library

I have a Cognito sample UI with this architecture on my blog - which you can log in to - see this link: https://authguidance.com/home/code-samples-quickstart/

There are some related write ups and code samples on the blog - maybe see the first SPA sample and the .Net Core sample

Related