khauvannam
My HttpContext.User always return null
My HttpContext.User always return null
I have login method that implement login logic and return accessToken, refreshToken
public async Task<LoginResponseDto> Login(LoginDto loginDto)
{
var user = _context.Users.FirstOrDefault(e => e.Email == loginDto.Email);
if (user is null)
throw new Exception("The user is not valid");
var result = await _signInManager.PasswordSignInAsync(
user.UserName,
loginDto.Password,
true,
false
);
if (!result.Succeeded)
{
return new LoginResponseDto()
{
IsLoginSuccessful = false,
ErrorMessage = "Invalid Authentication"
};
}
var claims = await _userManager.GetClaimsAsync(user);
var accessToken = _jwtHandler.GenerateAccessToken(claims);
var refreshToken = _jwtHandler.GenerateRefreshToken();
return new LoginResponseDto() { AccessToken = accessToken, RefreshToken = refreshToken };
}
}
Then i create post and assign the property post.UserId by getting it from httpcontext
public async Task<Post> CreatePost(CreatePostDto createPostDto)
{
var userId = _contextAccessor.HttpContext.User.FindFirstValue(
nameof(ClaimTypes.NameIdentifier)
);
var post = _mapper.Map<CreatePostDto, Post>(createPostDto);
if (createPostDto is { FileUpload: not null })
{
var filePath = await GenerateFilePath(createPostDto.FileUpload);
post.MainImage = filePath;
}
post.UserId = userId;
_context.Posts.Add(post);
await _context.SaveChangesAsync();
return post;
}
I have authorize in swagger the access token and have tested this token in jwt and it work fine
6 replies