How to build .net core 8 login and role base functionality, authentication and authorization using jwt token

coder rock 296 Reputation points
2024-07-16T20:32:03.8066667+00:00

Hi all

i am new to .net core 8 and implementing login funcationality, authentication and authorization funcationality

for that i have wrote below two methods.

	 [HttpGet("GetLoginDetailsById")]

	 public async Task<ActionResult<LoginDetails>> GetLoginDetailsById(string? Username,string? Password)

	 {

		 //return await _context.LoginDetails.ToListAsync();

		 var logins = await _context.LoginDetails.Where(x => x.Username == Username && x.Password == Password).ToListAsync(); 

		 if (logins == null || logins.Count==0)

			 return BadRequest("User is not valid");

		 var token = GenerateJwtToken();

		 return Ok(token);

	 }



	 private string GenerateJwtToken()

	 {

		 var tokenHandler = new JwtSecurityTokenHandler();

		 var key = Encoding.ASCII.GetBytes("xxxxxxxassaaaaaaasdddxxxxxxxxxxxxxxxx");

		 var tokenDescriptor = new SecurityTokenDescriptor

		 {

			 Subject = new ClaimsIdentity(new[] { new Claim("id", "testuser"), new Claim(ClaimTypes.Role, "Admin") }),

			 Issuer = "https://localhost:7054",

			 Audience = "https://localhost:7054",

			 Expires = DateTime.UtcNow.AddDays(7),

			 SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)

		 };

		 var token = tokenHandler.CreateToken(tokenDescriptor);

		 return tokenHandler.WriteToken(token);

	 }


I am using jwt token for login purpose in above methods

Beow is my model for login


	namespace coreapidotnet8.Models

	{

		public class LoginDetails

		{

			public int Id { get; set; }

			public string Username { get; set; }

			public string Password { get; set; }

			public int RoleId { get; set; }

		}

	}

Below is my application context class

	using Microsoft.EntityFrameworkCore;
	using coreapidotnet8.Models;
	namespace coreapidotnet8.Data

	{

		public class ApplicationDbContext : DbContext

		{

			public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)

				: base(options)

			{

			}

			public DbSet<LoginDetails> LoginDetails { get; set; }

		}

	}


below are my requirements and doubts

1) Is it requires to store token into my logintable? Current in my logintable have columns username password roleid

2) I am giving tokent to expire into 7s day how it will expired? 

3)I have role base login that means RoleId=1 means admin and RoleId=2 is users

4)Front end using angular so for that purpose buildin api for that role base login.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,386 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 61,266 Reputation points
    2024-07-16T23:07:26.41+00:00
    1. no. the angular app might store the token in local storage, if autologin allowed until token expires
    2. your code needs to validate the token. typically the token has an expiration date and an encrypted signature. if the expir date is in past, or bad signature, the token is invalid.
    3. jtw tokens have claims. to add roles, use: new Claim(ClaimTypes.Role, roleName). in your case the name would be "1" or "2", or map the "1" and "2" to a more meaningful names like "User" and "Admin".
    4. not sure the question. the angular code would have a login page, and pass the jwt token as a bearer token.

1 additional answer

Sort by: Most helpful
  1. Brando Zhang-MSFT 3,446 Reputation points Microsoft Vendor
    2024-07-17T02:32:18.0733333+00:00

    Hi @coder rock,

    Is it requires to store token into my logintable? Current in my logintable have columns username password roleid

    It is not required to store the token inside the database. The token is stateless and not stored at server-side. Normally, this token is stored at the client-side(usually in local storage or cookie). The client will send the token and the server will decode the token by checking its signature and claims.

    I am giving tokent to expire into 7s day how it will expired?

    This is a stored as a claim("exp"). When the server validate the token, it will check this value to check if this token is expired or not.

    I have role base login that means RoleId=1 means admin and RoleId=2 is users

    In my opinion, there is no need to store the roleid , you could directly store the role name, and you could directly using the role name to do authorize. If you still want to use the role id, you could try this codes:new Claim(ClaimTypes.Role, user.RoleId == 1 ? "Admin" : "User")

    Front end using angular so for that purpose buildin api for that role base login.

    The token contains the claims, you could set the role for the specific api method to make just specific role could access. Like below:

             [HttpPost]
            [Authorize(Roles = "Users")]
            public IActionResult Test()
            {
                return Ok(new { Test = "Value" });
            }