简体   繁体   English

“消息”:“此请求已拒绝授权。”OWIN中间件

[英]“Message”: “Authorization has been denied for this request.” OWIN middleware

I added Token based authentication to my OWIN middleware and can generate the token. 我将基于令牌的身份验证添加到我的OWIN中间件,并可以生成令牌。 But while using, the token for an API call with Authorize attribute I always get "Authorization has been denied for this request." 但是在使用时,带有Authorize属性的API调用的令牌总是得到“此请求已拒绝授权”。 It works fine though without Authorize attribute. 没有Authorize属性,它工作正常。 Here is my startup.cs and controller method. 这是我的startup.cs和控制器方法。 Any thoughts , what is wrong? 有什么想法,有什么不对?

startup.cs startup.cs

    public void Configuration(IAppBuilder app)
            {
                var issuer = ConfigurationManager.AppSettings["issuer"];
                var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);
                app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
                    AllowInsecureHttp = true,
                    TokenEndpointPath = new PathString("/token"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                    Provider = new SimpleAuthProvider(),
                    AccessTokenFormat = new JwtFormat(issuer)
                });
                app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] { "*" },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                    }
                });
                container = BuildDI();
                var config = new HttpConfiguration();
                config.Formatters.XmlFormatter.UseXmlSerializer = true;
                config.MapHttpAttributeRoutes();
                config.SuppressDefaultHostAuthentication();
                config.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ExternalBearer));
                config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
                app.UseCors(CorsOptions.AllowAll);
                app.UseSerilogRequestContext("RequestId");
                app.UseAutofacMiddleware(container);
                app.UseAutofacWebApi(config);
                app.UseWebApi(config);
                RegisterShutdownCallback(app, container);
            }

 public class SimpleAuthProvider: OAuthAuthorizationServerProvider
        {
            public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {

                if (context.UserName != context.Password)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect");
                    context.Rejected();
                    return Task.FromResult<object>(null);
                }

                var ticket = new AuthenticationTicket(SetClaimsIdentity(context), new AuthenticationProperties());
                context.Validated(ticket);

                return Task.FromResult<object>(null);
            }

            public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
            {
                context.Validated();
                return Task.FromResult<object>(null);
            }

            private static ClaimsIdentity SetClaimsIdentity(OAuthGrantResourceOwnerCredentialsContext context)
            {
                var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ExternalBearer);
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                return identity;
            }
        }

API Controller Method: API控制器方法:

 [HttpGet]
        [Route("sampleroute")]
        [Authorize]
        public async Task<HttpResponseMessage> GetSamples(string search)
        {
            try
            {

                HttpResponseMessage response;
                using (HttpClient client = new HttpClient(Common.CreateHttpClientHandler()))
                {
                     response = await client.GetAsync("test url");
                }
                var result = response.Content.ReadAsStringAsync().Result;
                Samples[] sampleArray = JsonConvert.DeserializeObject<Samples[]>(result);
                var filteredSamples = sampleArray .ToList().Where(y => y.NY_SampleName.ToUpper().Contains(search.ToUpper())).Select(n=>n);
                log.Information("<==========Ended==========>");
                return  Request.CreateResponse(HttpStatusCode.OK,filteredSamples);

            }
            catch (Exception ex)
            {
                log.Error($"Error occured while pulling the Samples:  {ex.ToString()}");
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.ToString());
            }
        }

It's probably a problem with the allowed audiences. 这可能是允许的受众群体的一个问题。 Here 这里

 app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
 {
     ...     
     AllowedAudiences = new[] { "*" },
     ...
 }

you set the allowed audiences. 您设置允许的受众群体。 The tokens aud claim will be checked against the list of AllowedAudiences . 令牌aud要求将针对列表进行检查AllowedAudiences But you never add any audience to the token. 但是,您永远不会向令牌添加任何受众。

In our project I used a CustomJwtFormat based on the code shown in http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/ 在我们的项目中,我使用了基于http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server中显示的代码的CustomJwtFormat /

The token will be generated with a call to 将通过调用生成令牌

var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);

the second parameter is responsible for the aud claim in the JWT: 第二个参数负责JWT中的aud索赔:

From https://msdn.microsoft.com/en-us/library/dn451037(v=vs.114).aspx : 来自https://msdn.microsoft.com/en-us/library/dn451037(v=vs.114).aspx

audience Type: System.String audience类型:System.String

If this value is not null, a { aud, 'audience' } claim will be added. 如果此值不为空,则会添加{aud,'audience'}声明。

After setting the aud claim in the token authorization should work fine. 在令牌授权中设置aud声明后,应该可以正常工作。

From what I understood, you need to add the header: Authorization: Bearer "token". 根据我的理解,你需要添加标题:Authorization:Bearer“token”。 If you have not modified the default implementation of the authorization request the steps are these: 如果您尚未修改授权请求的默认实现,则步骤如下:

  1. Register user at the endpoint: 在端点注册用户:

     /api/Account/Register 
  2. Post to /token the following items: 发布到/标记以下项目:
    • grant_type: password grant_type:密码
    • username: "the username you registered" 用户名:“您注册的用户名”
    • password: "the password you registered for the user" 密码:“您为用户注册的密码”
  3. You will receive a token in the Response 您将在响应中收到一个令牌
  4. Copy that token and create a Request to the method you secured with the [Authorize] filter of type: 复制该令牌并使用类型为[Authorize]过滤器的方法创建对您保护的方法的请求:

      Authorization: Bearer "the_token_you_copied_earlier" 

    Needless to say, it could be pretty easy for you if you used Postman or Fiddler to make and receive Requests because it shows you how everything works. 毋庸置疑,如果您使用Postman或Fiddler来制作和接收请求,这对您来说可能很容易,因为它向您展示了一切是如何工作的。

暂无
暂无

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

相关问题 始终获得“此请求已被拒绝授权。”消息 - Always getting the “Authorization has been denied for this request.” message 此请求已被拒绝授权。 总是 - Authorization has been denied for this request. Always 此请求的授权已被拒绝。 邮差 - Authorization has been denied for this request. Postman 挥舞着“此请求的授权已被拒绝”消息 - Swagger “Authorization has been denied for this request” message 自托管owin应用程序中的混合授权(Windows NTLM和匿名)不起作用-“此请求的授权已被拒绝” - Mixed authorization (Windows NTLM & anonymous) in selfhosted owin application not working - “Authorization has been denied for this request” 始终使用身份2中的不记名令牌获得“对此请求的授权已被拒绝”。 - Always get “Authorization has been denied for this request.” using Bearer tokens in Identity 2? 发送承载令牌时,API端点返回“此请求已拒绝授权。” - API end point returning “Authorization has been denied for this request.” when sending bearer token 如何修改“此请求的授权已被拒绝。”使用过滤器HostAuthenticationFilter - How to Modify “Authorization has been denied for this request.” Using filter HostAuthenticationFilter Azure AD 带有用于 Web API 的不记名令牌身份验证的 AD 无法正常工作,抛出错误,因为“此请求的授权已被拒绝”。 - Azure AD with Bearer token authentication for Web API not working throwing error as “Authorization has been denied for this request.” 此请求的C#授权被拒绝 - C# Authorization has been denied for this request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM