【问题标题】:Give response to JWT wrong Authentication Asp.Net Core Web Api响应 JWT 错误的 Authentication Asp.Net Core Web Api
【发布时间】:2019-06-25 18:16:06
【问题描述】:

我已经申请了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】:

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

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

    它与您的方法上的 [Authorize] 数据注释一起使用,并且仅在传递有效令牌时同时使用。

    稍后您可以提取声明并在

    上执行验证
    HttpContext.User.Identity as ClaimsIdentity;
    

    你可以检查一下...如果它有帮助 link1link2

    【讨论】:

    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2019-09-07
    相关资源
    最近更新 更多