コード例 #1
0
        public object Autentication(
            [FromBody] AutenticationViewModel request,
            [FromServices] SigningConfigurations signingConfigurations,
            [FromServices] TokenConfiguration tokenConfigurations)
        {
            bool validCredentials = false;

            var response = _mapper.Map <Player, PlayerViewModel>(_playerAppService.Authentication(request.Email, request.Password));

            validCredentials = response != null;


            if (validCredentials)
            {
                ClaimsIdentity identity = new ClaimsIdentity(
                    new GenericIdentity(response.Id.ToString(), "Id"),
                    new[] {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                    new Claim("User", JsonConvert.SerializeObject(response))
                }
                    );

                DateTime dataCriacao   = DateTime.Now;
                DateTime dataExpiracao = dataCriacao +
                                         TimeSpan.FromSeconds(tokenConfigurations.Seconds);

                var handler       = new JwtSecurityTokenHandler();
                var securityToken = handler.CreateToken(new SecurityTokenDescriptor
                {
                    Issuer             = tokenConfigurations.Issuer,
                    Audience           = tokenConfigurations.Audience,
                    SigningCredentials = signingConfigurations.SigningCredentials,
                    Subject            = identity,
                    NotBefore          = dataCriacao,
                    Expires            = dataExpiracao
                });
                var token = handler.WriteToken(securityToken);

                return(new
                {
                    authenticated = true,
                    created = dataCriacao.ToString("yyyy-MM-dd HH:mm:ss"),
                    expiration = dataExpiracao.ToString("yyyy-MM-dd HH:mm:ss"),
                    accessToken = token,
                    message = "OK",
                    FirstName = response.FirstName,
                    Id = response.Id
                });
            }
            else
            {
                return(new
                {
                    authenticated = false,
                });
            }
        }