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
4 Replies
Unknown User•11mo ago
Message Not Public
Sign In & Join Server To View
is that login method inside a controller or is it in a service layer?
Unknown User•11mo ago
Message Not Public
Sign In & Join Server To View
is this for blazor? Once the session starts and signal r kicks in there isn't an http context any longer. You have to catch it before it goes away or iirc the right way is to use AuthenticationStateProvider.