Blazor get jwt token on sign in or register

blazor

Question

I have to get the response of a token coming form a asp.net webapi which is like this

return new JwtSecurityTokenHandler().WriteToken(token);

and from the Blazor login page

    private async Task LoginEmisor()
{
    var response = await http.PostJsonAsync<Emisor>("api/Emisors/Login",emisor);
    Storage["token"] = response.Token;
    Console.WriteLine(response.Token);
}

And I get a serialization error because the response is expecting an Emisor object and not the Token that I actually want to get. As a workaround I added a string Token property to Emisor class

            emisor.Token = token.ToString();
            return emisor;

and return the whole Emisor with the token as Property, and that way I was able to get it and store it in local storage. But I think that is not the right way to do it, I think I have to be able to get the token without being part of Emisor

Accepted Answer

I've made an extenstion method for this purpose:

    public static async Task<string> SendJsonAsyncRawResult(this HttpClient httpClient, HttpMethod httpMethod, string requestUri, object content)
    {
        var requestJson = JsonUtil.Serialize(content);
        var response = await httpClient.SendAsync(new HttpRequestMessage(httpMethod, requestUri)
        {
            Content = new StringContent(requestJson, Encoding.UTF8, "application/json")
        });

        return await response.Content.ReadAsStringAsync();

    }

and then use it like this:

        var obj = new { username, password };
        var token = await _http.SendJsonAsyncRawResult(HttpMethod.Post, "api/token", obj);

Also available on nuget



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow