Identity 2.0 Web API为客户端生成令牌

时间:2014-09-22 23:20:25

标签: c# asp.net asp.net-web-api asp.net-identity asp.net-identity-2

我正在开发ASP.NET Web API应用程序。我需要通过登录和密码验证用户,并返回字符串令牌作为响应。我需要让属性[Authorize]正常工作。

我试图调查,如何使用BearerToken机制,但没有任何成功。请提供工作代码示例。

2 个答案:

答案 0 :(得分:7)

您需要配置授权服务器(在您的情况下是您的授权服务器和资源服务器)来颁发访问令牌并使用它们。 这可以使用Owin中间件通过定义和终止点来完成,您应该使用grant_type = password将用户凭据(资源所有者流)发送给它。因此,AS将验证这些凭据并为您提供与您配置的过期日期相关联的访问令牌。

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);
        //Rest of code is here;
    }

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

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

    }
}

现在您需要定义名为SimpleAuthorizationServerProvider的类并验证方法GrantResourceOwnerCredentials中的凭据,如下代码所示:

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

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        using (AuthRepository _repo = new AuthRepository())
        {
            IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
        }

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

        context.Validated(identity);

    }
}

我强烈建议您阅读我的post here,了解您正在安装的组件以及此流程的工作原理。

答案 1 :(得分:2)

按照this article逐步说明哪些软件包添加到解决方案中,并在OWIN上提供虚假的OAuth实现。