c# - 在 C# 中手动解码 OAuth 不记名 token

标签 c# asp.net-web-api oauth-2.0 owin bearer-token

在我的基于 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/

相关文章:

c# - 如何确保 UWP 应用程序在启动时始终全屏显示?

c# - MVC 和 WebAPI "Multiple types were found that match the controller named..."

android - 需要使用YouTube API授权Android应用的指南

c# - ASP.NET Web API MVC 4 中带有特殊字符的自定义参数名称

asp.net-web-api - 为什么 web api(RestFul) .Net Core 服务不接受参数中的正斜杠,如何解决此问题

web-services - 关于 OAuth 2.0 : Are 3rd Party Cookies Enabled a dependency?

oauth-2.0 - 换码成功后谷歌返回给我的id token应该如何使用?

c# - 正则表达式匹配 lookbehind 和 lookahead 命名组

c# - 从分隔字符串填充 Dictionary<String,String> 的最 'elegant' 方法

c# - 单元测试异步方法 C#