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

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.