![](/img/trans.png)
[英]How to I get the username of the currently logged in user in ASP.NET Core 2, not Application Pool details
[英]ASP.NET Core - How to get currently logged in user
我想使用路由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 });
}
}
user-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);
可以通過以下代碼檢索當前用戶的詳細信息。
var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value
有關更多詳細信息,請參見此處
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.