public string GetUserInfo() { var claimsIdentity = User.Identity as ClaimsIdentity; return JsonConvert.SerializeObject(new RequestResult { State = RequestState.Success, Data = new { UserName = claimsIdentity.Name } }); }
为方法添加装饰属性
[HttpGet] [Authorize()]
第二行代码说明这个action需要身份验证。
该文件完整的代码应该是这个样子:
using System; using System.Collections.Generic; 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()] 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 = }); } } private string GenerateToken(User user, DateTime expires) { var handler = new JwtSecurityTokenHandler(); ClaimsIdentity identity = new ClaimsIdentity( ), new[] { , 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()] 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; } } UserStorage { public static List<User> Users { get; set; } = new List<User> { ,Password = }, ,Password = }, ,Password = } }; } }
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,内容应该是这样。