多重身份验证身份-JWT

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

我有一个项目,其中网络通过身份进行身份验证,我想将 JWT 用于 API。我应该做哪些改变才能同时使用两者?

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

            }).AddCookie(options =>
            {
                options.LoginPath = "/Login";
                options.LogoutPath = "/Logout";
                options.ExpireTimeSpan = TimeSpan.FromMinutes(43200);
            });

同时使用JWT和Identity

c# asp.net asp.net-core jwt asp.net-identity
1个回答
0
投票

您可以尝试以下代码:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
//add cookie scheme
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
//add jwt scheme
                .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>{...}
                     );

//Add a policy called "Jwt_Or_Cookie" to allow either jwt or cookie.
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("Jwt_Or_Cookie", policy =>
    {
        policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
        policy.AuthenticationSchemes.Add(CookieAuthenticationDefaults.AuthenticationScheme);
        policy.RequireAuthenticatedUser();

    });
});

然后你可以使用这个允许这两种方案的策略

        [Authorize(Policy = "Jwt_Or_Cookie")]
        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {...}
© www.soinside.com 2019 - 2024. All rights reserved.