ASP.NET Core WebAPI Cookie + JWT身份验证 [英] ASP.NET Core WebAPI Cookie + JWT Authentication

查看:134
本文介绍了ASP.NET Core WebAPI Cookie + JWT身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个带有API后端(ASP.NET Core WebAPI)的SPA(角度):

we have a SPA (Angular) with API backend (ASP.NET Core WebAPI):

SPA在 app.mydomain.com 上侦听,在 app.mydomain.com/API

SPA is listens on app.mydomain.com, API on app.mydomain.com/API

我们使用内置的 Microsoft.AspNetCore.Authentication.JwtBearer 的JWT进行身份验证;我有一个创建令牌的控制器 app.mydomain.com/API/auth/jwt/login .SPA将它们保存到本地存储中.所有作品都很完美.经过安全审核后,我们被告知要为cookie切换本地存储.

We use JWT for Authentication with built-in Microsoft.AspNetCore.Authentication.JwtBearer; I have a controller app.mydomain.com/API/auth/jwt/login which creates tokens. SPA saves them into local storage. All works perfect. After a security audit, we have been told to switch local storage for cookies.

问题是,SPA会使用 app.mydomain.com/API 上的API,移动应用程序和一些客户的服务器2服务器解决方案也会使用该API.

The problem is, that API on app.mydomain.com/API is used by SPA but also by a mobile app and several customers server-2-server solutions.

因此,我们必须保持JWT不变,但要添加Cookies.我发现了几篇文章,它们结合了Cookie和JWT在不同的控制器上,但是我需要它们在每个控制器上并排工作.

So, we have to keep JWT as is, but add Cookies. I found several articles which combines Cookies and JWT on different controllers, but I need them work side-by-side on each controller.

如果客户端发送cookie,请通过cookie进行身份验证.如果客户端发送JWT承载,请通过JWT进行身份验证.

If client sends cookies, authenticate via cookies. If client sends JWT bearer, authenticate via JWT.

这是通过内置的ASP.NET身份验证或DIY中间件实现的吗?

Is this achievable via built-in ASP.NET authentication or DIY middleware?

谢谢!

推荐答案

好的,我已经尝试了一段时间了,我通过以下代码解决了使用jwt身份验证令牌和Cookie身份验证的相同问题.

Okay, I have been trying achieving this for a while and i solved same issue of using jwt Authentication Tokens and Cookie Authentication with the following code.

API服务提供商 UserController.cs

这通过(Cookie和JWT承载)身份验证方案为用户提供不同的服务

This Provide Different Services to the User with Both (Cookie and JWT Bearer)Authentication Schemes

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] 
[Route("[controller]")]
[ApiController]
public class UsersController : ControllerBase
{ 
    private readonly IUserServices_Api _services;
    public UsersController(IUserServices_Api services)
    {
        this._services = services;
    }
     
    [HttpGet]
    public IEnumerable<User> Getall()
    {
        return _services.GetAll();
    }
}

我的 Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
          
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
         
        services.AddAuthentication(options => {
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
            .AddCookie(options =>
            {
                options.LoginPath = "/Account/Login";
                options.AccessDeniedPath = "/Home/Error";
            })
            .AddJwtBearer(options =>
            {
                options.SaveToken = true;
                options.RequireHttpsMetadata = false;
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidAudience = " you site link blah blah",
                    ValidIssuer = "You Site link Blah  blah",
                    IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(sysController.GetSecurityKey()))
                    ,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero
                };
            });

    }

此外,如果您想为特定控制器进行自定义身份验证那么您必须为授权指定身份验证类型像:

And further if you want custom Authentication for a specific Controller then you have to specify the Authentitcation Type for the Authorization like:

[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
public IActionResult Index()
{
    return View();    // This can only be Access when Cookie Authentication is Authorized.
}

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public IActionResult Index()
{
    return View();    // And this one will be Access when JWT Bearer is Valid
}

这篇关于ASP.NET Core WebAPI Cookie + JWT身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆