How to create backend application using Asp.net C# Web API Core

coder rock 216 Reputation points
2024-05-17T06:22:52.4166667+00:00

How to create backend application using web api core application followed by standards

using desing pattern, Depedency injection and solid principle

I am new to web api core how to start following things

  1. JWT token authentical and authorization
  2. simple role base login there will two roles 1)admin and 2)user
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,269 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,350 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,436 questions
0 comments No comments
{count} votes

Accepted answer
  1. Brando Zhang-MSFT 3,201 Reputation points Microsoft Vendor
    2024-05-17T08:11:04.2133333+00:00

    Hi @coder rock,

    If you want to use JWT auth inside the web api, you need firstly install the jwt package:

    Microsoft.AspNetCore.Authentication.JwtBearer
    

    Then you could add the jwt auth related codes inside the program.cs and add app.UseAuthentication(); middleware:

    Like below, if you want you could modify the Issuer, audience, signingkey by yourself:

    var builder = WebApplication.CreateBuilder(args);
    // Add services to the container.
    builder.Services.AddControllers();
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = "your-issuer",
                ValidAudience = "your-audience",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("xxxxxxxassaaaaaaasdddxxxxxxxxxxxxxxxx"))
            };
        });
    var app = builder.Build();
    // Configure the HTTP request pipeline.
    app.UseHttpsRedirection();
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapControllers();
    app.Run();
    

    Then inside the user controller we could generate the token and use that token to access the protected web api method.

    Please notice: My sample doesn't contain the username and password verify, you could modify the codes to verify username and password based on the request body and then set the user role based on the username inside the GenerateJwtToken method.

        [Route("api/[controller]")]
        [ApiController]
        public class UserController : ControllerBase
        {
    
            [HttpPost("authenticate")]
            public async Task<IActionResult> Authenticate()
            {
                //Here you could pass user to generatejwttoeknmethod to generate the token based on the user
                var token = GenerateJwtToken( );
     
                if (token == null)
                    return BadRequest(new { message = "Username or password is incorrect" });
    
                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 = "your-issuer",
                    Audience = "your-audience",
                    Expires = DateTime.UtcNow.AddDays(7),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
           
                var token = tokenHandler.CreateToken(tokenDescriptor);
                return tokenHandler.WriteToken(token);
            }
    
            public async Task<IActionResult> Register( )
            {
                return Ok();
            }
    
    
            [HttpGet]
            [Authorize(Roles = "Admin")]
            public async Task<IActionResult> GetAll()
            {
                 
                return Ok("success");
            }
        }
    
    

    Test Result:

    Authencation:

    User's image

    Access admin role api method:

    User's image

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful