c# - "Message": "Authorization has been denied for this request." OWIN middleware

标签 c# jwt owin-middleware

我向 OWIN 中间件添加了基于 token 的身份验证,并且可以生成 token 。但在使用具有授权属性的 API 调用的 token 时,我总是收到“此请求的授权已被拒绝”。尽管没有 Authorize 属性,但它工作正常。这是我的startup.cs 和 Controller 方法。有什么想法,哪里出了问题?

启动.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 方法:

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

最佳答案

这可能是允许的受众的问题。 这里

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

您设置允许的受众。 token aud声明将根据AllowedAudiences列表进行检查。但您永远不会向 token 添加任何受众。

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

token 将通过调用

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

第二个参数负责 JWT 中的 aud 声明:

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

audience Type: System.String

If this value is not null, a { aud, 'audience' } claim will be added.

在 token 授权中设置 aud 声明后应该可以正常工作。

关于c# - "Message": "Authorization has been denied for this request." OWIN middleware,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44398177/

相关文章:

ssl - MVC Web 应用获取 Outlook 邮件失败,无法解析远程名称 'login.microsoftonline.com'

c# - 使用 Owin 中间件添加声明

c# - 使用 OWIN 静态文件时配置客户端缓存

c# - 为什么会出现 SecurityTokenSignatureKeyNotFoundException?

asp.net-core - 通过 AddIdentityServer 将声明添加到 IdentityServer 设置

authentication - 自定义对 jwt 策略 NestJs 验证失败的响应

c# - 字符串未被识别为使用 C# 的有效日期时间

c# - Winform 内部的框架?

c# - 如何缩进 XML 文本并保留 C# 中的换行符?

c# - OWIN 上下文未在 ASP.NET Forms 应用程序中正确初始化