未设置DefaultAuthenticateScheme

未设置DefaultAuthenticateScheme

本文介绍了未设置DefaultAuthenticateScheme的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在启动时像这样设置DefaultAuthenticateScheme

I set DefaultAuthenticateScheme on startup like this

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultSignInScheme =  JwtBearerDefaults.AuthenticationScheme;
});

所以,我应该使用类似这样的东西:

So, I should use something like this :

 [Authorize]
 public IEnumerable<UserViewModel> Get()
 {
    return someData;
 }

但是我不得不写这段代码

But I had to write this code

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public IEnumerable<UserViewModel> Get()
    {
        return somedata;
    }

我用谷歌搜索这个问题,我注意到在启动时使用AddCookie或在AddMVC()之后使用AddAuthentication()时应该会发生,但是我不是这种情况.

I google the problem and I notice it should happen when using AddCookie or use AddAuthentication() after AddMVC() in startup, but they are not my case.

推荐答案

默认情况下,它将使用基于cookie的身份验证方案,直到您明确指定为止. Asp .Net Core允许使用AuthenticationSchemes的组合.您需要稍微修改startup.cs,以从Authorize属性中删除AuthenticationSchemes.

By default it will use cookie based auth scheme, until you specify explicitly. As Asp .Net Core allows to use combination of AuthenticationSchemes. You need to slightly modify your startup.cs to remove AuthenticationSchemes from Authorize attribute.

services
    .AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(cfg =>
    {
        cfg.RequireHttpsMetadata = false;
        cfg.SaveToken = true;
        cfg.Audience = "http://localhost:5111/";
        cfg.TokenValidationParameters = new TokenValidationParameters
        {
            // token config
        };
    });

这行代码cfg.Audience = "http://localhost:5111/";将设置您为该特定受众(主机)设置的默认身份验证方案.

This line of code cfg.Audience = "http://localhost:5111/"; will set default auth scheme you set up for that particular audience (host).

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

它将为特定的控制器使用指定的AuthenticationSchemes,而不管其默认设置如何.

It will use the specified AuthenticationSchemes for that particular controller regardless of default.

这篇关于未设置DefaultAuthenticateScheme的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 10:14