从自定义AuthorizeAttribute中的承载访问令牌获取ClaimsPrincipal

时间:2016-09-15 09:49:27

标签: asp.net-web-api

我可以从嵌入式授权服务器获取承载访问令牌。

问题是当我从WebAPI请求资源时,我无法根据发送的访问令牌取回ClaimsPrincipal。

以下是Http帖子:(1)

GET /api/v1/courses/categories HTTP/1.1
Host: localhost:8080
Authorization: Bearer QoHxP-MbGna2ekhZl-zV9C_3gW2LPBbe-i7DQDp1DFF0BGurjAsqx-rShhmTZlnvScnAdZHNnR1PLcVVuz8B3VwvsYwKKvp-tYw3sohf4B2m5IH97FeCRbA9_nv4DflZtUSSQnrdlKNHHQGgl8VZ5Pcdc09V5hAv5f3sGd-1qsIsKuON81mhlC2PKWNA6a0NTid_LyvzEY1zGQtrgx8ue2NFMNztXBYuy1jXgv6SPAdoOLU3mH38wXg4l7UmVJ10MAbcljNczDSgY9QOC439BmpscG_kIYONiqQaMGMQhmFqnaKIkCMy9PgQ9WvQaLpz
Cache-Control: no-cache
Postman-Token: bd0096e6-3471-bb49-460d-f198f7f516e4

以下是Owin Startup:(2)

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);

        HttpConfiguration config = new HttpConfiguration();
        WebApiConfig.Register(config);
        app.UseWebApi(config);
        app.UseCors(CorsOptions.AllowAll);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
            Provider = new AuthorizationServerProvider(),
        };
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

以下是WebAPI配置:(3)

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        config.Filters.Add(new CustomAuthorizeAttribute());
        config.SuppressDefaultHostAuthentication();
        config.SuppressHostPrincipal();
        config.Formatters.OfType<JsonMediaTypeFormatter>().First().SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }
}

授予访问令牌:(4)

public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        await Task.FromResult(context.Validated());
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType); // using Bearer
        identity.AddClaim(new Claim("AccountId", Guid.NewGuid()));
        context.Validated(identity);
    }
}

最后这是问题部分:(5)

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        // I tried to access the - ((ClaimsPrincipal)actionContext.RequestContext.Principal).Claims
    }
}

我试图访问ClaimsPrincipal但是空了,我需要&#34; AccountId&#34;这是在GrantResourceOwnerCredentials()期间设置的 - 在(4)处查看代码。

0 个答案:

没有答案
相关问题