GVKun编程网logo

asp.net-core – options的用途.AutomaticAuthenticate with UseJwtBearerAuthentication(asp.net core优点)

16

对于想了解asp.net-core–options的用途.AutomaticAuthenticatewithUseJwtBearerAuthentication的读者,本文将提供新的信息,我们将详细介

对于想了解asp.net-core – options的用途.AutomaticAuthenticate with UseJwtBearerAuthentication的读者,本文将提供新的信息,我们将详细介绍asp.net core优点,并且为您提供关于.net – IAuthenticationFilter.OnAuthenticationChallenge()的目的是什么、Asp.net core Authentication and Authorization、ASP.NET Core JWTAuthentication 和 Authorize 角色声明、asp.net webapi UseOAuthBearerAuthentication vs UseJwtBearerAuthentication的有价值信息。

本文目录一览:

asp.net-core – options的用途.AutomaticAuthenticate with UseJwtBearerAuthentication(asp.net core优点)

asp.net-core – options的用途.AutomaticAuthenticate with UseJwtBearerAuthentication(asp.net core优点)

在将代码库从ASP 5 beta 7更新到RC1-final之后,我开始从JwtBearer中间件接收此异常

Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'System.IConvertible'.

到目前为止我可以看到的决定因素似乎是选项的设置.AutomaticAuthenticate.如果这是真的,那么我得到例外,否则,我没有.

什么是AutomaticAuthenticate,为什么我需要启用它?

app.UseJwtBearerAuthentication(options =>
    {
        options.AutomaticAuthenticate = true; 
    }

这是完整的堆栈跟踪:

at System.Convert.ToInt32(Object value,IFormatProvider provider)
   at System.IdentityModel.Tokens.Jwt.JwtPayload.GetIntClaim(String claimType)
   at System.IdentityModel.Tokens.Jwt.JwtPayload.get_Nbf()
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.Validatetoken(String token,TokenValidationParameters validationParameters,SecurityToken& validatedToken)
   at Microsoft.AspNet.Authentication.JwtBearer.JwtBearerHandler.<HandleAuthenticateAsync>d__1.MoveNext()
--- End of stack trace from prevIoUs location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptiondispatchInfo.Throw()
   at Microsoft.AspNet.Authentication.JwtBearer.JwtBearerHandler.<HandleAuthenticateAsync>d__1.MoveNext()
--- End of stack trace from prevIoUs location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNet.Authentication.AuthenticationHandler`1.<InitializeAsync>d__48.MoveNext()
--- End of stack trace from prevIoUs location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from prevIoUs location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Api.Startup.<<Configure>b__9_0>d.MoveNext() in ...\Startup.cs:line 156

更新根本原因

我们的代码库正在为nbf,exp和iat创建重复声明.这就解释了为什么get_Nbf在堆栈跟踪中以及关于“JArray”的抱怨,因为每个值都是数组而不是值.

解决方法

如果设置为true,则中间件将在每个入站请求上运行,查找JWT令牌,如果存在,则将验证它,如果有效则从中创建标识并将其添加到当前用户.

如果它没有发生,那么您需要通过在authorize属性中指定承载的方案来请求中间件设置标识.

[Authorize(AuthenticationSchemes = "YourBearerSchemeName")]

或者你在政策中设置这个;

options.AddPolicy("RequireBearer",policy =>
{
    policy.AuthenticationSchemes.Add("YourBearerSchemeName");
    policy.RequireAuthenticatedUser();

});

因此,通过将其设置为false,您实际上并没有运行持有者的东西,直到您要求它为止,您只是将异常关闭直到稍后.

.net – IAuthenticationFilter.OnAuthenticationChallenge()的目的是什么

.net – IAuthenticationFilter.OnAuthenticationChallenge()的目的是什么

我在RegisterGlobalFilters()中注册了自定义 IAuthenticationFilter实现.在我的项目中,我正在目睹以下呼叫序列:

> IAuthenticationFilter.OnAuthentication
>授权(如果有的话)
>控制器动作
> IAuthenticationFilter.OnAuthenticationChallenge

为什么在控制器动作之后会发生?从this blog post开始,我读到了

The key thing to remember is that OnAuthenticationChallenge does not
necessarily run before every other Action Filter. It can run at
varIoUs stages.

如果我们无法判断它究竟何时被调用,它怎么有用呢?

解决方法

Source

“只要请求失败了操作方法的身份验证或授权策略,MVC框架就会调用OnAuthenticationChallange方法.OnAuthenticationChallenge方法传递一个AuthenticationChallengeContext对象,该对象派生自ControllerContext类”

所以,一个实际的例子是:

1 – 您设置自定义授权过滤器

2 – 用户在授权方法上失败

调用3 – OnAuthenticationChallenge方法.

Asp.net core Authentication and Authorization

Asp.net core Authentication and Authorization

之前有写过关于这些的文章, 本来想认证写一个系类的,但是感觉非常大. 太多工了.

先记入一些零零散散的. 看看以后要不要整理起来。

 

refer resources : 

https://www.cnblogs.com/stulzq 晓晨博客 

https://www.cnblogs.com/sheng-jie/p/9430920.html 圣杰博客 identity server 4 知多少

https://www.cnblogs.com/sheng-jie/p/6564520.html 圣杰博客 oauth 2.0 知多少

 

Access token type, self-contained (self-encoded type) vs reference (identifier type)

access token 有 2 种, 一种是作为一个 reference key, 每当 resource server 拿到 access token 后并不能知道授权的具体信息. 

而是需要用 token 去访问 autho server 获取授权信息. 这个做法的缺点就是每次都要去访问 autho server 性能可能有点伤, 好处就是可以立刻 revoke token

另一种叫 self-contained 当 resource server 拿到 access token 后它自己就可以解锁. 这里用的是不对称加密. 私钥加密,公钥解锁. 

好处就是不用每次去 autho server 咯, 性能快一点, 坏处就是你无法立刻去 revoke token. 而是需要等它自己过期. 所以 access token 就要设置时间段, 而 refresh token 就需要一直去续命. 

oauth 没有规定用哪一种, 建议大家自己去做 balance 权衡.

相关的资源 : 

https://www.oauth.com/oauth2-servers/listing-authorizations/revoking-access/

https://www.oauth.com/oauth2-servers/access-tokens/self-encoded-access-tokens/

https://darutk.medium.com/oauth-access-token-implementation-30c2e8b90ff0

https://docs.wso2.com/m/mobile.action#page/76748735

https://docs.wso2.com/display/IS540/Self-contained+Access+Tokens

 

ASP.NET Core JWTAuthentication 和 Authorize 角色声明

ASP.NET Core JWTAuthentication 和 Authorize 角色声明

我也不确定“权限”是怎么回事,但假设您获得了角色......

您可以简单地以这种方式重构它,并将声明列表添加到您传递给 ClaimsIdentity 的集合中:

        private async Task<string> GenerateJwtToken(UserDto user)
        {
            // generate token that is valid for 7 days
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var claims = new List<Claim>(await FetchClaims(user.UserAccountId)) {
                new Claim("userAccountId",user.UserAccountId.ToString())
            };
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),Expires = DateTime.UtcNow.AddHours(_appSettings.JwtExpiryHours),SigningCredentials =
                    new SigningCredentials(new SymmetricSecurityKey(key),SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }

        private async Task<IEnumerable<Claim>> FetchClaims(int userId)
        {
            var userPermissions = await GetUserPermissionsByUserId(userId);

            return userPermissions
                .Select(x => new Claim(ClaimTypes.Role,x.PermissionName));
        }

(如果需要,您也可以使用 JwtSecurityToken 代替 SecurityTokenDescriptor;它直接接受 IEnumerable<Claim>。)

诚然,我已经有一段时间没有使用角色了,所以如果它不起作用,请告诉我。但是从快速的谷歌搜索来看,向令牌添加多个 Role 声明似乎是合法的。 [编辑:我测试了添加多个角色声明并针对它们进行授权,它对我有用。]

asp.net webapi UseOAuthBearerAuthentication vs UseJwtBearerAuthentication

asp.net webapi UseOAuthBearerAuthentication vs UseJwtBearerAuthentication

任何人都可以解释一下USEOAuthBearerAuthentication和UseJwtBearerAuthentication之间有什么区别?

为什么我应该使用’USEOAuthBearerAuthentication’而不是’UseJwtBearerAuthentication’,反之亦然?

我如何确定哪个选项对我的系统最好?

谢谢,
Szymo

解决方法

当令牌由Identityserver,Auth0等外部OAuth2授权服务器创建时,将使用UseJwtBearerAuthentication中间件.这是标准令牌格式.

当Katana OAuth2授权服务器创建令牌时,使用USEOuthBearerAuthentication中间件.此授权服务器使用专有令牌格式.

UseJwtBearerAuthentication中间件是两者中不错的选择.此中间件使用OpenId Connect规范中指定的令牌格式(JWT).所有外部授权服务器都使用此令牌格式.

谢谢,索玛.

关于asp.net-core – options的用途.AutomaticAuthenticate with UseJwtBearerAuthenticationasp.net core优点的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于.net – IAuthenticationFilter.OnAuthenticationChallenge()的目的是什么、Asp.net core Authentication and Authorization、ASP.NET Core JWTAuthentication 和 Authorize 角色声明、asp.net webapi UseOAuthBearerAuthentication vs UseJwtBearerAuthentication等相关内容,可以在本站寻找。

本文标签: