明确的令牌验证

时间:2014-11-23 06:48:44

标签: asp.net-web-api

我正在开发一个Asp.net web Api 2项目,我正在使用OAuth。现在我能够生成令牌并将其发送给客户端。现在我将如何使用jQuery ajax调用从客户端向服务器发送该令牌,并验证该令牌显式并获取用户信息。 我没有使用asp.net身份

代码

public class UserModel
{     
    public string UserName { get; set; }
    public string Password { get; set; }        
    public string ConfirmPassword { get; set; }
}

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        ConfigureOAuth(app);
        HttpConfiguration config = new HttpConfiguration();
        WebApiConfig.Register(config);            
        app.UseWebApi(config);
    }

    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);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

    }
}

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{        
    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        // Resource owner password credentials does not provide a client ID.
        if (context.ClientId == null)
        {
            context.Validated();
        }

        return Task.FromResult<object>(null);
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        using (AuthRepository _repo = new AuthRepository())
        {
            var user = _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);

    }
}

1 个答案:

答案 0 :(得分:1)

您不需要也不应该手动验证令牌,只需将受保护的API端点归属于[Authorize]属性,并将此验证留给框架,如果令牌无效或过期,Web API将返回401和你很高兴。

关于从客户端应用程序向服务器发送获取的令牌,您需要使用承载方案Authorization: Bearer xf7jsjaaa9292....

在您的请求的授权标头中发送令牌

以下内容将有助于

beforeSend: function (xhr) {
    xhr.setRequestHeader ("Authorization", "Bearer YOUR_TOKEN_GOES_HERE");
}

因此,您可以使用jQuery beforeSend回调来添加HTTP授权标头。

顺便说一下,我想示例代码来自我的博客http://bitoftech.net,因此请随意删除以下声明,因为它对您的案例无效:

identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));

用这个替换它:

identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));