简体   繁体   中英

Securing and accessing a .NET core WebApi service using OAuth2

I have a working Asp.NET core WebApi service and a that can be called from an ASP.NET core MVC application. The service is called using an AutoRest generated wrapper. The service currently has no security layer while the website is secured using OAuth2.

I have added the following to the service:

public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddMvc();

        // NEW Authorisation
        services.AddAuthorization(options =>
        {
            options.AddPolicy("ApiAccess", policy => policy.RequireClaim("email"));
        });

    }

My Controller is secured so:

[Authorize(Policy = "ApiAccess")]
public class StatusController : Controller

However I get an "Unauthorized" exception when I call the AutoRest wrapper:

try
        {
            var service = new StatusAPI(new Uri("http://localhost:17237/"));
            ViewData["State"] = service.ApiStatusGet();
        }
        catch (Exception ex)
        {
            ViewData["State"] = new[] { new ServiceStatus { Name = "Health API", Message = "Is unreachable " + ex.Message } };
        }

I'm not sure if the problem lies in that I need a way to pass on the claims in my call to the wrapper or if its in my setup of the service and how it detects the claims.

Please try specifying the value of the claim like the allowed email address. As suggested here - https://docs.asp.net/en/latest/security/authorization/claims.html

Repeated the code

options.AddPolicy("Founders", policy => policy.RequireClaim("EmployeeNumber", "1", "2", "3", "4", "5"));

Autorization cannot be done without authentication. You need to authenticate the user first, then looks at its identity for granting access.

If you have a JWT provided by your OAuth2 AS, you may use the JWT authentication middleware.

public void ConfigureServices(IServiceCollection services)
{
  // add the authentication dependencies
  services.AddAuthentication();
}

public void Configure(IApplicationBuilder app)
{
  app.UseJwtBearerAuthentication(new JwtBearerOptions
  {
     // configure your JWT authentication here
  });
}

Of course the JWT should contains a "email" claim.

You can look at the ASPNET Core sample : https://github.com/aspnet/Security/blob/dev/samples/JwtBearerSample/Startup.cs#L67

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