Пример #1
0
    /// <summary>
    /// If Authentication is successful, JWT tokens are generated.
    /// </summary>
    public virtual IToken GenerateToken(string username, IList <string> roles, DateTime tokenExpiredDate)
    {
        var tokenHandler = new JwtSecurityTokenHandler();

        //Kullanıcıya ait roller Tokene Claim olarak ekleniyor
        var claimsIdentityList = new ClaimsIdentity(roles.Select(r => new Claim(ClaimTypes.Role, r)));

        //Kullanıcını UserName 'i tokena claim olarak ekleniyor
        claimsIdentityList.AddClaim(new Claim(ClaimTypes.Name, username));

        //Kullanıcını UserName 'i tokena claim olarak ekleniyor
        claimsIdentityList.AddClaim(new Claim(ClaimTypes.Expired, value: tokenExpiredDate.ToString()));

        //Token üretimi için gerekli bilgiler , _tokenManagement => appsettings.json dosyasını okur
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject            = claimsIdentityList,
            Issuer             = _tokenManagement.Issuer,
            Audience           = _tokenManagement.Audience,
            Expires            = tokenExpiredDate,
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_tokenManagement.Secret)), SecurityAlgorithms.HmacSha256Signature)
        };

        var token = tokenHandler.CreateToken(tokenDescriptor);//Token Üretimi

        return(new MilvaToken
        {
            AccessToken = tokenHandler.WriteToken(token),
            Expiration = tokenExpiredDate,
            RefreshToken = IdentityHelpers.CreateRefreshToken()
        });
    }