【问题标题】:Jwt Authentication for just web api .net core web api仅用于 web api .net 核心 web api 的 Jwt 身份验证
【发布时间】:2020-07-20 03:53:26
【问题描述】:

我的应用程序中有两个身份,一个用于管理仪表板(asp.net core mvc),它使用身份类的默认身份验证,我有另一个用于移动服务的身份.Net Core web api,我在本节中使用 jwt auth . 我如何将 jwt 的 authroize 属性用于 web api 控制器,而不是所有控制器,另一个控制器必须使用默认配置。 我的启动类中有这个配置:

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,
                    };
                });

对于我的 api 控制器:

[HttpGet("getUsers")]
        [Authorize]
        public IActionResult GetUsers()
        {..}

【问题讨论】:

    标签: c# authentication asp.net-core jwt asp.net-core-webapi


    【解决方案1】:

    您可以为 MVC 操作和 API 端点使用不同的基本控制器,并使用 AuthorizeAttribute 为每个控制器定义不同的身份验证方案。

    https://docs.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-3.1#selecting-the-scheme-with-the-authorize-attribute

    例子:

    [Authorize(Policy = CookieAuthenticationDefaults.AuthenticationScheme)]
    public abstract class MvcControllerBase : Controller
    {
    
    }
    
    [Authorize(Policy = JwtBearerDefaults.AuthenticationScheme)]
    public abstract class ApiControllerBase : ControllerBase
    {
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-25
      • 2017-07-30
      • 2020-12-22
      • 2021-06-11
      • 2017-03-09
      • 2017-05-23
      相关资源
      最近更新 更多