Exemple #1
0
        public override Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context)
        {
            string username = context.UserName;
            string password = context.Password;

            UserManager <ApplicationUser> userManager = context.HttpContext.RequestServices.GetRequiredService <UserManager <ApplicationUser> >();
            ApplicationUser user = userManager.FindByNameAsync(username).Result;

            if (userManager.CheckPasswordAsync(user, password).Result)
            {
                ClaimsIdentity identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);
                identity.AddClaim(ClaimTypes.Name, user.UserName,
                                  OpenIdConnectConstants.Destinations.AccessToken,
                                  OpenIdConnectConstants.Destinations.IdentityToken);

                List <string> roles = userManager.GetRolesAsync(user).Result.ToList();
                foreach (string role in roles)
                {
                    identity.AddClaim(ClaimTypes.Role, role,
                                      OpenIdConnectConstants.Destinations.AccessToken,
                                      OpenIdConnectConstants.Destinations.IdentityToken);
                }

                AuthenticationTicket ticket = new AuthenticationTicket(
                    new ClaimsPrincipal(identity),
                    new AuthenticationProperties(),
                    context.Options.AuthenticationScheme);
                ticket.SetResources("resource_server");

                List <string> scopes = new List <string>();
                if (context.Request.HasScope("offline_access"))
                {
                    scopes.Add("offline_access");
                }
                ticket.SetScopes(scopes);

                if (string.IsNullOrWhiteSpace(context.Request.Resource))
                {
                    _logger.LogDebug("setting default audience for ticket....");
                }

                context.Validate(ticket);
            }
            else
            {
                context.Reject("invalid credentials");
            }

            return(Task.FromResult(0));
        }
        /// <summary>
        /// Validates the userName and password provided by the user.
        /// </summary>
        public override async Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context)
        {
            var query  = new UserNamePasswordLogin(context.UserName, context.Password);
            var result = await ExecuteMessage(context, query);

            if (!result.Succeeded)
            {
                context.Reject("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            SetCorsHeader(context);

            var ticket = CreateAuthenticationTicket(result, context);

            context.Validate(ticket);
        }
        public async override Task GrantResourceOwnerCredentials(
            GrantResourceOwnerCredentialsContext context)
        {
            _authService = (IAuthService)context.HttpContext.RequestServices.GetService(typeof(IAuthService));
            Client client        = _authService.FindClient(context.ClientId);
            string allowedOrigin = string.Empty;

            allowedOrigin = client.AllowedOrigin == null ? "*" : client.AllowedOrigin;

            //comentado pois está dando conflito com cors adicionado anteriormente
            //context.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            var user = await _authService.GetUsuarioEmail(context.UserName);

            var valid = await _authService.CheckPasswordAsync(user, context.Password);

            if (valid)
            {
                int casaId = await _authService.GetCasaSelecionada(user);

                //verifica se usuario esta bloqueado para aquela casa
                if (_authService.AcessoUsuarioBloqueado(user.Id, casaId))
                {
                    //tenta obter acesso em outra casa
                    int novaCasaSelec = _authService.TentaSelecOutraCasa(user.Id, casaId);

                    if (novaCasaSelec == 0)
                    {
                        context.Reject("O seu acesso foi bloqueado");
                        return;
                    }

                    casaId = novaCasaSelec;
                }

                var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);

                foreach (var claim in  _authService.GetClaims(user, casaId))
                {
                    identity.AddClaim(claim.Type, claim.Value, "access_token", "id_token");
                }

                identity.AddClaim("casa", casaId.ToString(), "access_token", "id_token");

                identity.AddClaim(ClaimTypes.NameIdentifier, user.Id, "access_token", "id_token");

                identity.AddClaim(ClaimTypes.Name, user.UserName, "access_token", "id_token");


                var principal = new ClaimsPrincipal(identity);

                var props = new AuthenticationProperties(new Dictionary <string, string>
                {
                    {
                        "client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                    },
                    {
                        "userName", context.UserName
                    }
                });

                var ticket = new AuthenticationTicket(principal, props, OpenIdConnectServerDefaults.AuthenticationScheme);

                List <string> scopes = new List <string>();
                if (context.Request.HasScope("offline_access"))
                {
                    scopes.Add("offline_access");
                }

                ticket.SetScopes(scopes);

                context.Validate(ticket);
            }
        }
Exemple #4
0
        public override async Task GrantResourceOwnerCredentials([NotNull] GrantResourceOwnerCredentialsContext context)
        {
            var services = context.HttpContext.RequestServices.GetRequiredService <OpenIddictServices <TUser, TApplication> >();

            var user = await services.Users.FindByNameAsync(context.UserName);

            if (user == null)
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidGrant,
                    description: "Invalid credentials.");

                return;
            }

            // Ensure the user is allowed to sign in.
            if (!await services.SignIn.CanSignInAsync(user))
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidGrant,
                    description: "The user is not allowed to sign in.");

                return;
            }

            // Ensure the user is not already locked out.
            if (services.Users.SupportsUserLockout && await services.Users.IsLockedOutAsync(user))
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidGrant,
                    description: "Account locked out.");

                return;
            }

            // Ensure the password is valid.
            if (!await services.Users.CheckPasswordAsync(user, context.Password))
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidGrant,
                    description: "Invalid credentials.");

                if (services.Users.SupportsUserLockout)
                {
                    await services.Users.AccessFailedAsync(user);

                    // Ensure the user is not locked out.
                    if (await services.Users.IsLockedOutAsync(user))
                    {
                        context.Reject(
                            error: OpenIdConnectConstants.Errors.InvalidGrant,
                            description: "Account locked out.");
                    }
                }

                return;
            }

            if (services.Users.SupportsUserLockout)
            {
                await services.Users.ResetAccessFailedCountAsync(user);
            }

            // Reject the token request if two-factor authentication has been enabled by the user.
            if (services.Users.SupportsUserTwoFactor && await services.Users.GetTwoFactorEnabledAsync(user))
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidGrant,
                    description: "Two-factor authentication is required for this account.");

                return;
            }

            // Return an error if the username corresponds to the registered
            // email address and if the "email" scope has not been requested.
            if (context.Request.HasScope(OpenIdConnectConstants.Scopes.Profile) &&
                !context.Request.HasScope(OpenIdConnectConstants.Scopes.Email) &&
                string.Equals(await services.Users.GetUserNameAsync(user),
                              await services.Users.GetEmailAsync(user),
                              StringComparison.OrdinalIgnoreCase))
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidRequest,
                    description: "The 'email' scope is required.");

                return;
            }

            var identity = await services.Applications.CreateIdentityAsync(user, context.Request.GetScopes());

            Debug.Assert(identity != null);

            // Create a new authentication ticket holding the user identity.
            var ticket = new AuthenticationTicket(
                new ClaimsPrincipal(identity),
                new AuthenticationProperties(),
                context.Options.AuthenticationScheme);

            ticket.SetResources(context.Request.GetResources());
            ticket.SetScopes(context.Request.GetScopes());

            context.Validate(ticket);
        }