【问题标题】:Decrypt Bearer Token in Web API在 Web API 中解密承载令牌
【发布时间】:2017-01-09 09:44:15
【问题描述】:

有没有办法在 web api 项目中读取/解密不记名令牌?

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

默认情况下,令牌由 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);

【问题讨论】:

  • 您是否使用 OAuthBearerAuthenticationOptions 来生成令牌?
  • 一种方法是将身份验证提供程序存储在 owin 启动类的静态变量中,并在需要从令牌中获取声明时调用它。
  • @Nikola.Lukovic:是的
  • 我刚刚将我的配置添加到帖子中
  • @VinceBlack 检查尼古拉斯的回答:)

标签: c# asp.net-web-api signalr bearer-token


【解决方案1】:

我假设在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,我正在创建一个 Authorization 属性,我在其中获取 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的连接

【讨论】:

  • 感谢您的解决方案!不幸的是,它对我来说并不完全有效:在 AuthorizeHubConnection 中,由于某种原因,票证为空。但是,令牌已从请求中正确提取。您的令牌字符串在上面的行中看起来如何?我的格式为'Bearer '
  • 您可以尝试从字符串中删除“Bearer”,然后将其传递给 Unprotect 方法
  • 好的,我刚刚切断了 Bearer 部分,现在它可以工作了!谢谢一百万!
  • 前段时间我也遇到过这个问题,这里是complete GitHub project with authenticating WebApi and SignalR.祝你好运!
猜你喜欢
  • 2018-06-11
  • 1970-01-01
  • 2015-01-02
  • 2015-01-14
  • 2017-01-20
  • 2021-08-13
  • 1970-01-01
  • 2014-10-06
  • 2015-12-25
相关资源
最近更新 更多