0
votes

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:

  1. How and where to set HttpClient header (with my token) only one time when user login
  2. 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..

1

1 Answers

0
votes

How and where to set HttpClient header (with my token) only one time when user login

As far as I know, we couldn't set the httpclient header only one time when user login. Normally, we could store the token into session or cookie and then read it from cookie or session when you want to send request to web api.

How to force users stay at the Login page if they aren't login yet

For this requirement, I suggest you could consider using the authentication middleware to achieve your requirement.

You could check the user's session inside this middleware, if this user doesn't contains the session then you could modify the request path to login page.

More details, you could refer to below example:

      //Below cods should add after app.usesession in startup.cs Configure method
      app.Use((context, next) =>
        {
            string token = context.Session.GetString("token");
            if (token == null)
            {
                context.Request.Path = "/account/login";
            }               
            return next.Invoke();
        });