Пример #1
0
        public static SecurityToken CreateSecurityToken(TokenDomainModel model, string secret)
        {
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(secret);
            var roles           = JsonConvert.SerializeObject(model.Roles);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, model.Name),
                    new Claim(ClaimTypes.Role, roles)
                }),
                Expires            = model.ExpiresOn,
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            return(tokenHandler.CreateToken(tokenDescriptor));
        }
Пример #2
0
 public static string CreateStringSecurityToken(TokenDomainModel model, string secret)
 {
     return(CreateSecurityToken(model, secret).ToJwtString());
 }
Пример #3
0
        public async Task <IActionResult> Authenticate([FromBody] AppLoginRequest request)
        {
            var result = new LoginResponse();

            try
            {
                #region .: request validation :.

                if (request == null || request.Data == null)
                {
                    return(result.ToBadRequest("Request and Request.Data can not be null!"));
                }
                if (string.IsNullOrEmpty(request.Data.ClientId))
                {
                    return(result.ToBadRequest("ClientId can not be null"));
                }
                if (string.IsNullOrEmpty(request.Data.ClientSecret))
                {
                    return(result.ToBadRequest("ClientSecret can not be null"));
                }
                if (request.Data.ExpiresInSeconds <= 0)
                {
                    return(result.ToBadRequest("ExpiresInSeconds is not valid"));
                }

                var cachedToken = cacheManager.CreateTokenKey(request.Data.ClientId, request.Data.ClientSecret);
                var cache       = await cacheManager.Find <LoginResponse>(cachedToken);

                if (cache != null)
                {
                    return(cache.ToOk(this.Response));
                }

                var app = await appRepository.FindByClientId(request.Data.ClientId);

                if (app == null)
                {
                    return(result.ToNotFound($"App {request.Data.ClientId} not found!"));
                }
                if (!app.ClientSecret.Equals(request.Data.ClientSecret))
                {
                    return(result.ToNotFound($"App {request.Data.ClientId} not found!"));
                }

                #endregion

                var token = new TokenDomainModel
                {
                    Name          = app.Name,
                    CreatedOn     = DateTimeHelper.Now(),
                    ExpiresOn     = DateTimeHelper.Now().AddSeconds(request.Data.ExpiresInSeconds),
                    IsAutoRefresh = request.Data.IsAutoRefresh,
                    TokenType     = EnumTokenType.App,
                    Roles         = app.Roles
                };

                await tokenRepository.Create(token);

                var jwtSecret  = configuration.GetAppSettings().JwtSecret;
                var jwtContent = TokenHelper.CreateStringSecurityToken(token, jwtSecret);

                result.Data = new LoginResponseData
                {
                    Token      = token.Id,
                    JwtContent = jwtContent,
                    Name       = app.Name,
                    ExpiresOn  = token.ExpiresOn
                };

                await cacheManager.Save(cachedToken, result);

                return(result.ToOk());
            }
            catch (UnauthorizedAccessException ex)
            {
                await logRepository.AddError("Login.Authenticate", ex);

                return(result.ToUnauthorized(ex.Message));
            }
            catch (Exception ex)
            {
                await logRepository.AddError("Login.Authenticate", ex);

                return(result.ToInternalServerError(ex.Message));
            }
        }