I upgraded to .Net6 from .Net5 and now my token is stored in double quotes and I cannot validate calls to the API from my blazor server app

Viewed 157

I upgraded my WebAPI and Blazor Server side projects from NET5 to NET6 and now I cannot validate my JWT Token. It gets stored with double quotes in local storage

** My JWTHandler Class used to create token **

public class JwtHandler
    {
        private readonly IConfiguration _configuration;
        private readonly IConfigurationSection _jwtSettings;
        private readonly IConfigurationSection _googleSettings;
        private readonly UserManager<ApplicationUser> _userManager;
        public JwtHandler(IConfiguration configuration, UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
            _configuration = configuration;
            _jwtSettings = _configuration.GetSection("JWT");
            _googleSettings = _configuration.GetSection("Google");
        }

        private SigningCredentials GetSigningCredentials()
        {
            var key = Encoding.ASCII.GetBytes(_jwtSettings.GetSection("Secret").Value);
            var secret = new SymmetricSecurityKey(key);

            return new SigningCredentials(secret, SecurityAlgorithms.HmacSha256Signature);
        }

        private async Task<List<Claim>> GetClaims(ApplicationUser user)
        {
            var claims = new List<Claim>
            {
                 new Claim(ClaimTypes.Name, user.UserName),
                 new Claim(ClaimTypes.NameIdentifier, user.Id),
                 new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };

            var roles = await _userManager.GetRolesAsync(user);
            foreach (var role in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }

            return claims;
        }

        private JwtSecurityToken GenerateTokenOptions(SigningCredentials signingCredentials, List<Claim> claims)
        {
            var tokenOptions = new JwtSecurityToken(
                issuer: _jwtSettings.GetSection("ValidIssuer").Value,
                audience: _jwtSettings.GetSection("ValidAudience").Value,
                claims: claims,
                expires: DateTime.Now.AddMinutes(Convert.ToDouble(_jwtSettings.GetSection("ExpiryInMinutes").Value)),
                signingCredentials: signingCredentials);

            return tokenOptions;
        }

        public async Task<string> GenerateToken(ApplicationUser user)
        {
            var signingCredentials = GetSigningCredentials();
            var claims = await GetClaims(user);
            var tokenOptions = GenerateTokenOptions(signingCredentials, claims);
            var token = new JwtSecurityTokenHandler().WriteToken(tokenOptions);

            return token;
        }

        public async Task<GoogleJsonWebSignature.Payload> VerifyGoogleToken(ExternalAuthDto externalAuth)
        {
            try
            {
                var settings = new GoogleJsonWebSignature.ValidationSettings()
                {
                    Audience = new List<string>() { _googleSettings.GetSection("ClientId").Value }
                };

                var payload = await GoogleJsonWebSignature.ValidateAsync(externalAuth.IdToken, settings);
                return payload;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }

** My Code used to store to local storage **

 _interceptor.MonitorEvent();
                var response = await client.PostAsJsonAsync("Authenticate/login", loginModel);
                var result = await response.Content.ReadFromJsonAsync<AuthenticatedModel>();

                if (response.IsSuccessStatusCode)
                {
                    var token = result.token;

                    await _locStorage.SetItemAsync("AuthToken", token);

                    ((AuthStateProvider)_authStateProvider).NotifyUserAuthentication(token);

                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

                    showAuthenticationError = false;
                    loginIsSuccessful = true;

                    this.NavToPage();
}

** The code that returns an invalid token exception **

 var token = await _locStorage.GetItemAsStringAsync("AuthToken");

            var client = _clientFactory.CreateClient("meta");
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

                _interceptor.MonitorEvent();
                user = await client.GetFromJsonAsync<UserModel>("User/DashDetails");
                var tempDashs = (ICollection<DashboardsDTO>)await client.GetFromJsonAsync<IEnumerable<DashboardsDTO>>("User/Dashboards");
             

The code above was working just fine before I upgraded from NET5 to NET6

1 Answers

I don't think the solution I have used is the best, if a way to prevent the adding of the double quotes is found please advise.

My solution, : I changed the AuthenticatedHeaderValue token as follows in the code that returns an invalid token exception

From: client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

To: client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Trim('"'));

Related