在Hangfire的IDashboardAuthorizationFilter中解码access_token

时间:2019-01-30 14:08:31

标签: c# asp.net-web-api2 jwt hangfire webapi2

我使用了thisthat链接来使用令牌保护我的WebApi2。当我进行身份验证时,它会发出类似以下内容的响应:

{
    ".expires": "Wed, 30 Jan 2019 14:14:44 GMT",
    ".issued": "Wed, 30 Jan 2019 13:44:44 GMT",
    "access_token": "ZYQm9txvb_fVqYo8Be-NQzC1o3DQM3HYwIdi_2aDNazXW3x9BlYwXqGLBf_Ptqv3azR6uSzhp3_CIjPGGDuolmC0Z1PaHOZJKHn7DJHVnJlMN4FYlE_oCAA1HgM1sWYY97-a21gUNsGLdVCA1UNVo_u2E52ef-sl9-2aOTMJcrJli--waNBBKVok5aP_H4ufdAdxkGTGYrvdTU9Tm2zduadsGeeifI522QY8EwwDNQ2T-6A9_yBuI0yRT-B-TzayUevKvITkZZBKbMAMJNDNQC_dvqiZeaVlKiaxLZsnZ6V1t49nEDQ58pXmDqfdWIF88sbcQXFR_zt5Rly7znL8bWCY1OEuLcF_wH-NHnuyd7PCTT0cxUNu75Vz0wlM5SidxqoJ1KBi2I64IqPvXEObf5NXJb9QP3ZKOGWKtHqaanj9dOS2URGfY8VxfQDpkaMc",
    "as:client_id": "5F6617AD-3364-41EB-B0F1-F538C950FA09",
    "expires_in": 1799,
    "refresh_token": "4d7e77c8c0cf4cc2bc417a6166c07d4d,
    "token_type: "bearer"
}

当我调用授权的api方法时,我需要将access_token作为Bearer令牌附加到我的请求中-因此它可以正常工作。现在,我想使用此令牌来授权对Hangfire仪表板的访问。从服务器获取令牌后,我将其保存为token_cookie在cookie中。然后在服务器端,我尝试像这样读取它:

public class CustomAuthorizationFilter : IDashboardAuthorizationFilter
{
    public bool Authorize(DashboardContext context)
    {
        var cookies = HttpContext.Current.Request.Cookies;

        if (cookies["token_cookie"] != null)
        {
            var jwtCookie = cookies["token_cookie"];
            var jwtToken = jwtCookie.Value;
            var handler = new JwtSecurityTokenHandler();
            var token = handler.ReadToken(jwtToken);
            // check if user is in admin role etc.
        }
        return false;
    }
}

访问令牌具有与客户端上相同的值。但是,ReadToken方法会引发错误:

  

IDX12741:JWT:“ [PII隐藏]”必须具有三个网段(JWS)或   五段(JWE)。

如何读取此令牌以访问用户声明?由于Authorize属性可在我的控制器上使用,因此jwt中间件似乎可以某种方式读取它。我想念什么吗?

我的身份验证配置如下:

private static void AddJwtAuthentication(IAppBuilder app)
{
    var OAuthServerOptions = new OAuthAuthorizationServerOptions
    {
        AllowInsecureHttp = false,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
        Provider = new SimpleAuthorizationServerProvider(),
        RefreshTokenProvider = new SimpleRefreshTokenProvider(),
    };

    // Token Generation
    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}

0 个答案:

没有答案