Exemplo n.º 1
0
        public ActionResult GetJwtCertificate()
        {
            var certificate = _jwtOptions.GetCertificate();

            var builder = new StringBuilder();

            builder.AppendLine("-----BEGIN CERTIFICATE-----");
            builder.AppendLine(Convert.ToBase64String(certificate.RawData, Base64FormattingOptions.InsertLineBreaks));
            builder.AppendLine("-----END CERTIFICATE-----");

            return(Content(builder.ToString(), "application/x-x509-user-cert"));
        }
Exemplo n.º 2
0
        private string IssueToken(TypeToken type, int userId)
        {
            var         now         = DateTime.UtcNow;
            AuthSession authSession = null;

            // General claims
            var claims = new List <Claim>
            {
                new Claim("idUser", Convert.ToString(userId)),
                new Claim("nbf", Convert.ToString(DateTimeOffset.Now.ToUnixTimeSeconds()))
            };

            if (type == TypeToken.Аuthorization)
            {
                claims.Add(new Claim("type", "Auth"));
                authSession = new AuthSession()
                {
                    ExpirationTime = now.Add(TimeSpan.FromMinutes(_tokenSettings.AuthLifetime)),
                    UserId         = userId,
                    CreatedAt      = now
                };
            }
            else
            {
                claims.Add(new Claim("type", "Session"));
            }

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Token");
            var            creds          = new SigningCredentials(new X509SecurityKey(_jwtSettings.GetCertificate()), SecurityAlgorithms.RsaSha256);

            var jwt = new JwtSecurityToken(
                issuer: _tokenSettings.Issuer,
                audience: _tokenSettings.Audience,
                claims: claimsIdentity.Claims,
                signingCredentials: creds);

            jwt.Header.Remove("kid");
            string token = new JwtSecurityTokenHandler().WriteToken(jwt);

            if (type == TypeToken.Аuthorization)
            {
                authSession.Token = token;
                _dbContext.authSessions.Add(authSession);
                _dbContext.SaveChanges();
            }

            return(token);
        }