简体   繁体   中英

.Net Core 2.1 CORS and Authorization with Firebase JWT

I'm following this blog post on authenticating with firebase with .net Core 2 https://blog.markvincze.com/secure-an-asp-net-core-api-with-firebase/

(I realise i'm using .net core 2.1 but thinking it must be similar)

I'm using a React Frontend with a .net core 2.1 WebApi Backend.

I am able to hit the controller no problem, however once I try to add the authentication to startup.cs I then get a: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at localhost:4000 (Reason: CORS request did not succeed)

Works totally fine up until that point

My request is coming from http://localhost:3000

UPDATES------------------------------------------------------------------

As a side note, this works when using POSTMAN. I can authenticate with Firebase AND hit the controller without a problem

Also works in chrome. Seems to be an issue with the firefox browser

My Implementation (After Successful Firebase Login Frontend)

Axios Request

axois
.get("https://localhost:4000/v1/picture", {
  headers: {
    accept: "application/json",
    "Accept-Language": "en-US,en;q=0.8",
    "Content-Type": `multipart/form-data;`,
    Authorization: "Bearer " + localStorage.getItem("token") 
    //Is the above the correct way to pass a jwt to be authenticated backend? This is the full jwt returned by Firebase
  }
})

Startup.cs

services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                    builder => builder.WithOrigins("http://localhost:3000")
                        .AllowAnyMethod()
                        .AllowAnyHeader());
            }
        );

        //https://blog.markvincze.com/secure-an-asp-net-core-api-with-firebase/
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Authority = "https://securetoken.google.com/mafirebaseapp";
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = "https://securetoken.google.com/mafirebaseapp",
                    ValidateAudience = true,
                    ValidAudience = "mafirebaseapp",
                    ValidateLifetime = true
                };
            });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
...

...
        app.UseCors("AllowSpecificOrigin");
        app.UseAuthentication();
        app.UseHttpsRedirection();
        app.UseMvc();
}

PictureController.cs

[Route("v1/picture")]
public class PictureController : Controller
{
    [Authorize]
    [HttpGet]
    public IActionResult GetPicture()
    {
        return Ok("Hi");
    }
}

I looked at another post which pointed out that the ordering of the methods made a difference so i don't think that's a problem.

Any help will be much appreciated!

Thanks!

您可以尝试为特定操作使用指定的CORS策略,只需将[EnableCors("AllowSpecificOrigin")]到您的操作中即可。

You can use this NuGet package to make it easy (Support AspNetCore >= 2.0)

Install-Package AspNetCore.Firebase.Authentication

In Startup.cs file

public void ConfigureServices(IServiceCollection services)
{
   services.AddFirebaseAuthentication(Configuration["FirebaseAuthentication:Issuer"], Configuration["FirebaseAuthentication:Audience"]);
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
   app.UseAuthentication();
}

Just have to use [Authorize] attribute on your controllers to enforce authorization

Source: https://bitbucket.org/RAPHAEL_BICKEL/aspnetcore.firebase.authentication/src/master/

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