我想创建一个路由GET api/auth/user
的控制器,以返回当前登录用户的详细信息。我创建了api api/auth/login
,令牌处理在15分钟内到期。那么哪种方法可以返回当前登录用户的ID?
这是我目前的代码:
AUTH-controller.cs:
[Route("api/auth")]
public class AuthController : Controller
{
private readonly IAuthRepository repo;
private readonly IConfiguration config;
private readonly IUserRepository userRepo;
public AuthController(IAuthRepository repo, IConfiguration config, IUserRepository userRepo)
{
this.userRepo = userRepo;
this.config = config;
this.repo = repo;
}
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody]UserForLogin userForLogin)
{
var userFromRepo = await this.repo.Login(userForLogin.Email.ToLower(), userForLogin.Password);
if (userFromRepo == null)
return Unauthorized();
// generate token
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(this.config.GetSection("AppSettings:Token").Value);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
new Claim(ClaimTypes.Name, userFromRepo.Email)
}),
Expires = DateTime.Now.AddMinutes(15),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return Ok(new { tokenString });
}
}
用户repository.cs:
public class UserRepository : IUserRepository
{
private readonly DataContext context;
public UserRepository(DataContext context)
{
this.context = context;
}
public async Task<User> GetUser(int id)
{
return await this.context.User
.AsNoTracking()
.SingleOrDefaultAsync(u => u.Id == id);
}
}
修改 好吧,到目前为止,我在控制器内解决了这个问题:
var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
答案 0 :(得分:3)
以下代码可以检索当前用户详细信息。
var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value
有关详细信息,请参阅here