0

I want to create a controller with route GET api/auth/user to return the detail of currently logged in user. I created api api/auth/login with token handling expired within 15 mins. So which method can return the ID of currently logged in user?

Here is my current code:

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);
    }
  }

EDIT: Alright, so far I got it work around by this within the controller:

var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

Hoàng Nguyễn
  • 1,121
  • 3
  • 33
  • 57
  • 1
    Possible duplicate of [How to get user id of logged in user in .NET Core 2.0?](https://stackoverflow.com/q/46273107) – NightOwl888 Feb 13 '18 at 08:05

1 Answers1

5

Current user details can be retrieved by the below code.

var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value 

For more details refer here

SMR
  • 136
  • 5