繁体   English   中英

Jwt Authentication for just web api .net core web api

[英]Jwt Authentication for just web api .net core web api

I have two identities in my app one for admin dashboard (asp.net core mvc) and it uses default authentication by identity class and i have another identity.Net Core web api for mobile services and i using in this section jwt auth. 我如何使用 jwt 的 authroize 属性用于 web api 控制器仅不适用于所有控制器,另一个 Z594C3C18DAZ03F2C031E00 必须使用默认配置。 我的启动 class 中有这个配置:

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 controller:

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

您可以为 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
{

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM