mercredi 24 octobre 2018

JWT Kullanımı .net Core 2.1.4

Selamlar,

araştırmalarımda burak selim şenyurt ve bir kaç ustadın makalelerinden faydalandım.

.net core Jwt(json web token)

kullanacağımız referanslar

using System.IdentityModel.Tokens.Jwt;

using Microsoft.IdentityModel.Tokens;

using System.Security.Claims;

Startup

services.AddAuthentication(options => {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                }
            )
            .AddJwtBearer(options => {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = true,
                    ValidAudience = "***************",
                    ValidateIssuer = true,
                    ValidIssuer = "***************",
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes("***************"))
                };

                options.Events = new JwtBearerEvents
                {
                    OnTokenValidated = ctx => {
                        return Task.CompletedTask;
                    },
                    OnAuthenticationFailed = ctx => {
                        Console.WriteLine("Exception:{0}", ctx.Exception.Message);
                        return Task.CompletedTask;
                    }
                };
            });

AuthController

    [HttpPost("Auth")]
    public TokenResultModel Auth([FromBody] AuthModel model)
    {
        var loginResult = _userService.Login(model.Email, model.Password);

        if (loginResult != null)
            return GenerateToken(loginResult.Email, loginResult.Id, loginResult.TenantId);

        return new TokenResultModel
        {
            Message = "Error Login",
            Status = false

        };
    }

GenerateToken

private TokenResultModel GenerateToken(string userEmail, int userId, int userTenantId)
    {

        var claims = new Claim[]{
            new Claim("Email", userEmail),
            new Claim(JwtRegisteredClaimNames.UniqueName, userId.ToString()),
            new Claim(JwtRegisteredClaimNames.Email,"**********"),
            new Claim("UserId",userId.ToString()),
            new Claim("TenantId",userTenantId.ToString())
        };


        SecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("*************"));
        var token = new JwtSecurityToken(
            issuer: "**************",
            audience: "**************",
            claims: claims,
            expires: DateTime.Now.AddMinutes(3),
            signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
        );

        return new TokenResultModel
        {
            AccessToken = new JwtSecurityTokenHandler().WriteToken(token),
            ExpireInSeconds = token.ValidTo,
            UserName = userEmail,
            UserId = userId,
            TenantId = userTenantId
        };
    }

postman results for token I created

enter image description here




Aucun commentaire:

Enregistrer un commentaire