JWT Bearer Token

Anonymous
2022-10-20T06:59:22.797+00:00

How do I create bearer token and dybamically pass to getMessage , note this example works well with Postman

https://github.com/KalyanAllam/JWTAuth

app.MapGet("/security/getMessage", () => "Hello World!").RequireAuthorization();
app.MapPost("/security/createToken",
[AllowAnonymous] (User user) =>
{
if (user.UserName == "joydip" && user.Password == "joydip123")
{
var issuer = builder.Configuration["Jwt:Issuer"];
var audience = builder.Configuration["Jwt:Audience"];
var key = Encoding.ASCII.GetBytes
(builder.Configuration["Jwt:Key"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim("Id", Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Email, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti,
Guid.NewGuid().ToString())
}),
Expires = DateTime.UtcNow.AddMinutes(5),
Issuer = issuer,
Audience = audience,
SigningCredentials = new SigningCredentials
(new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha512Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var jwtToken = tokenHandler.WriteToken(token);
var stringToken = tokenHandler.WriteToken(token);
return Results.Ok(stringToken);
}
return Results.Unauthorized();
});

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,649 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,731 Reputation points
    2022-10-20T16:26:19.827+00:00

    you question is not clear. the client would call your createToken to get the token and pass to the get message

    var token = await fetch("https://localhost/security/createToken", {   
        headers: {   
          'Accept': 'application/json',   
          'Content-Type': 'application/json'   
        },   
        method: "POST",   
        body: JSON.stringify({userName: "joydip", password: "joydip123"})   
    }).then(r => r.json());   
       
    var message = await fetch("https://localhost/security/message", {   
        headers: {   
          'Accept': 'application/json',   
          'Authorization': 'Bearer ' + token,   
        }   
    }).then(r => r.json());   
       
    console.log(message);   
       
    
    0 comments No comments