在ASP.NET Core中实现一个Token base的身份认证实例(3)

private string GenerateToken(User user, DateTime expires) { var handler = new JwtSecurityTokenHandler(); ClaimsIdentity identity = new ClaimsIdentity( new GenericIdentity(user.Username, "TokenAuth"), new[] { new Claim("ID", user.ID.ToString()) } ); var securityToken = handler.CreateToken(new SecurityTokenDescriptor { Issuer = TokenAuthOption.Issuer, Audience = TokenAuthOption.Audience, SigningCredentials = TokenAuthOption.SigningCredentials, Subject = identity, Expires = expires }); return handler.WriteToken(securityToken); }

该方法仅仅只是生成一个Auth Token,接下来我们来添加另外一个方法来调用它

在相同文件中添加如下代码

[HttpPost] public string GetAuthToken(User user) { var existUser = UserStorage.Users.FirstOrDefault(u => u.Username == user.Username && u.Password == user.Password); if (existUser != null) { var requestAt = DateTime.Now; var expiresIn = requestAt + TokenAuthOption.ExpiresSpan; var token = GenerateToken(existUser, expiresIn); return JsonConvert.SerializeObject(new { stateCode = 1, requertAt = requestAt, expiresIn = TokenAuthOption.ExpiresSpan.TotalSeconds, accessToken = token }); } else { return JsonConvert.SerializeObject(new { stateCode = -1, errors = "Username or password is invalid" }); } }

该文件完整的代码应该是这样

using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Security.Principal; using Microsoft.IdentityModel.Tokens; using CSTokenBaseAuth.Auth; namespace CSTokenBaseAuth.Controllers { [Route("api/[controller]")] public class TokenAuthController : Controller { [HttpPost] public string GetAuthToken(User user) { var existUser = UserStorage.Users.FirstOrDefault(u => u.Username == user.Username && u.Password == user.Password); if (existUser != null) { var requestAt = DateTime.Now; var expiresIn = requestAt + TokenAuthOption.ExpiresSpan; var token = GenerateToken(existUser, expiresIn); return JsonConvert.SerializeObject(new { stateCode = 1, requertAt = requestAt, expiresIn = TokenAuthOption.ExpiresSpan.TotalSeconds, accessToken = token }); } else { return JsonConvert.SerializeObject(new { stateCode = -1, errors = "Username or password is invalid" }); } } private string GenerateToken(User user, DateTime expires) { var handler = new JwtSecurityTokenHandler(); ClaimsIdentity identity = new ClaimsIdentity( new GenericIdentity(user.Username, "TokenAuth"), new[] { new Claim("ID", user.ID.ToString()) } ); var securityToken = handler.CreateToken(new SecurityTokenDescriptor { Issuer = TokenAuthOption.Issuer, Audience = TokenAuthOption.Audience, SigningCredentials = TokenAuthOption.SigningCredentials, Subject = identity, Expires = expires }); return handler.WriteToken(securityToken); } } public class User { public Guid ID { get; set; } public string Username { get; set; } public string Password { get; set; } } public static class UserStorage { public static List<User> Users { get; set; } = new List<User> { new User {ID=Guid.NewGuid(),Username="user1",Password = "user1psd" }, new User {ID=Guid.NewGuid(),Username="user2",Password = "user2psd" }, new User {ID=Guid.NewGuid(),Username="user3",Password = "user3psd" } }; } }

接下来我们来完成授权验证部分

在Controllers中新建一个Web API Controller Class,命名为ValuesController.cs

在其中添加如下代码

public string Get() { var claimsIdentity = User.Identity as ClaimsIdentity; var id = claimsIdentity.Claims.FirstOrDefault(c => c.Type == "ID").Value; return $"Hello! {HttpContext.User.Identity.Name}, your ID is:{id}"; }

为方法添加装饰属性

[HttpGet] [Authorize("Bearer")] 完整的文件代码应该是这样 using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using System.Security.Claims; namespace CSTokenBaseAuth.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { [HttpGet] [Authorize("Bearer")] public string Get() { var claimsIdentity = User.Identity as ClaimsIdentity; var id = claimsIdentity.Claims.FirstOrDefault(c => c.Type == "ID").Value; return $"Hello! {HttpContext.User.Identity.Name}, your ID is:{id}"; } } }

最后让我们来添加视图

在Controllers中新建一个Web Controller Class,命名为LoginController.cs

其中的代码应该是这样

using Microsoft.AspNetCore.Mvc; namespace CSTokenBaseAuth.Controllers { [Route("[controller]/[action]")] public class LoginController : Controller { public IActionResult Index() { return View(); } } }

在项目Views目录下新建一个名为Login的目录,并在其中新建一个Index.cshtml文件。

代码应该是这个样子

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjywjg.html