给予回应JWT错误的身份验证Asp.Net核心网络API

问题描述 投票:0回答:1

我已经申请tutorial创造一个asp.net核心web API认证申请。

一切都很好,并运行完美,但如果我通过了错误的授权密钥它不返回任何东西。

我想下面的代码来测试,但我没有得到语境委托。

x.Events.OnChallenge = context =>
                {
                    // Skip the default logic.
                    context.HandleResponse();

                    var payload = new JObject
                    {
                        ["error"] = context.Error,
                        ["error_description"] = context.ErrorDescription,
                        ["error_uri"] = context.ErrorUri
                    };

                    return context.Response.WriteAsync(payload.ToString());
                };

我也想设置自定义错误返回码错误的授权,因此任何帮助,将不胜感激。

提前致谢。

我的配置服务的代码是:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // configure strongly typed settings objects
            var appSettingsSection = Configuration.GetSection("AppSettings");
            services.Configure<AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get<AppSettings>();
            var key = Encoding.ASCII.GetBytes(appSettings.Secret);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })

            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

            // configure DI for application services
            services.AddScoped<IUserService, UserService>();
        }
asp.net-core authorization jwt asp.net-core-webapi
1个回答
1
投票

它不会工作,因为在startup.cs文件,你会使用

app.UseJwtBearerAuthentication(new JwtBearerOptions()
{//other stuff}

这与你的方法[授权]数据标注,并同时只有当有效令牌传递工作。

稍后,您可以提取索赔和执行验证

HttpContext.User.Identity as ClaimsIdentity;

您可以检查此...如果它有助于link1link2

© www.soinside.com 2019 - 2024. All rights reserved.