如果使用OpenIddict在ASP.NET Core中的[AllowAnonymous]方法上通过请求标头发送,则验证访问令牌

时间:2018-04-16 07:23:41

标签: asp.net-core asp.net-core-2.0 openiddict

我在我的ASP.NET Core 2.0应用程序中使用OpenIddict进行JWT身份验证。

我有一个[AllowAnonymous]属性的方法。用户在客户端上进行了身份验证(发送了访问令牌),但访问令牌无效(由于某种原因,此时此刻不重要)所以

contextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)

返回null

问题是如果用户通过身份验证或匿名,我会返回一组不同的数据。服务器认为用户是匿名的,客户端认为用户已登录。

如果请求有Authorization: Bearer eyJhb....请求标头,我想返回http错误代码(不是200),但是在服务器上用户为空。怎么样?

如果方法具有Authorize属性(返回403),但在AllowAnonymous控制器方法上没有,则此功能已经有效。

我想我需要AutomaticAuthenticate exist in ASP.NET Core 1之类的东西。如果设置Context.Token,我想返回401,但用户不存在。

这是我的设置:

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                o.Authority = this.Configuration["Authentication:OpenIddict:Authority"];
                o.Audience = "Web";           //Also in Auhorization.cs controller.
                o.RequireHttpsMetadata = !this.Environment.IsDevelopment();

                if (this.Environment.IsDevelopment())
                {
                    //This ensures that access token is valid, if application is restarted. See also AddOpenIddict in this file.
                    o.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("ThisIsSecretKeyOnlyInDevelopmentSoItIsSafe")),
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        RequireExpirationTime = true
                    };
                }

                o.Events = new JwtBearerEvents()
                {
                    OnMessageReceived = context =>
                    {
                        if (context.Request.Path.ToString().StartsWith("/HUB/"))
                            context.Token = context.Request.Query["access_token"];
                        else
                        {
                            if (context.Request.Query.ContainsKey("access_token"))          //We can download file with acces_token in url
                                context.Token = context.Request.Query["access_token"];
                        }
                        return Task.CompletedTask;
                    },
                    //It would be nice to report error to user with custom status code, but this is not possible: https://stackoverflow.com/questions/48649717/addjwtbearer-onauthenticationfailed-return-custom-error?noredirect=1#comment84308248_48649717
                    OnAuthenticationFailed = context =>
                    {
                        this._logger.LogInformation(Log.OpPIS, "JWT authentication failed.");
                        if (this.Environment.IsDevelopment())
                            Debug.Write(context.Exception.Message);
                        return Task.CompletedTask;
                    }
                };
            });

0 个答案:

没有答案