首页 » SEO优化 » phpinipost转移技巧_ASPNET Core 认证与授权系列4JwtBearer认证

phpinipost转移技巧_ASPNET Core 认证与授权系列4JwtBearer认证

duote123 2024-12-10 0

扫一扫用手机浏览

文章目录 [+]

目录

Bearer认证JWT(JSON WEB TOKEN)头部(Header)载荷(Payload)署名(Signature)示例仿照Token注册JwtBearer认证添加受保护资源运行扩展自定义Token获取办法利用OIDC做事源码探索JwtBearerPostConfigureOptionsJwtBearerHandlerBearer认证

HTTP供应了一套标准的身份验证框架:做事器可以用来针对客户真个要求发送质询(challenge),客户端根据质询供应身份验证凭据。
质询与应答的事情流程如下:做事器端向客户端返回401(Unauthorized,未授权)状态码,并在WWW-Authenticate头中添加如何进行验证的信息,个中至少包含有一种质询办法。
然后客户端可以在要求中添加Authorization头进行验证,其Value为身份验证的凭据信息。

phpinipost转移技巧_ASPNET Core 认证与授权系列4JwtBearer认证

在HTTP标准验证方案中,我们比较熟习的是"Basic"和"Digest",前者将用户名密码利用BASE64编码后作为验证凭据,后者是Basic的升级版,更加安全,由于Basic是明文传输密码信息,而Digest是加密后传输。
在前文先容的Cookie认证属于Form认证,并不属于HTTP标准验证。

phpinipost转移技巧_ASPNET Core 认证与授权系列4JwtBearer认证
(图片来自网络侵删)

本文要先容的Bearer验证也属于HTTP协议标准验证,它随着OAuth协议而开始盛行,详细定义见: RFC 6570。

A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

Bearer验证中的凭据称为BEARER_TOKEN,或者是access_token,它的颁发和验证完备由我们自己的运用程序来掌握,而不依赖于系统和Web做事器,Bearer验证的标准要求办法如下:

Authorization: Bearer [BEARER_TOKEN]

那么利用Bearer验证有什么好处呢?

CORS: cookies + CORS 并不能跨不同的域名。
而Bearer验证在任何域名下都可以利用HTTP header头部来传输用户信息。
对移动端友好: 当你在一个原平生台(iOS, Android, WindowsPhone等)时,利用Cookie验证并不是一个好主张,由于你得和Cookie容器打交道,而利用Bearer验证则大略的多。
CSRF: 由于Bearer验证不再依赖于cookies, 也就避免了跨站要求攻击。
标准:在Cookie认证中,用户未登录时,返回一个302到登录页面,这在非浏览器情形下很难处理,而Bearer验证则返回的是标准的401 challenge。
JWT(JSON WEB TOKEN)

上面先容的Bearer认证,其核心便是BEARER_TOKEN,而最盛行的Token编码办法便是:JSON WEB TOKEN。

Json web token (JWT), 是为了在网络运用环境间通报声明而实行的一种基于JSON的开放标准(RFC 7519)。
该token被设计为紧凑且安全的,特殊适用于分布式站点的单点登录(SSO)场景。
JWT的声明一样平常被用来在身份供应者和做事供应者间通报被认证的用户身份信息,以便于从资源做事器获取资源,也可以增加一些额外的其它业务逻辑所必须的声明信息,该token也可直接被用于认证,也可被加密。

JWT是由.分割的如下三部分组成:

头部(Header)

Header 一样平常由两个部分组成:

algtyp

alg是是所利用的hash算法,如:HMAC SHA256或RSA,typ是Token的类型,在这里便是:JWT。

{ "alg": "HS256", "typ": "JWT"}

然后利用Base64Url编码成第一部分:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.<second part>.<third part>载荷(Payload)

这一部分是JWT紧张的信息存储部分,个中包含了许多种的声明(claims)。

Claims的实体一样平常包含用户和一些元数据,这些claims分成三种类型:

reserved claims:预定义的 一些声明,并不是逼迫的但是推举,它们包括 iss (issuer), exp (expiration time), sub (subject),aud(audience) 等(这里都利用三个字母的缘故原由是担保 JWT 的紧凑)。
public claims: 公有声明,这个部分可以随便定义,但是要把稳和 IANA JSON Web Token 冲突。
private claims: 私有声明,这个部分是共享被认定信息中自定义部分。

一个大略的Pyload可以是这样子的:

{ "sub": "1234567890", "name": "John Doe", "admin": true}

这部分同样利用Base64Url编码成第二部分:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.<third part>署名(Signature)

Signature是用来验证发送者的JWT的同时也能确保在期间不被修改。

在创建该部分时候你该当已经有了编码后的Header和Payload,然后利用保存在做事真个秘钥对其署名,一个完全的JWT如下:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

因此利用JWT具有如下好处:

通用:由于json的通用性,以是JWT是可以进行跨措辞支持的,像JAVA,JavaScript,NodeJS,PHP等很多措辞都可以利用。
紧凑:JWT的构成非常大略,字节占用很小,可以通过 GET、POST 等放在 HTTP 的 header 中,非常便于传输。
扩展:JWT是自我包涵的,包含了必要的所有信息,不须要在做事端保存会话信息, 非常易于运用的扩展。

关于更多JWT的先容,网上非常多,这里就不再多做先容。
下面,演示一下 ASP.NET Core 中 JwtBearer 认证的利用办法。

示例仿照Token

ASP.NET Core 内置的JwtBearer验证,并不包含Token的发放,我们先仿照一个大略的实现:

[HttpPost("authenticate")]public IActionResult Authenticate([FromBody]UserDto userDto){ var user = _store.FindUser(userDto.UserName, userDto.Password); if (user == null) return Unauthorized(); var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(Consts.Secret); var authTime = DateTime.UtcNow; var expiresAt = authTime.AddDays(7); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(JwtClaimTypes.Audience,"api"), new Claim(JwtClaimTypes.Issuer,"http://localhost:5200"), new Claim(JwtClaimTypes.Id, user.Id.ToString()), new Claim(JwtClaimTypes.Name, user.Name), new Claim(JwtClaimTypes.Email, user.Email), new Claim(JwtClaimTypes.PhoneNumber, user.PhoneNumber) }), Expires = expiresAt, SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return Ok(new { access_token = tokenString, token_type = "Bearer", profile = new { sid = user.Id, name = user.Name, auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(), expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds() } });}

如上,利用微软供应的Microsoft.IdentityModel.Tokens帮助类(源码地址:azure-activedirectory-identitymodel-extensions-for-dotnet),可以很随意马虎的创建出JwtToen,就不再多说。

注册JwtBearer认证

首先添加JwtBearer包引用:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer --version 2.0.0

然后在Startup类中添加如下配置:

public void ConfigureServices(IServiceCollection services){ services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(o => { o.TokenValidationParameters = new TokenValidationParameters { NameClaimType = JwtClaimTypes.Name, RoleClaimType = JwtClaimTypes.Role, ValidIssuer = "http://localhost:5200", ValidAudience = "api", IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Consts.Secret)) /TokenValidationParameters的参数默认值/ // RequireSignedTokens = true, // SaveSigninToken = false, // ValidateActor = false, // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
// ValidateAudience = true, // ValidateIssuer = true, // ValidateIssuerSigningKey = false, // 是否哀求Token的Claims中必须包含Expires // RequireExpirationTime = true, // 许可的做事器韶光偏移量 // ClockSkew = TimeSpan.FromSeconds(300), // 是否验证Token有效期,利用当前韶光与Token的Claims中的NotBefore和Expires比拟 // ValidateLifetime = true }; });}public void Configure(IApplicationBuilder app){ app.UseAuthentication();}

在JwtBearerOptions的配置中,常日IssuerSigningKey(署名秘钥), ValidIssuer(Token颁发机构), ValidAudience(颁发给谁) 三个参数是必须的,后两者用于与TokenClaims中的Issuer和Audience进行比拟,不一致则验证失落败(与上面发放Token中的Claims对应)。

而NameClaimType和RoleClaimType需与Token中的ClaimType同等,在IdentityServer中也是利用的JwtClaimTypes,否则会造成User.Identity.Name为空等问题。

添加受保护资源

创建一个须要授权的掌握器,直策应用Authorize即可:

[Authorize][Route("api/[controller]")]public class SampleDataController : Controller{ [HttpGet("[action]")] public IEnumerable<WeatherForecast> WeatherForecasts() { return ... }}运行

末了运行,直接访问/api/SampleData/WeatherForecasts,将返回一个401:

HTTP/1.1 401 UnauthorizedServer: KestrelContent-Length: 0WWW-Authenticate: Bearer

让我们调用api/oauth/authenticate,获取一个JWT:

要求:POST http://localhost:5200/api/oauth/authenticate HTTP/1.1content-type: application/json{ "username": "alice", "password": "alice"}相应:HTTP/1.1 200 OK{"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJuYW1lIjoiYWxpY2UiLCJlbWFpbCI6ImFsaWNlQGdtYWlsLmNvbSIsInBob25lX251bWJlciI6IjE4ODAwMDAwMDAxIiwibmJmIjoxNTA5NDY0MzQwLCJleHAiOjE1MTAwNjkxNDAsImlhdCI6MTUwOTQ2NDM0MH0.Y1TDz8KjLRh_vjQ_3iYP4oJw-fmhoboiAGPqIZ-ooNc","token_type":"Bearer","profile":{"sid":1,"name":"alice","auth_time":1509464340,"expires_at":1510069140}}

末了利用该Token,再次调用受保护资源:

GET http://localhost:5200/api/SampleData/WeatherForecasts HTTP/1.1Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJuYW1lIjoiYWxpY2UiLCJlbWFpbCI6ImFsaWNlQGdtYWlsLmNvbSIsInBob25lX251bWJlciI6IjE4ODAwMDAwMDAxIiwibmJmIjoxNTA5NDY0MzQwLCJleHAiOjE1MTAwNjkxNDAsImlhdCI6MTUwOTQ2NDM0MH0.Y1TDz8KjLRh_vjQ_3iYP4oJw-fmhoboiAGPqIZ-ooNc

授权成功,返回了预期的数据:

HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8[{"dateFormatted":"2017/11/3","temperatureC":35,"summary":"Chilly","temperatureF":94}]扩展自定义Token获取办法

JwtBearer认证中,默认是通过Http的Authorization头来获取的,这也是最推举的做法,但是在某些场景下,我们可能会利用Url或者是Cookie来通报Token,那要怎么来实现呢?

实在实现起来非常大略,如前几章先容的一样,JwtBearer也在认证的各个阶段为我们供应了事宜,来实行我们的自定义逻辑:

.AddJwtBearer(o =>{ o.Events = new JwtBearerEvents() { OnMessageReceived = context => { context.Token = context.Request.Query["access_token"]; return Task.CompletedTask; } }; o.TokenValidationParameters = new TokenValidationParameters { ... };

然后在Url中添加access_token=[token],直接在浏览器中访问:

同样的,我们也可以很随意马虎的在Cookie中读取Token,就不再演示。

除了OnMessageReceived外,还供应了如下几个事宜:

TokenValidated:在Token验证通过后调用。
AuthenticationFailed: 认证失落败时调用。
Challenge: 未授权时调用。
利用OIDC做事

在上面的示例中,我们大略仿照的Token颁发,功能非常大略,并不适宜在生产环境中利用,可是微软也没有供应OIDC做事的实现,好在.NET社区中供应了几种实现,可供我们选择:

Name

Description

AspNet.Security.OpenIdConnect.Server (ASOS)

Low-level/protocol-first OpenID Connect server framework for ASP.NET Core and OWIN/Katana

IdentityServer4

OpenID Connect and OAuth 2.0 framework for ASP.NET Core - officially certified by the OpenID Foundation and under governance of the .NET Foundation

OpenIddict

Easy-to-use OpenID Connect server for ASP.NET Core

PwdLess

Simple, stateless, passwordless authentication for ASP.NET Core

我们在这里利用IdentityServer4来搭建一个OIDC做事器,并添加如下配置:

/OIDC做事器代码片段/public void ConfigureServices(IServiceCollection services){ services.AddMvc(); // 配置IdentitryServer services.AddIdentityServer() .AddInMemoryPersistedGrants() .AddInMemoryApiResources(Config.GetApis()) .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddInMemoryClients(Config.GetClients()) .AddTestUsers(Config.GetUsers()) .AddDeveloperSigningCredential();}new Client{ ClientId = "jwt.implicit", ClientName = "Implicit Client (Web)", AllowedGrantTypes = GrantTypes.Implicit, AllowAccessTokensViaBrowser = true, RedirectUris = { "http://localhost:5200/callback" }, PostLogoutRedirectUris = { "http://localhost:5200/home" }, AllowedCorsOrigins = { "http://localhost:5200" }, AllowedScopes = { "openid", "profile", "email", "api" },}

而JwtBearer客户真个配置就更加大略了,由于OIDC具有配置创造的功能:

public void ConfigureServices(IServiceCollection services){ services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(o => { o.Authority = "https://oidc.faasx.com/"; o.Audience = "api"; o.TokenValidationParameters = new TokenValidationParameters { NameClaimType = JwtClaimTypes.Name, RoleClaimType = JwtClaimTypes.Role, }; });}

如上,最主要的是Authority参数,用来表示OIDC做事的地址,然后便可以自动创造Issuer, IssuerSigningKey等配置,而o.Audience与o.TokenValidationParameters = new TokenValidationParameters { ValidAudience = "api" }是等效的,后面剖析源码时会先容。

OIDC兼容OAuth2协议,我们可以利用上一章先容的授权码模式来获取Token,也可以直接用户名密码模式来获取Token:

要求:POST https://oidc.faasx.com/connect/token HTTP/1.1Content-Type: application/x-www-form-urlencodedclient_id=client.rop&client_secret=secret&grant_type=password&scope=api&username=alice&password=alice相应:HTTP/1.1 200 OKContent-Type: application/json{"access_token":"eyJhbGciOiJSUzI1NiIsImtpZCI6IjdlYzk5MjVlMmUzMTA2NmY2ZmU2ODgzMDRhZjU1ZmM0IiwidHlwIjoiSldUIn0.eyJuYmYiOjE1MDk2NzI1NjksImV4cCI6MTUwOTY3NjE2OSwiaXNzIjoiaHR0cHM6Ly9vaWRjLmZhYXN4LmNvbSIsImF1ZCI6WyJodHRwczovL29pZGMuZmFhc3guY29tL3Jlc291cmNlcyIsImFwaSJdLCJjbGllbnRfaWQiOiJjbGllbnQucm9wIiwic3ViIjoiMDAxIiwiYXV0aF90aW1lIjoxNTA5NjcyNTY5LCJpZHAiOiJsb2NhbCIsIm5hbWUiOiJBbGljZSBTbWl0aCIsImVtYWlsIjoiQWxpY2VTbWl0aEBlbWFpbC5jb20iLCJzY29wZSI6WyJhcGkiXSwiYW1yIjpbInB3ZCJdfQ.PM93LThOZA3lkgPFVwieqGQQQtgmYDCY0oSFVmudv1hpKO6UaaZsmnn4ci9QjbGl5g2433JkDks5UIZsZ0xE62Qqq8PicPBBuaNoYrCf6dxR7j-0uZcoa7-FCKGu-0TrM8OL-NuMvN6_KEpbWa3jlkwibCK9YDIwJZilVoWUOrbbIEsKTa-DdLScmzHLUzksT8GBr0PAVhge9PRFiGqg8cgMLjsA62ZeDsR35f55BucSV5Pj0SAj26anYvrBNTHKOF7ze1DGW51Dbz6DRu1X7uEIxSzWiNi4cRVJ6Totjkwk5F78R9R38o_mYEdehZBjRHFe6zLd91hXcCKqOEh5eQ","expires_in":3600,"token_type":"Bearer"}

我们利用https://jwt.io解析一下OIDC做事器颁发的Token中的Claims:

{ "nbf": 1509672569, // 2017/11/3 1:29:29 NotBefore Token生效韶光,在此之前不可用 "exp": 1509676169, // 2017/11/3 2:29:29 Expiration Token过期韶光,在此之后不可用 "iss": "https://oidc.faasx.com", // Issuer 颁发者,常日为STS做事器地址 "aud": [ // Audience Token的浸染工具,也便是被访问的资源做事器授权标识 "https://oidc.faasx.com/resources", "api" ], "client_id": "client.rop", // 客户端标识 "sub": "001", "auth_time": 1509672569, // Token颁发韶光 "idp": "local", "name": "Alice Smith", "email": "AliceSmith@email.com", "scope": [ "api" ], "amr": [ "pwd" ]}

我在本章的示例代码中,利用前端Angular框架演示了如何从本地登录获取Tokek或利用简化模式(implicit)从OIDC做事器获取Token,然后保存到sesstionStorage,在发送要求时附加到要求头中的示例,可供大家参考:JwtBearerSample。

源码探索JwtBearerPostConfigureOptions

在ASP.NET Core 2.0 Options框架中,新增了一种PostConfigure模式,用来在我们所注册的Options配置实行完之后,再对Options做一些修正。

JwtBearerPostConfigureOptions用来实现配置创造:

public class JwtBearerPostConfigureOptions : IPostConfigureOptions<JwtBearerOptions>{ public void PostConfigure(string name, JwtBearerOptions options) { // 如果未设置options.TokenValidationParameters.ValidAudience,则利用options.Audience if (string.IsNullOrEmpty(options.TokenValidationParameters.ValidAudience) && !string.IsNullOrEmpty(options.Audience)) { options.TokenValidationParameters.ValidAudience = options.Audience; } if (options.ConfigurationManager == null) { // 如果未设置MetadataAddress,则利用options.Authority+.well-known/openid-configuration .... options.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(options.MetadataAddress, new OpenIdConnectConfigurationRetriever(), new HttpDocumentRetriever(httpClient) { RequireHttps = options.RequireHttpsMetadata }); } } }}JwtBearerHandler

JwtBearerHandler相对付前几章先容的CookieHandler, OpenIdConnectHandler等,都大略的多。

首先便是从要求中获取Token:

protected override async Task<AuthenticateResult> HandleAuthenticateAsync(){ var messageReceivedContext = new MessageReceivedContext(Context, Scheme, Options); // 先触发MessageReceived事宜,来获取Token await Events.MessageReceived(messageReceivedContext); if (messageReceivedContext.Result != null) { return messageReceivedContext.Result; } token = messageReceivedContext.Token; // Token为空时,从Authorization头中获取 if (string.IsNullOrEmpty(token)) { string authorization = Request.Headers["Authorization"]; if (string.IsNullOrEmpty(authorization)) { return AuthenticateResult.NoResult(); } if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) { token = authorization.Substring("Bearer ".Length).Trim(); } if (string.IsNullOrEmpty(token)) { return AuthenticateResult.NoResult(); } } ... }

然后初始化TokenValidationParameters参数,为Token验证做准备:

if (_configuration == null && Options.ConfigurationManager != null){ _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);}var validationParameters = Options.TokenValidationParameters.Clone();if (_configuration != null){ var issuers = new[] { _configuration.Issuer }; validationParameters.ValidIssuers = validationParameters.ValidIssuers?.Concat(issuers) ?? issuers; validationParameters.IssuerSigningKeys = validationParameters.IssuerSigningKeys?.Concat(_configuration.SigningKeys) ?? _configuration.SigningKeys;}

可以看到,从OIDC做事器供应的配置创造中,获取ValidIssuers和IssuerSigningKeys。

末了对Token进行验证:

// Options.SecurityTokenValidators 默认为: new List<ISecurityTokenValidator> { new JwtSecurityTokenHandler() }foreach (var validator in Options.SecurityTokenValidators){ if (validator.CanReadToken(token)) { ClaimsPrincipal principal; try { principal = validator.ValidateToken(token, validationParameters, out validatedToken); } catch (Exception ex) { // RefreshOnIssuerKeyNotFound默认为True, 在SignatureKey未找到时,重新从OIDC做事器获取 if (Options.RefreshOnIssuerKeyNotFound && Options.ConfigurationManager != null && ex is SecurityTokenSignatureKeyNotFoundException) { Options.ConfigurationManager.RequestRefresh(); } continue; } ... // 触发TokenValidated事宜 await Events.TokenValidated(tokenValidatedContext); // 默认为true,保存Token到`AuthenticationProperties`中,可以通过`context.AuthenticateAsync()`来获取,在我们须要在做事端利用用户Token调用其他资源是非常有用。
if (Options.SaveToken) { tokenValidatedContext.Properties.StoreTokens(new[] { new AuthenticationToken { Name = "access_token", Value = token } }); } // 验证成功 tokenValidatedContext.Success(); return tokenValidatedContext.Result; }}

其核心的验证也是在Microsoft.IdentityModel.Tokens中,就不在穷究。

当利用JwtBearer认证时,我们肯定不肯望在未登录时返回一个302,因此在前面的示例中,我们配置了x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;,对应的,会实行JwtBearerHandler的HandleChallengeAsync方法:

protected override async Task HandleChallengeAsync(AuthenticationProperties properties){ var authResult = await HandleAuthenticateOnceSafeAsync(); var eventContext = new JwtBearerChallengeContext(Context, Scheme, Options, properties) { AuthenticateFailure = authResult?.Failure }; if (Options.IncludeErrorDetails && eventContext.AuthenticateFailure != null) { eventContext.Error = "invalid_token"; eventContext.ErrorDescription = CreateErrorDescription(eventContext.AuthenticateFailure); } await Events.Challenge(eventContext); if (eventContext.Handled) { return; } Response.StatusCode = 401; // 终极将相应报文拼接成如下: // https://tools.ietf.org/html/rfc6750#section-3.1 // WWW-Authenticate: Bearer realm="example", error="invalid_token", error_description="The access token expired"}

ASP.NET Core JwtBearer认证的完全源码地址:Microsoft.AspNetCore.Authentication.JwtBearer。

本文示例代码地址:https://github.com/RainingNight/AspNetCoreSample/tree/master/src/Functional/Authentication/JwtBearerSample

总结

JwtToken实在与Cookie认证中加密后的Cookie值很像,他们都是基于Claim的,认证时无需STS(Security token service)的参与,这在分布式环境下供应了极大的便利。
而他们的实质上的差异是:Cookie是微软式的,很难与其他措辞集成,而JwtToken则是开放再开放,与平台,措辞无关,在前端也可以直接解析出Claims。

PS: 在利用在Bearer认证时,常日还需与刷新Token合营来利用,由于JwtToken的验证是无需经由STS的,而当用户实行了退出,修正密码等操作时,是无法使该Token失落效的。
以是,常日会给access_token设置一个较短的有效期(JwtBearer认证默认会验证有效期,通过notBefore和expires来验证),当access_token过期后,可以在用户无感知的情形下,利用refresh_token自动从STS重新获取access_token,但这就不属于Bearer认证的范畴了,在后续先容IdentityServer时再来详细先容一下。

标签:

相关文章

phptp断定标签技巧_php面试题2020

分类专栏: PHP展开一 、PHP根本部分 1、PHP措辞的一大上风是跨平台,什么是跨平台?PHP的运行环境最优搭配为Apache...

SEO优化 2024-12-12 阅读0 评论0