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

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

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

返回 null .

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

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

如果方法具有 Authorize 属性(它返回403),但在 AllowAnonymous Controller方法上没有,则这已经有效 .

我想我需要 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;
                    }
                };
            });