Asp.Net Core Web Api - Using both BASIC and JWT Authentication

Cenk 1,036 Reputation points
2022-12-22T05:01:41.477+00:00

Hello,

Can I use both BASIC and JWT in my controller? If so can you show me an example, please?

Thank you.

Developer technologies ASP.NET ASP.NET Core
{count} votes

1 answer

Sort by: Most helpful
  1. Cenk 1,036 Reputation points
    2022-12-23T13:20:14.463+00:00

    I followed your JWT tutorial. But the token somehow doesn't expire, how can I fix it?

    Here is the Program.cs:

     builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>  
        {  
            options.RequireHttpsMetadata = false;  
            options.SaveToken = true;  
            options.TokenValidationParameters = new TokenValidationParameters()  
            {  
                ValidateIssuer = true,  
                ValidateAudience = true,  
                ValidateLifetime = true,  
                ValidAudience = builder.Configuration["Jwt:Audience"],  
                ValidIssuer = builder.Configuration["Jwt:Issuer"],  
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))  
            };  
        });  
    

    Here is the token controller:

    [Route("api/token")]  
        [ApiController]  
        public class TokenController : Controller  
        {  
            private readonly IUserValidate _userValidate;  
            private readonly IConfiguration _config;  
      
      
            public TokenController(IUserValidate userValidate, IConfiguration config)  
            {  
                _userValidate = userValidate;  
                _config = config;  
            }  
      
            [HttpPost]  
            public async Task<IActionResult> Post([FromForm]string username, [FromForm] string password)  
            {  
                if (username != null && password != null)  
                {  
                    var user = _userValidate.Login(username, password);  
                    if (user)  
                    {  
                        //create claims details based on the user information  
                        var claims = new[] {  
                            new Claim(JwtRegisteredClaimNames.Sub, _config["Jwt:Subject"]),  
                            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),  
                            new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),  
                            //new Claim("UserId", _company.customerID.ToString()),  
                            new Claim("DisplayName", username),  
                            new Claim("UserName", username),  
                            //new Claim("Email", _company.Email)  
                        };  
      
                        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));  
                        var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);  
                        var token = new JwtSecurityToken(  
                            _config["Jwt:Issuer"],  
                            _config["Jwt:Audience"],  
                            claims,  
                            expires: DateTime.UtcNow.AddMinutes(1),  
                            signingCredentials: signIn);  
      
                        return Ok(new JwtSecurityTokenHandler().WriteToken(token));  
                    }  
                    else  
                    {  
                        return BadRequest("Invalid credentials");  
                    }  
                }  
                else  
                {  
                    return BadRequest();  
                }  
            }  
        }  
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.