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

Evg*_*aya 4 c# asp.net asp.net-web-api asp.net-identity asp.net-identity-2

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

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

Tai*_*deh 8

您需要配置授权服务器(在您的情况下是您的授权服务器和资源服务器)来发出访问令牌并使用它们.这可以使用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());

    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您需要定义已命名的类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);

    }
}
Run Code Online (Sandbox Code Playgroud)

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