Ejemplo n.º 1
0
        private async Task <Result <SbApiAuthToken> > AuthenticateWithToken(AuthTokenPayload payload)
        {
            var authJwtOptions           = _configuration.GetOptions <JwtOptions>(JwtOptions.SectionName);
            var jwtEmailEncryptionSecret = authJwtOptions.EmailEncryptionSecret;
            var jwtSecret = authJwtOptions.Secret;

            var user = await _authService.Authenticate(payload);

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, jwtEmailEncryptionSecret, user.Id.ToString()),
                new Claim(JwtRegisteredClaimNames.Email, Security.Encrypt(jwtEmailEncryptionSecret, user.Email)),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };

            var key   = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSecret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                authJwtOptions.Issuer,
                authJwtOptions.Audience,
                claims,
                expires: DateTime.Now.AddSeconds(3600),
                signingCredentials: creds);

            return(Result.Ok(new SbApiAuthToken(new JwtSecurityTokenHandler().WriteToken(token))));
        }
        private string GenerateAuthToken(User user)
        {
            AuthTokenPayload payload = new AuthTokenPayload
            {
                Issuer   = _settings.Issuer,
                Subject  = user.Id,
                Audience = _settings.Audience,
                IssuedAt = DateTime.Now.Millisecond,
                Expires  = DateTime.Now.AddHours(_settings.RefreshTokenValidityHours).Millisecond,
                User     = user
            };

            return(GenerateToken(payload));
        }