当前位置: 首页 > 编程语言 > C#

在c#中手动解码OAuth承载令牌分享

时间:2023-04-10 13:10:38 C#

C#学习教程:在c#中手动解码OAuthBearerToken这个怎么做。这是我的startup.cspublicclassStartup{publicstaticOAuthAuthorizationServerOptionsOAuthServerOptions{get;私有集;公共静态UnityContainerIoC;publicvoidConfiguration(IAppBuilderapp){//设置Auth配置ConfigureOAuth(app);....和其他东西}publicvoidConfigureOAuth(IAppBuilderapp){OAuthServerOptions=newOAuthAuthorizationServerOptions(){AllowInsecureHttp=true,TokenEndpointPath=newPathString("/token"),AccessTokenExpireTimeSpan=TimeSpan.FromDays(1),Provider=newAuthProvider(IoC.Resolve(),IoC.Resolve())};//令牌生成app.UseOAuthAuthorizationServer(OAuthServerOptions);app.UseOAuthBearerAuthentication(新的OAuthBearerAuthenticationOptions());}}在我的控制器中,我发送了一个承载命令为参数[RoutePrefix("api/EP")]publicclassEPController:MasterController{[HttpGet][AllowAnonymous][Route("DC")]publicasyncTaskGetDC(stringtoken){//从此处的令牌中获取声明标识//Startup.OAuthServerOptions...//..andotherstuff}}如何手动解码并从作为参数传递的令牌中获取声明?注意:我知道我可以在标头中发送令牌并使用[Authorize]和(ClaimsIdentity)User.Identity等,但问题是当令牌没有出现在标头中时如何读取令牌我创建了一个用于反序列化承载示例令牌项目,使用MachineKeyDataProtector加密。你可以查看源代码。BearerToken-Deserializer把这个放在这里,供以后访问的其他人使用。在https://long2know.com/2015/05/decrypting-owin-authentication-ticket/找到的解决方案更简单。只有2行:varsecureDataFormat=newTicketDataFormat(newMachineKeyProtector());AuthenticationTicketticket=secureDataFormat.Unprotect(accessToken);privateclassMachineKeyProtector:IDataProtector{privatereadonlystring[]_purpose={"Accesstypeof(wareOAutherAuthork_Authorization)","v1"};publicbyte[]Protect(byte[]userData){thrownewNotImplementedException();}publicbyte[]Unprotect(byte[]protectedData){returnSystem.Web.Security.MachineKey.Unprotect(protectedData,_purpose);您可以阅读JWT并使用System.IdentityModel.Tokens.Jwt包创建Principals和Identity对象–https://www.nuget.org/packages/System.IdentityModel.Tokens.Jwt/。这是一个快速示例,显示读取和验证令牌时可用的选项,以上是关于C#学习教程:在C#中手动解码OAuth承载令牌多关于C#学习教程,希望大家多多注意—privateClaimsIdentityGetIdentityFromToken(stringtoken,X509Certificate2certificate){vartokenDecoder=newJwtSecurityTokenHandler();varjwtSecurityToken=(JwtSecurityToken)tokenDecoder.ReadToken(token);SecurityToken验证令牌;varprincipal=tokenDecoder.ValidateToken(jwtSecurityToken.RawData,newTokenValidationParameters(){ValidateActor=false,ValidateIssuer=false,ValidateAudience=false,ValidateLifetime=false,ValidateIssuerSigningKey=false,RequireExpirationTime=false,RequireSignedTokens=false,IssuerSigningToken=newX509SecurityToken(证书)},出validatedToken);返回principal.Identities.FirstOrDefault();}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: