简体   繁体   English

Asp.net Core授权用户使用策略

[英]Asp.net Core Authorize user with Policy

I am trying to authorize an user with a bearer token send from the request header. 我正在尝试使用从请求标头发送的承载令牌来授权用户。 I added this code in startup file of resource server. 我将此代码添加到资源服务器的启动文件中。

services.AddAuthorization(auth =>
{
   auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()                        
  .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
  .RequireAuthenticatedUser().Build());
});

Here is my method in controller. 这是我在控制器中的方法。

[Authorize("Bearer")]
[HttpGet]
[Route("list")]
public IEnumerable<Products> List()
{
    string Authorization = Request.Headers["Authorization"];
}

Application showing me error 401 Unauthorized even if i had token 应用程序向我显示错误401未经授权,即使我有令牌也是如此

I am sending this Token in the header request 我正在标题请求中发送此令牌

Authorization:Bearer "xyz" 授权:承载者“ xyz”

To work with Bearer token you have to add the following code on your Configure method 要使用Bearer令牌,必须在Configure方法上添加以下代码

public void Configure(IApplicationBuilder app) {
    app.UseJwtBearerAuthentication(options => {
        options.AutomaticAuthenticate = true;
        options.AutomaticChallenge = true;
        options.Audience = "OAuth:Audience";
        options.Authority = "OAuth:Authority";
        options.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(
            metadataAddress: options.Authority + ".well-known/openid-configuration",
            configRetriever: new OpenIdConnectConfigurationRetriever(),
            docRetriever: new HttpDocumentRetriever() { RequireHttps = false });
    });
}

You will also need a middleware to handle the authorization process. 您还需要一个中间件来处理授权过程。 Have a look at AspNet.Security.OpenIdConnect.Server and OpenIddict 看看AspNet.Security.OpenIdConnect.ServerOpenIddict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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