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" } }; }
接下来在TokenAuthController.cs中添加如下方法
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" }); } }
接下来我们来完成授权部分,在相同的文件中添加如下代码:
public string GetUserInfo() { var claimsIdentity = User.Identity as ClaimsIdentity; return JsonConvert.SerializeObject(new RequestResult { State = RequestState.Success, Data = new { UserName = claimsIdentity.Name } }); }
为方法添加装饰属性
[HttpGet]
[Authorize("Bearer")]
第二行代码说明这个action需要身份验证。
该文件完整的代码应该是这个样子:
using System; using System.Collections.Generic; using System.Linq;using Microsoft.AspNetCore.Mvc; using CSAuthorAngular2InASPNetCore.Auth; using System.IdentityModel.Tokens.Jwt; using Newtonsoft.Json; using System.Security.Claims; using System.Security.Principal; using Microsoft.IdentityModel.Tokens; using CSAuthorAngular2InASPNetCore.Model; using Microsoft.AspNetCore.Authorization; namespace CSAuthorAngular2InASPNetCore.Controllers { [Route("api/[controller]")] public class TokenAuthController : Controller { [HttpPost] public string GetAuthToken([FromBody]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 RequestResult { State = RequestState.Success, Data = new { requertAt = requestAt, expiresIn = TokenAuthOption.ExpiresSpan.TotalSeconds, tokeyType = TokenAuthOption.TokenType, accessToken = token } }); } else { return JsonConvert.SerializeObject(new RequestResult { State = RequestState.Failed, Msg = "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); } [HttpGet] [Authorize("Bearer")] public string GetUserInfo() { var claimsIdentity = User.Identity as ClaimsIdentity; return JsonConvert.SerializeObject(new RequestResult { State = RequestState.Success, Data = new { UserName = claimsIdentity.Name } }); } } 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" } }; } }
4.2Angular2端
4.2.1创建View Model
在wwwroot/app下创建一个目录:_model, 并添加一个Typescript文件RequestResult.ts,内容应该是这样。
export class RequestResult { State: number; Msg: string; Data: Object; }
4.2.2创建Service
在wwwroot/app下创建一个目录:_services,并添加一个Typescript文件auth.service.ts,内容应该是这样。