DotNet Core 3.1 MVC JWT authentication for Identity

Heinrich Ludike 121 Reputation points
2021-05-27T09:11:53.41+00:00

100194-image.png
I have an application that I am working on, we are using JWT for our WebAPI and then we have a very simple frontend. The problem I have is the moment I enable my JWTBearer in startup.cs and run my application it refuses to log in. It does not return a JWT object and I can do nothing further.

This is what my code looks like in startup.cs
100155-image.png

I think I might be missing something in startup.cs but I am unable to find it at the moment.

Microsoft Identity Manager
Microsoft Identity Manager
A family of Microsoft products that manage a user's digital identity using identity synchronization, certificate management, and user provisioning.
610 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,158 questions
0 comments No comments
{count} votes

Accepted answer
  1. Heinrich Ludike 121 Reputation points
    2021-05-27T11:16:48.723+00:00

    My function to create the token

    private async Task<string> GenerateJSONWebToken(AppUser user)
    {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
        var userRoles = await _userManager.GetRolesAsync(user);
    
        var authClaims = new List<Claim>
        {
             new Claim(ClaimTypes.Name, user.UserName),
             new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        };
    
        foreach (var userRole in userRoles)
        {
            authClaims.Add(new Claim(ClaimTypes.Role, userRole));
        }
    
        var token = new JwtSecurityToken(_config["Jwt:Issuer"],
          _config["Jwt:Issuer"],
          authClaims,
          expires: DateTime.Now.AddMinutes(120),
          signingCredentials: credentials);
    
        return new JwtSecurityTokenHandler().WriteToken(token);
    }
    

1 additional answer

Sort by: Most helpful
  1. AgaveJoe 26,201 Reputation points
    2021-05-27T10:15:43.353+00:00

    You did not share code that creates the JWT or persists the token. Below is an example service to create the JWT in a Web API application. Can you explain the MVC security design? Are you using an authentication cookie to persist claims/roles or are you using a JavaScript application to persist the JWT? Can you explain your Web API security intent?

    namespace JwtService.Services
    {
        public interface IApplicationUser
        {
            string Authenticate(string username, string password);
            LoginResponse AuthenticateMvc(string username, string password);
        }
    
        public class ApplicationUser : IApplicationUser
        {
            private readonly IConfiguration Configuration;
            public ApplicationUser(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            private List<User> _users = new List<User>
            {
                new User { Id = 1, FirstName = "Hello", LastName = "World", Username = "username", Password = "password" }
            };
    
            public string Authenticate(string username, string password)
            {
                var user = _users.SingleOrDefault(x => x.Username == username && x.Password == password);
    
                // return null if user not found
                if (user == null)
                    return null;
    
                // authentication successful so generate jwt token
                var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.ASCII.GetBytes(Configuration["JwtConfig:secret"]);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, user.Id.ToString()),
                    }),
                    IssuedAt = DateTime.UtcNow,
                    Expires = DateTime.UtcNow.AddDays(7),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
                    Issuer = "Issuer",
                    Audience = "Audience"
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);
                return tokenHandler.WriteToken(token);
            }
    
            public LoginResponse AuthenticateMvc(string username, string password)
            {
                var user = _users.SingleOrDefault(x => x.Username == username && x.Password == password);
    
                // return null if user not found
                if (user == null)
                    return null;
    
                // authentication successful so generate jwt token
                var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.ASCII.GetBytes(Configuration["JwtConfig:secret"]);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, user.Id.ToString()),
                    }),
                    IssuedAt = DateTime.UtcNow,
                    Expires = DateTime.UtcNow.AddDays(7),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
                    Issuer = "Issuer",
                    Audience = "Audience"
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);
    
                //Mock response
                LoginResponse response = new LoginResponse()
                {
                    token = tokenHandler.WriteToken(token),
                    role = "User",
                    claims = new List<ClaimDto>()
                    {
                        new ClaimDto() {type = ClaimTypes.Role, value = "UserRole" },
                        new ClaimDto() {type= ClaimTypes.Email, value = "email@email.com" }
                    }
                };
    
                return response;
    
            }
        }
    }