Web Api Blog

 
 
 

We will be understanding Token based security in Asp.net core web api through series of blog post.

Understanding JWT Token based security using a diagram.

Simple JWT

Step 1

Create a Asp.net core web api project in Visual Studio.


Step 2

Add new empty api controller and named it "AccountController".


Step 3

Add Login action method as below:

Note: In order to keep the example simple, I am using hard-code user validation. We will learn how to replace that logic with actual user validation in next post.

[AllowAnonymous]
[HttpPost]
[Route("api/Account/login")]
public IActionResult Login([FromBody] LoginRequest request)
{
    //Todo:  Replace if condition with actual user validation logic
    if (request.Username == "User1" && request.Password == "password")
    {
        //Todo:  Bring this key from appsettings.json file or some where more maintainable.
        var securityKey = "SomeSupperSecretKey_AIzaSyClzfrOzB818x55FASHvX4JuGQciR9lv7q";
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: "yourdomain.com",
            audience: "yourdomain.com",             
            expires: DateTime.Now.AddMinutes(30),
            signingCredentials: creds);

        return Ok(new
        {
            token = new JwtSecurityTokenHandler().WriteToken(token)
        });
    }

    return BadRequest("Could not verify username and password");
}

Step 4

Let's test it using Postman rest client and make sure everything is working as expected.

Test JWT token creation using postman

Next we will understand, how to validate JWT token and call the actual resource api.


 
 
Didn't find what you were looking for? Find more on Simplest way to generate Jwt token in Asp.net core Web Api