Im new to C# and im struggling with authorization in ASP.Net Core 3.1 MVC web application.I know that there is a lot of instruction on google, i've been reading and watching for 3 days but can not work this out because every instruction i found, it use another way and im really confused.
The idea of my system is:
Step 1. I POST username and password to my API and it'll response with JWT Token (if account is correct)
Step 2. I decode the token and get the username, email, role for my website, set HttpClient header for another requests.
My problems:
- How and where to set HttpClient header (with my token) only one time when user login
- How to force users stay at the Login page if they aren't login yet
Here's my Login method
[HttpPost, AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel account)
{
string url = "accounts/signin";
var response = await new HttpClientHelper<LoginViewModel>().PostRequest(url, account);
var userToken = JsonConvert.DeserializeObject<UserToken>(response);
Console.Out.WriteLine(userToken.Token);
if (userToken.Token != null)
{
var token = new JwtSecurityToken(jwtEncodedString: userToken.Token);
var userId = token.Claims.First(c => c.Type == "userId").Value;
var username = token.Claims.First(c => c.Type == "unique_name").Value;
var role = token.Claims.First(c => c.Type == "role").Value;
HttpContext.Session.SetString("token", token.ToString());
HttpContext.Session.SetString("userId", userId);
HttpContext.Session.SetString("username", username);
HttpContext.Session.SetString("role", role);
return RedirectToAction("Home", "Index");
}
return RedirectToAction("Login", "Login");
}
My model to receive response from api
public class UserToken
{
public string Token { get; set; }
public string ValidFrom { get; set; }
public string ValidTo { get; set; }
}
FYI: Ive already recived the response from api and got the Token, but ive to set HttpClient header every time i make a request..