How to create JWT Token authorization in ASP.NET Core 2.0 Project.

in #utopian-io7 years ago (edited)

Hello

Today I want to present how to make custom JWT Tokens authorization in ASP.NET Core 2.0 project.

image.png

JSON Web Tokens it is an open standard that allows transmitting data between parties as a JSON object in a compact and secure way. They are usually used in authentication and information exchange scenarios.

First of all we have to create new project:

image.png

I'm using Visual Studio 2017 Community.

image.png

At the beginning we have to download and install library with JWT. I recommend you use Nuget.
So, we have to find: Microsoft.AspNetCore.Authentication.JwtBearer it is library from Microsoft to manage JWT.

image.png

Then in our appsetings.json:

image.png

we have to create section witch will be responsible for our Token settings:

{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "Token": {
    "Key": "SuperSecretKey1234%",
    "ExpireMinutes": "5"
  }
} 

Then we have to go to Startup.cs:

image.png

and write this code:

 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidateAudience = false,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                    };
                });

Its mean that we will use authentication and it will be JWT authentication. What is more in this function we can define how our verification will looks like. I defined that our token will be verified by time and secret key.

 app.UseAuthentication();

When we have defined our token settings, we can start creating our tokens!

Let's make class and name it: JwtHandler. In this class we will have just one method: Create Token.

image.png

This method should looks like this:

public class JwtHandler : IJwtHandler
    {
        private readonly IConfiguration _configuration;

        public JwtHandler(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public JwtDTO CreateToken(Guid userId, string role)
        {
            var now = DateTime.UtcNow;
            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, userId.ToString()),
                new Claim(JwtRegisteredClaimNames.UniqueName, userId.ToString()),
                new Claim(ClaimTypes.Role, role),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, now.ToTimeStamp().ToString(), ClaimValueTypes.Integer64),
            };

            var signingCredentials = new SigningCredentials(
                new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Token:Key"]))
                , SecurityAlgorithms.HmacSha256);

            var expiry = now.AddMinutes(double.Parse(_configuration["Token:ExpireMinutes"]));

            var jwt = new JwtSecurityToken(
                claims: claims,
                notBefore: now,
                expires: expiry,
                signingCredentials: signingCredentials
            );

            var token = new JwtSecurityTokenHandler().WriteToken(jwt);

            return new JwtDTO()
            {
                Token = token,
                Expiry = expiry.ToTimeStamp()
            };
        }
    }

That is all, we have created authorization with JWT Tokens. When we have use it, we have to attribut [Authorize] to our method in Controller. Like this:

[HttpGet]
[Route("auth")]
[Authorize]
public IActionResult GetAuth()
{
      return Content("This method require authorization");
}

If you like this tutorial please give a Like.

Thanks!



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Your contribution cannot be approved yet. See the Utopian Rules. Please edit your contribution to reapply for approval.

  • Please write all your code in a code box instead of including a photo of the same.

You may edit your post here, as shown below:

You can contact us on Discord.
[utopian-moderator]

Sorry for that. I changed picture to code box. Can you check again?

Please put all the code used in the tutorial into code box!

fixed, sorry again for my mistake.

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @babelek I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • This is your first accepted contribution here in Utopian. Welcome!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x