我最近刚学习web api,所以写的一token认证比较简单
1、新建一个web api的项目
2、打开Provides中的这个类
3、在这个类的GrantResourceOwnerCredentials方法中进行认证修改
4、注释掉这个方法中的东西,自己写认证
UserDomain user = new UserDomain(new UserRepository());
var login = user.Login(new LoginModel()
{
UserEmail = context.UserName,
UserPassword = context.Password
});
if(login.Status)
{
//var identity = new ClaimsIdentity(context.Options.AuthenticationType);
//identity.AddClaim(new Claim("username", model.UserName));
ClaimsIdentity claimsIdentity = new ClaimsIdentity(new List<Claim> {
new Claim("Id", login.UserId.ToString()),
new Claim(ClaimTypes.Role, login.RoleId.ToString()),
}, OAuthDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties("Lian");
AuthenticationTicket ticket = new AuthenticationTicket(claimsIdentity, properties);
context.Validated(ticket);
}
else
{
context.SetError("invalid_grant", "用户名或密码不正确。");
return;
}
wo写的里边连接了SQL server数据库
5、在用到这个认证的controller或者action或者...中添加[Authorize]