解密Web API中的承载令牌

本文关键字:令牌 Web API 解密 | 更新日期: 2023-09-27 18:05:14

是否有办法在web api项目中读取/解密承载令牌?

我的web api还托管SignalR集线器,这些集线器通过websocket从浏览器调用。与我的普通api调用不同,我不能在这里添加授权头。虽然我可以在查询字符串中发送令牌,并在SignalR hub中读取。

默认情况下,令牌由owin解析为声明标识。我需要的是手动操作。我该怎么做呢?

    OAuthAuthorizationServerOptions serverOptions = new OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(Config.TokenLifetime),
        Provider = new AuthProvider()
    };
    // Token Generation
    app.UseStageMarker(PipelineStage.Authenticate); // wait for authenticate stage, so we get the windows principle for use with ntlm authentication
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    app.UseOAuthAuthorizationServer(serverOptions);

解密Web API中的承载令牌

我假设在Startup.cs中您有类似于以下代码:

var oAuthOpt = new OAuthBearerAuthenticationOptions
{
    Provider = new OAuthTokenProvider(
        req => req.Query.Get("bearer_token"),
        req => req.Query.Get("access_token"),
        req => req.Query.Get("refresh_token"),
        req => req.Query.Get("token"),
        req => req.Headers.Get("X-Token"))
};
app.UseOAuthBearerAuthentication(OAuthOpt);
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
    AllowInsecureHttp = true,
    TokenEndpointPath = new PathString(settings.TokenEndpointBasePath),
    AccessTokenExpireTimeSpan = Util.AccessTokenExpireTimeSpan,
    Provider = new AuthorizationServerProvider(new AuthenticationService()),
});

你要做的是将oAuthOpt替换为Startup.cs中的公共静态字段,然后在需要取消对承载令牌的保护时使用它。

对于SignalR,我正在创建一个授权属性,在那里我使用oAuthOpt并使用它解码令牌。

我是这样做的:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class AuthorizeHubAttribute : AuthorizeAttribute
{
    public override bool AuthorizeHubConnection (HubDescriptor hubDescriptor, IRequest request)
    {
        var token = request.QueryString["Authorization"];
        var ticket = Startup.OAuthOpt.AccessTokenFormat.Unprotect(token);
        if ( ticket != null && ticket.Identity != null && ticket.Identity.IsAuthenticated )
        {
            request.Environment["server.User"] = new ClaimsPrincipal(ticket.Identity);
            return true;
        }
        else
            return false;
    }
    public override bool AuthorizeHubMethodInvocation (IHubIncomingInvokerContext hubIncomingInvokerContext, bool appliesToMethod)
    {
        var connectionId = hubIncomingInvokerContext.Hub.Context.ConnectionId;
        var environment = hubIncomingInvokerContext.Hub.Context.Request.Environment;
        var principal = environment["server.User"] as ClaimsPrincipal;
        if ( principal != null && principal.Identity != null && principal.Identity.IsAuthenticated )
        {
            hubIncomingInvokerContext.Hub.Context = new HubCallerContext(new Microsoft.AspNet.SignalR.Owin.ServerRequest(environment), connectionId);
            return true;
        }
        else
            return false;
    }
}

var ticket = Startup.OAuthOpt.AccessTokenFormat.Unprotect(token);

这一行是与Startup.cs的连接