public object Authenticate(
            [FromBody] AuthenticateUserRequest request,
            [FromServices] SigningConfigurations signingConfigurations,
            [FromServices] TokenConfigurations tokenConfigurations)
        {
            bool credenciaisValidas           = false;
            AuthenticateUserResponse response = _serviceUser.AuthenticateUser(request);

            credenciaisValidas = response != null;

            if (credenciaisValidas)
            {
                ClaimsIdentity identity = new ClaimsIdentity(
                    new GenericIdentity(response.Id.ToString(), "Id"),
                    new[] {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                    //new Claim(JwtRegisteredClaimNames.UniqueName, response.Usuario)
                    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
                });
            }
            else
            {
                return(new
                {
                    authenticated = false,
                    _serviceUser.Notifications
                });
            }
        }
 public async Task <HttpResponseMessage> Authenticate(AuthenticateUserRequest request)
 {
     try
     {
         var response = _serviceUser.AuthenticateUser(request);
         return(await ResponseAsync(response, _serviceUser));
     }
     catch (Exception ex)
     {
         return(await ResponseExceptionAsync(ex));
     }
 }
Example #3
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                IServiceUser serviceUser = _container.Resolve <IServiceUser>();

                AuthenticateUserRequest request = new AuthenticateUserRequest();
                request.Email = context.UserName;
                request.Senha = context.Password;

                AuthenticateUserResponse response = serviceUser.AuthenticateUser(request);



                if (serviceUser.IsInvalid())
                {
                    if (response == null)
                    {
                        context.SetError("invalid_grant", "Preencha um e-mail válido e uma senha com pelo menos 6 caracteres.");
                        return;
                    }
                }

                serviceUser.ClearNotifications();

                if (response == null)
                {
                    context.SetError("invalid_grant", "Usuário não encontrado!");
                    return;
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);

                //Definindo as Claims
                identity.AddClaim(new Claim("User", JsonConvert.SerializeObject(response)));

                var principal = new GenericPrincipal(identity, new string[] { });

                Thread.CurrentPrincipal = principal;

                context.Validated(identity);
            }
            catch (Exception ex)
            {
                context.SetError("invalid_grant", ex.Message);
                return;
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
                IServiceUser serviceUser = _container.Resolve <IServiceUser>();

                AuthenticateUserRequest request = new AuthenticateUserRequest();
                request.Email    = context.UserName;
                request.Password = context.Password;

                AuthenticateUserResponse response = serviceUser.AuthenticateUser(request);

                if (response == null)
                {
                    context.SetError("invalid_grant", "Usuário inválido");
                    return;
                }

                serviceUser.ClearNotifications();

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);

                identity.AddClaim(new Claim("Usuário", JsonConvert.SerializeObject(response)));

                var principal = new GenericPrincipal(identity, new string[] { });

                Thread.CurrentPrincipal = principal;

                context.Validated(identity);
            }
            catch (Exception ex)
            {
                context.SetError("invalid_grant", ex.Message);
                return;
            }
        }