简体   繁体   中英

React (CRA) and Asp.Net Core WebAPI External Login CORS issue

I am working on integrating external auth in asp.net core web API project. The frontend is created using create-react-app and backend and frontend are running on different ports on localhost. For auth, I am already using JWT for email/password login. That is working fine. Now I am trying to add external login for Facebook and Google. I have already implemented the same for another asp.net core MVC app using Identity and it's working, because frontend and backend are on the same site.

I am trying to implement the same approach. That is, I call the external login endpoint from react app, it will send redirect response to Facebook, then on successful it will redirect to API, and I will create user if not exist.

The problem is now when on my API send the 302 response, it is giving below error:

Access to XMLHttpRequest at 'https://www.facebook.com/v3.1/dialog/oauth?client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' (redirected from 'https://localhost:44373/api/Auth/external-login?provider=Facebook') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is the code for Startup:

services.AddAuthentication(options => {
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options => {
    options.SaveToken = true;
    options.RequireHttpsMetadata = true;
    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidIssuer = "https://example.com",
        ValidAudiences = new string[] { "https://example.com" },
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("keystring"))
    };
}).AddFacebook(fbOptions =>
{
    fbOptions.AppId = Configuration["FB_APPID"];
    fbOptions.AppSecret = Configuration["FB_APPSECRET"];
}); 
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                        .AllowAnyMethod()
                                                         .AllowAnyHeader().AllowCredentials()));

And the Auth controller:

[AllowAnonymous]
[Route("external-login")]
//[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
    // Request a redirect to the external login provider.
    var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl });
    var properties = signinManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
    return Challenge(properties, provider);
}

I don't want to use Graph API call from asp.net core. Let me know what i am missing.

On your API that is running on port 44373 you have to enable CORS to allow request from http://localhost:3000.

Check the next link: Enable CORS in ASP.NET Core

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