Asp.net web api 显式令牌验证

Asp.net web api 显式令牌验证,asp.net-web-api,Asp.net Web Api,我正在开发一个Asp.NETWebAPI2项目,我正在使用OAuth。现在我可以生成令牌并将其发送到客户端。现在,我将如何使用jqueryajax调用将该令牌从客户端发送到服务器,并显式地验证该令牌并获取用户信息我没有使用asp.net标识 代码 public class UserModel { public string UserName { get; set; } public string Password { get; set; } pu

我正在开发一个Asp.NETWebAPI2项目,我正在使用OAuth。现在我可以生成令牌并将其发送到客户端。现在,我将如何使用jqueryajax调用将该令牌从客户端发送到服务器,并显式地验证该令牌并获取用户信息我没有使用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);

    }
}
公共类用户模型
{     
公共字符串用户名{get;set;}
公共字符串密码{get;set;}
公共字符串ConfirmPassword{get;set;}
}
公营创业
{
公共无效配置(IAppBuilder应用程序)
{
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
配置OAuth(应用程序);
HttpConfiguration config=新的HttpConfiguration();
WebApiConfig.Register(配置);
app.UseWebApi(配置);
}
公共void配置OAuth(IAppBuilder应用程序)
{
OAuthAuthorizationServerOptions OAuthServerOptions=新的OAuthAuthorizationServerOptions()
{
AllowInsecureHttp=true,
TokenEndpointPath=新路径字符串(“/token”),
AccessTokenExpireTimeSpan=TimeSpan.FromDays(1),
Provider=新的SimpleAuthorizationServerProvider()
};
//令牌生成
使用OAuthAuthorizationServer(OAuthServerOptions);
使用OAuthBeareAuthentication(新的OAuthBeareAuthenticationOptions());
}
}
公共类SimpleAuthorizationServerProvider:OAuthAuthorizationServerProvider
{        
公共覆盖任务ValidateClientAuthentication(OAuthValidateClientAuthenticationContext)
{
//资源所有者密码凭据不提供客户端ID。
if(context.ClientId==null)
{
context.Validated();
}
返回Task.FromResult(空);
}
公共重写异步任务GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentials上下文)
{
使用(AuthRepository\u repo=new AuthRepository())
{
var user=_repo.FindUser(context.UserName,context.Password);
if(user==null)
{
SetError(“无效的授权”,“用户名或密码不正确”);
返回;
}
}
var identity=newclaimsidentity(context.Options.AuthenticationType);
identity.AddClaim(新声明(“sub”,context.UserName));
identity.AddClaim(新声明(“角色”、“用户”));
上下文验证(身份);
}
}

您不需要也不应该手动验证令牌,只需使用
[Authorize]
属性为您保护的API端点添加属性,并将此验证留给框架,如果令牌无效或过期,Web API将返回401,您可以继续

关于从客户端应用程序向服务器发送获得的令牌,您需要在授权头中为您的请求发送令牌,使用承载方案
授权:承载xf7jsjaaa9292….

下面类似的内容会有所帮助

beforeSend: function (xhr) {
    xhr.setRequestHeader ("Authorization", "Bearer YOUR_TOKEN_GOES_HERE");
}
因此,您可以使用jQuery beforeSend回调来添加HTTP授权头

顺便说一句,我猜示例代码来自我的博客,因此请随意删除以下声明,因为它对您的情况没有用处:

identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
并将其替换为以下内容:

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