简体   繁体   English

ASP.NET 核心 3+ JWT 认证

[英]ASP.NET Core 3+ JWT authentication

Been spending a few days lately getting into how to protect a ASP.NET Core Web API/Web App with JWT authentication and/or OIDC.最近花了几天时间研究如何使用 JWT 身份验证和/或 OIDC 保护 ASP.NET 内核 Web API/Web 应用程序。

I have so far been unable to find proper documentation to the two(?) different middleware extensions ( .AddOpenIdConnect and .AddJwtBearer ).到目前为止,我一直无法找到两个(?)不同中间件扩展( .AddOpenIdConnect.AddJwtBearer )的正确文档。 From googling and experimenting I have arrived at the assumption that the former supports the full OIDC dance (validation, redirecting to authority etc., suitable for a web app) whereas the latter is used for JWT validation only (more suitable for an API).通过谷歌搜索和实验,我得出假设前者支持完整的 OIDC 舞蹈(验证、重定向到权限等,适用于 web 应用程序),而后者仅用于 JWT 验证(更适合 API)。

What articles I have found are all recipes, focused on how to configure for a specific id provider, such as Azure or IdentityServer4, but I have found almost nothing that actually dives into how these component behaves and how each configurable option affects that behavior.我发现的文章都是秘籍,重点是如何为特定的 id 提供程序进行配置,例如 Azure 或 IdentityServer4,但我几乎没有发现任何真正深入研究这些组件的行为以及每个可配置选项如何影响该行为的文章。 My company uses its own id provider for authentication and issuing JWT tokens so most recipes I find only provides the occasional hint, not real understanding.我的公司使用自己的 id 提供者进行身份验证和颁发 JWT 令牌,所以我发现的大多数食谱只提供偶尔的提示,而不是真正的理解。

I realize documentation must exist but I haven't been able to find anything beyond the skeleton doc provided by Microsoft on docs.microsoft.com.我意识到文档必须存在,但除了 Microsoft 在 docs.microsoft.com 上提供的骨架文档之外,我找不到任何东西。

Would really appreciate more in-detail information for how to use these two middlewares;非常感谢有关如何使用这两个中间件的更多详细信息; not specifically for a named id provider, but more generally:不是专门针对命名的 id 提供者,而是更一般地说:

  • Is my assumption correct, that .AddOpenIdConnect performs both JWT validation and supports the OIDC dance, automatically redirecting to the authority, token issuer etc?我的假设是否正确,即.AddOpenIdConnect执行 JWT 验证并支持 OIDC 舞蹈,自动重定向到权限、令牌颁发者等?
  • Is the middleware dependent on cookie auth;中间件是否依赖于cookie auth; ie can I omit the .AddCookie setup?即我可以省略.AddCookie设置吗?
  • Would it ever make sense to use both middleware components ( .AddOpenIdConnect and .AddJwtBearer )?使用这两个中间件组件( .AddOpenIdConnect.AddJwtBearer )是否有意义?
  • Please describe the behavior of each component, and how the options affect that behavior.请描述每个组件的行为,以及选项如何影响该行为。
  • What are the required options that have to be specified and which ones are optional?必须指定哪些必需选项以及哪些选项是可选的?
  • Is there a need to interact with the OAuth2 "dance" (via events) or are those there for debugging and response/redirect customization only?是否需要与 OAuth2“舞蹈”(通过事件)进行交互,还是仅用于调试和响应/重定向自定义?

AddOpenIdConnect is as you say responsible for the oauth dance, to authenticate user and to create the user session.正如您所说,AddOpenIdConnect 负责 oauth 舞蹈,对用户进行身份验证并创建用户 session。 It handle everything internally, so you dont need to involve the events unless you need to customize it.它在内部处理所有事情,因此您不需要涉及事件,除非您需要自定义它。

You typcically use AddOpenIdConnect with AddCookie, so that AddCookie is responsble for the user session cookie.您通常将 AddOpenIdConnect 与 AddCookie 一起使用,以便 AddCookie 负责用户 session cookie。 AddOpenIdConnect is only used for the challenge part of the user login flow. AddOpenIdConnect 仅用于用户登录流程的质询部分。

AddJwtBearer is only for for API/services that receives and authenticate tokens, it will only do valdidation of the token and create a ClaimsPrincipal user based on the token. AddJwtBearer 仅用于接收和验证令牌的 API/服务,它只会对令牌进行验证并基于令牌创建 ClaimsPrincipal 用户。

you can use both in the same service, but I recommend that you don't because it can get really complex to figure out what is going on.您可以在同一个服务中同时使用两者,但我建议您不要这样做,因为弄清楚发生了什么会变得非常复杂。 Keep it simple and follow the single responsibility principle and you are good to go.保持简单并遵循单一责任原则,您对 go 很好。 (ie, put them in different services) (即,将它们放在不同的服务中)

A typical AddJwtBearer setup can look like this:典型的 AddJwtBearer 设置如下所示:

.AddJwtBearer(opt =>
{
    opt.Authority = "https://localhost:6001";
    opt.Audience = "paymentapi";

    opt.TokenValidationParameters.RoleClaimType = "roles";
    opt.TokenValidationParameters.NameClaimType = "name";
    opt.TokenValidationParameters.ClockSkew = TimeSpan.FromSeconds(0);


    // IdentityServer emits a typ header by default, recommended extra check
    opt.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
});

A typical AddOpenIdConnect setup can look like this:典型的 AddOpenIdConnect 设置如下所示:

    .AddOpenIdConnect(options =>
{
    options.AccessDeniedPath = "/User/AccessDenied";
    options.Authority = _configuration["openid:authority"];
    options.ClientId = _configuration["openid:clientid"];
    options.ClientSecret = "mysecret";
    options.ResponseType = "code";

    options.Scope.Clear();
    options.Scope.Add("openid");
    options.Scope.Add("profile");
    options.Scope.Add("email");
    options.Scope.Add("employee");
    options.Scope.Add("payment");
    options.Scope.Add("offline_access");

    options.GetClaimsFromUserInfoEndpoint = true;
    options.SaveTokens = true;
    options.Prompt = "consent";

    options.TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = JwtClaimTypes.Name,
    };


});

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

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