在我的基于 Web Api 2.2 OWIN 的应用程序中,我遇到了一种情况,我需要手动解码不记名 token ,但我不知道如何执行此操作。 这是我的 startup.cs
public class Startup
{
public static OAuthAuthorizationServerOptions OAuthServerOptions { get; private set; }
public static UnityContainer IoC;
public void Configuration(IAppBuilder app)
{
//Set Auth configuration
ConfigureOAuth(app);
....and other stuff
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new AuthProvider(IoC.Resolve<IUserService>(), IoC.Resolve<IAppSettings>())
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
在我的 Controller 中,我将不记名 token 作为参数发送
[RoutePrefix("api/EP")]
public class EPController : MasterController
{
[HttpGet]
[AllowAnonymous]
[Route("DC")]
public async Task<HttpResponseMessage> GetDC(string token)
{
//Get the claim identity from the token here
//Startup.OAuthServerOptions...
//..and other stuff
}
}
如何手动解码并从作为参数传递的 token 中获取声明?
注意:我知道我可以在 header 中发送 token 并使用 [Authorize] 和 (ClaimsIdentity)User.Identity 等,但问题是当 token 未出现在 header 。
最佳答案
只是把它放在这里供将来可能访问的其他人使用。在 https://long2know.com/2015/05/decrypting-owin-authentication-ticket/ 找到解决方案更简单。
只有两行:
var secureDataFormat = new TicketDataFormat(new MachineKeyProtector());
AuthenticationTicket ticket = secureDataFormat.Unprotect(accessToken);
private class MachineKeyProtector : IDataProtector {
private readonly string[] _purpose =
{
typeof(OAuthAuthorizationServerMiddleware).Namespace,
"Access_Token",
"v1"
};
public byte[] Protect(byte[] userData)
{
throw new NotImplementedException();
}
public byte[] Unprotect(byte[] protectedData)
{
return System.Web.Security.MachineKey.Unprotect(protectedData, _purpose);
} }
关于c# - 在 C# 中手动解码 OAuth 不记名 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40800238/