“消息”:“授权已被拒绝了这个请求。” OWIN中间件(“Message”: “Authorizat

2019-09-27 17:32发布

我加了基于令牌的认证,以我的OWIN中间件,可以生成令牌。 但同时使用,对于授权API调用令牌属性我总是得到“授权已被拒绝了这个请求。” 它虽然能正常工作没有授权属性。 这是我的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控制器的方法:

 [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());
            }
        }

Answer 1:

这可能与被许可的观众的一个问题。 这里

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

您设置允许观众。 令牌aud要求将针对列表进行检查AllowedAudiences 。 但是你从来没有任何观众添加到令牌。

在我们的项目中,我使用了基于所示的代码CustomJwtFormat http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server /

令牌将通过调用生成

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

第二个参数是负责将aud在JWT权利要求:

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

观众类型:System

如果该值不为空,一个{AUD,“观众”}权利要求将被添加。

设置后, aud在令牌授权要求应该可以正常工作。



Answer 2:

从我的理解,你需要添加标题:授权:承载“令牌”。 如果你还没有修改的授权请求的默认实现的步骤是这些:

  1. 在端点注册用户:

     /api/Account/Register 
  2. 发布到/令牌以下项目:
    • grant_type:密码
    • 用户名:“你注册的用户名”
    • 密码:“您的用户注册的密码”
  3. 您将在接收响应令牌
  4. 复制令牌并创建一个请求给您类型的[授权]过滤器固定在所述方法:

      Authorization: Bearer "the_token_you_copied_earlier" 

    不用说,这可能是很容易为你,如果你使用的邮递员或提琴手发出和接收请求,因为它显示了你的一切是如何工作的。



文章来源: “Message”: “Authorization has been denied for this request.” OWIN middleware