Web API 2 - OAuth2拦截授权令牌

时间:2014-06-04 13:06:25

标签: oauth-2.0 asp.net-web-api2

我创建了一个简单的Web服务 - 使用IIS上托管的owin的WebAPI 2 在我的启动文件中

public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
        ConfigureOAuth(app);
        var configuration = new HttpConfiguration();
        WebApiConfig.Register(configuration);
        app.UseWebApi(configuration);
        app.UseCors(CorsOptions.AllowAll);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        var oAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new SimpleAuthorizationServerProvider()
        };

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

    }

并创建了一个带有authorize属性的简单控制器。在身份模型中我添加了当用户调用服务器时我想要读取的信息

var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));
        identity.AddClaim(new Claim("session", "50"));

对于我想要获取会话值的每个请求,有没有办法做到这一点?如何添加中间件来拦截令牌授权过程?

1 个答案:

答案 0 :(得分:3)

你可以在控制器动作中尝试这样的事情:

IPrincipal x = ControllerContext.RequestContext.Principal;
ClaimsIdentity ci = x.Identity as ClaimsIdentity;
string session = ci.FindFirst("session").Value;