skip to Main Content

Good day all:

It seems trivial and there are many examples out there but I haven’t found a clear piece of code for such a simple issue.

I have an external WEB API that sends a bearer token after the user authenticates

WEB API CONTROLLER


 public class IdentityController : ControllerBase
    {
        private readonly IIdentityService _identityService;

        public IdentityController(IIdentityService identityService)
        {
            _identityService = identityService;
        }

        [HttpPost("login")]
        public async Task<IActionResult> Login([FromBody] LoginViewModel model) 
        {
            var result = await _identityService.LoginAsync(model);
            if (!string.IsNullOrEmpty(result?.Token))
            {
                return Ok(result);
            }
            return Unauthorized();
        }

        [HttpPost("register")]
        public async Task<IActionResult> Register([FromBody] RegisterViewModel model)
        {
            var result = await _identityService.RegisterAsync(model);
            return Ok(result);
        }

        [HttpPost("register-admin")]
        public async Task<IActionResult> RegisterAdmin([FromBody] RegisterViewModel model)
        {

            var result = await _identityService.RegisterAdminAsync(model);
            return Ok(result);
        }
    }
}

The above works perfectly and the endpoint ( an ASP.NET CORE Web application) receives the token after the user authenticates via the code below.

     [HttpPost]
        public async Task<ActionResult<string>> Login([FromForm] LoginViewModel model)
        {
            var httpClient = _httpClientFactory.CreateClient("HousingWebAPI");           
            var body = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
            using (var posting  = await httpClient.PostAsync("Login/login", body))
            {              
                posting.EnsureSuccessStatusCode();
                var content = await posting.Content.ReadAsStringAsync();                
                return Ok(content);
            }
            return NotFound();
        }

The User receives the code so the above is correct.

The problem:

after a successful authentication, the token should be stored in order to send it in the requests( otherwise they should authenticate every time isn’t it ?). This is my first question How do I safely store my token …there are a lot of options there : Cookies, database, etc. but I haven’t seen a clear example that suits my coding.
Now …let say that I want to send my stored token in the request below. it’s said that I should send it using the httpClient.DefaultRequestHeaders.Authorization, but I don’t have an idea how to do it in the code below.
I know what to do but I don’t know how to achieve it. There are a lot of examples but sometimes too much information confuses.

How to attach the stored token in httpClient.DefaultRequestHeaders.Authorization in this code ???

[HttpPost]
    public async Task<ActionResult<string>> PostData([FromForm] DataTableAjaxPostModel model)
    {
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var body = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
              
        var response = await client.PostAsync("https://localhost:7193/HousingWebAPI/GetData", body);
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            return Ok(content);
        }
        return NotFound();
    }

Searched Forums and YouTube channels but I haven’t seen a clear answer for my post.

2

Answers


  1. As you said, the token could stored in cookie, session, cahce or else.

    But storing in where is based on your application environment.

    Since you are developing a web api login service not a web page login view, which receive the request and send the response to the client. Normally, storing the token is not web api considering things.

    The web api is a restful service and we don’t know which client will send the request to it. If we let the web api to tell client store the token inside the cookie, for some request which is not sent from browser, where to store the cookie?

    For normal login process, it will be a login view to let the user type in the username and password, then the server will tell the browser store the token inside the cookie.

    For web api restful service, this must will be a client which sent the user name and password to your web api and your web api just need to return the token. For how to store the token , this is related with the client. Different client will use different way to store the token.

    If client is the bowser, it will store inside the cookie, if the client is a windows app, it will store it inside the memory or else.

    So based on my opinion, there is no need to consider storing the token.

    Login or Signup to reply.
  2. I think you confused some people here. So, to confirm – your server side is ASP.NET Core WebApi application. And your client is also ASP.NET Core application (like, Blazor). And you are asking how to store JWT in the client after successful authentication. If that’s not the case – let me know and I will correct this answer.

    Typically, browser application store tokens that are returned from the server in browser local storage. And then you send the token during subsequent requests, as you describe. Typically it is done in Authorization header, and not in a cookie. I am not Blazor expert, but here is what seems to be a good description (among many others)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search