Пример #1
0
        public async Task <IActionResult> GenerateToken([FromBody] LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var config = new ConfigurationBuilder()
                             .SetBasePath(Directory.GetCurrentDirectory())
                             .AddJsonFile("appsettings.json")
                             .Build();

                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);

                    if (result.Succeeded)
                    {
                        var userRoles  = new List <string>();
                        var userClaims = new List <Claim>();

                        if (_userManager.SupportsUserRole)
                        {
                            var roles = await _userManager.GetRolesAsync(user);

                            foreach (var roleName in roles)
                            {
                                if (_roleManager.SupportsRoleClaims)
                                {
                                    userRoles.Add(roleName);

                                    var role = await _roleManager.FindByNameAsync(roleName);

                                    if (role != null)
                                    {
                                        userClaims.AddRange(await _roleManager.GetClaimsAsync(role));
                                    }
                                }
                            }
                        }

                        var claims = new[]
                        {
                            new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                        };

                        var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Jwt:Secret"]));
                        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                        var token = new JwtSecurityToken(config["Jwt:Iss"],
                                                         config["Jwt:Aud"],
                                                         claims.Union(userClaims),
                                                         expires: DateTime.Now.AddMinutes(30),
                                                         signingCredentials: creds);

                        token.Payload.Add("roles", userRoles);


                        return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) }));
                    }
                }
            }

            return(BadRequest("Could not create token"));
        }
Пример #2
0
 public async Task <SignInResult> ValidatePasswordAsync(User user, string Password)
 {
     return(await _signInManager.CheckPasswordSignInAsync(user, Password, false));
 }
Пример #3
0
        public IActionResult Login(
            [FromBody] User usuario,
            [FromServices] UserManager <ApplicationUser> userManager,
            [FromServices] SignInManager <ApplicationUser> signInManager,
            [FromServices] SigningConfigurations signingConfigurations,
            [FromServices] TokenConfigurations tokenConfigurations)
        {
            bool credenciaisValidas = false;

            if (usuario != null && !string.IsNullOrEmpty(usuario.UserName))
            {
                // Verifica a existência do usuário nas tabelas do
                // ASP.NET Core Identity
                var userIdentity = userManager.FindByNameAsync(usuario.UserName).Result;
                if (userIdentity != null)
                {
                    // Efetua o login com base no Id do usuário e sua senha
                    var resultadoLogin = signInManager.CheckPasswordSignInAsync(userIdentity, usuario.Password, false).Result;
                    if (resultadoLogin.Succeeded)
                    {
                        // Verifica se o usuário em questão possui
                        // a role Acesso-API
                        credenciaisValidas = userManager.IsInRoleAsync(
                            userIdentity, Roles.ROLE_API).Result;
                    }
                }
            }
            if (credenciaisValidas)
            {
                // Usado para gerar Token de login
                var identity = new ClaimsIdentity(
                    new GenericIdentity(usuario.UserName, "Login"),
                    new[] {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                    new Claim(JwtRegisteredClaimNames.UniqueName, usuario.UserName)
                }
                    );
                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);

                object obj = 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"
                };



                return(new ObjectResult(obj));
            }
            else
            {
                return(new ObjectResult(new
                {
                    authenticated = false,
                    message = "Falha ao autenticar"
                }));
            }
        }
        public async Task <ActionResult <LoginAccountOutputDto> > Login(LoginAccountInputDto loginDto)
        {
            var user = await _userManager.FindByEmailAsync(loginDto.UserName);

            if (user == null)
            {
                return(Unauthorized(new ApiResponse(401)));
            }

            var result = await _signInManager.CheckPasswordSignInAsync(user, loginDto.Password, false);


            // Ensure the user is not already locked out.
            if (result.IsLockedOut)
            {
                return(BadRequest(new ApiResponse(400, "The specified user account has been suspended.")));
            }

            // Reject the token request if two-factor authentication has been enabled by the user.
            if (result.RequiresTwoFactor)
            {
                return(BadRequest(new ApiResponse(400, "Invalid login procedure.")));
            }

            if (!result.Succeeded)
            {
                return(Unauthorized(new ApiResponse(401)));
            }
            var tokenResponse = await _tokenService.CreateToken(user, loginDto.TimeZone);

            var timezone = await _accountService.GetUserTimezoneById(user.Id);

            var hasChangePassword = user.HasChangePassword.HasValue ? user.HasChangePassword.Value : false;

            var role     = 1;
            var roleName = (await _userManager.GetRolesAsync(user)).FirstOrDefault();

            if (roleName == "admin")
            {
                role = (int)UserRole.admin;
            }
            else if (roleName == "manager")
            {
                role = (int)UserRole.manager;
            }
            else
            {
                role = (int)UserRole.sdr;
            }

            return(new LoginAccountOutputDto
            {
                Id = user.Id,
                Username = user.Email,
                Token = tokenResponse.Token,
                RefreshToken = tokenResponse.RefreshToken,
                TimeZone = timezone,
                HasChangePassword = hasChangePassword,
                Role = role
            });
        }
Пример #5
0
        public async Task <IActionResult> Exchange(OpenIdConnectRequest request)
        {
            Debug.Assert(request.IsTokenRequest(),
                         "The OpenIddict binder for ASP.NET Core MVC is not registered. " +
                         "Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");

            if (request.IsPasswordGrantType())
            {
                var user = await _userManager.FindByNameAsync(request.Username);

                if (user == null)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    }));
                }

                // Validate the username/password parameters and ensure the account is not locked out.
                var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, lockoutOnFailure : true);

                if (!result.Succeeded)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    }));
                }

                // Create a new authentication ticket.
                var ticket = await CreateTicketAsync(request, user);

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }

            else if (request.IsRefreshTokenGrantType())
            {
                // Retrieve the claims principal stored in the refresh token.
                var info = await HttpContext.AuthenticateAsync(OpenIdConnectServerDefaults.AuthenticationScheme);

                // Retrieve the user profile corresponding to the refresh token.
                // Note: if you want to automatically invalidate the refresh token
                // when the user password/roles change, use the following line instead:
                // var user = _signInManager.ValidateSecurityStampAsync(info.Principal);
                var user = await _userManager.GetUserAsync(info.Principal);

                if (user == null)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The refresh token is no longer valid."
                    }));
                }

                // Ensure the user is still allowed to sign in.
                if (!await _signInManager.CanSignInAsync(user))
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The user is no longer allowed to sign in."
                    }));
                }

                // Create a new authentication ticket, but reuse the properties stored
                // in the refresh token, including the scopes originally granted.
                var ticket = await CreateTicketAsync(request, user, info.Properties);

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }

            return(BadRequest(new OpenIdConnectResponse
            {
                Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
                ErrorDescription = "The specified grant type is not supported."
            }));
        }
        public async Task <User> Post([FromBody] User User)
        {
            User user = null;

            if (ModelState.IsValid)
            {
                int hostroleid = -1;
                if (!Users.GetUsers().Any())
                {
                    hostroleid = Roles.GetRoles(User.SiteId, true).Where(item => item.Name == Constants.HostRole).FirstOrDefault().RoleId;
                }

                IdentityUser identityuser = await IdentityUserManager.FindByNameAsync(User.Username);

                if (identityuser == null)
                {
                    identityuser          = new IdentityUser();
                    identityuser.UserName = User.Username;
                    identityuser.Email    = User.Email;
                    var result = await IdentityUserManager.CreateAsync(identityuser, User.Password);

                    if (result.Succeeded)
                    {
                        user = Users.AddUser(User);

                        // assign to host role if this is the initial installation
                        if (hostroleid != -1)
                        {
                            UserRole userrole = new UserRole();
                            userrole.UserId        = user.UserId;
                            userrole.RoleId        = hostroleid;
                            userrole.EffectiveDate = null;
                            userrole.ExpiryDate    = null;
                            UserRoles.AddUserRole(userrole);
                        }
                    }
                }
                else
                {
                    var result = await IdentitySignInManager.CheckPasswordSignInAsync(identityuser, User.Password, false);

                    if (result.Succeeded)
                    {
                        user = Users.GetUser(User.Username);
                    }
                }

                if (user != null && hostroleid == -1)
                {
                    // add auto assigned roles to user for site
                    List <Role> roles = Roles.GetRoles(User.SiteId).Where(item => item.IsAutoAssigned == true).ToList();
                    foreach (Role role in roles)
                    {
                        UserRole userrole = new UserRole();
                        userrole.UserId        = user.UserId;
                        userrole.RoleId        = role.RoleId;
                        userrole.EffectiveDate = null;
                        userrole.ExpiryDate    = null;
                        UserRoles.AddUserRole(userrole);
                    }
                }
            }

            return(user);
        }
Пример #7
0
        public virtual async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            var clientId = context.Request?.Client?.ClientId;

            using var scope = ServiceScopeFactory.CreateScope();

            await ReplaceEmailToUsernameOfInputIfNeeds(context);

            IdentityUser user = null;

            async Task SetSuccessResultAsync()
            {
                var sub = await UserManager.GetUserIdAsync(user);

                Logger.LogInformation("Credentials validated for username: {username}", context.UserName);

                var additionalClaims = new List <Claim>();

                await AddCustomClaimsAsync(additionalClaims, user, context);

                context.Result = new GrantValidationResult(
                    sub,
                    OidcConstants.AuthenticationMethods.Password,
                    additionalClaims.ToArray()
                    );

                await IdentitySecurityLogManager.SaveAsync(
                    new IdentitySecurityLogContext
                {
                    Identity = IdentityServerSecurityLogIdentityConsts.IdentityServer,
                    Action   = IdentityServerSecurityLogActionConsts.LoginSucceeded,
                    UserName = context.UserName,
                    ClientId = clientId
                }
                    );
            }

            if (AbpIdentityOptions.ExternalLoginProviders.Any())
            {
                foreach (var externalLoginProviderInfo in AbpIdentityOptions.ExternalLoginProviders.Values)
                {
                    var externalLoginProvider = (IExternalLoginProvider)scope.ServiceProvider
                                                .GetRequiredService(externalLoginProviderInfo.Type);

                    if (await externalLoginProvider.TryAuthenticateAsync(context.UserName, context.Password))
                    {
                        user = await UserManager.FindByNameAsync(context.UserName);

                        if (user == null)
                        {
                            user = await externalLoginProvider.CreateUserAsync(context.UserName, externalLoginProviderInfo.Name);
                        }
                        else
                        {
                            await externalLoginProvider.UpdateUserAsync(user, externalLoginProviderInfo.Name);
                        }

                        await SetSuccessResultAsync();

                        return;
                    }
                }
            }

            user = await UserManager.FindByNameAsync(context.UserName);

            string errorDescription;

            if (user != null)
            {
                var result = await SignInManager.CheckPasswordSignInAsync(user, context.Password, true);

                if (result.Succeeded)
                {
                    await SetSuccessResultAsync();

                    return;
                }
                else if (result.IsLockedOut)
                {
                    Logger.LogInformation("Authentication failed for username: {username}, reason: locked out", context.UserName);
                    errorDescription = Localizer["UserLockedOut"];
                }
                else if (result.IsNotAllowed)
                {
                    Logger.LogInformation("Authentication failed for username: {username}, reason: not allowed", context.UserName);
                    errorDescription = Localizer["LoginIsNotAllowed"];
                }
                else
                {
                    Logger.LogInformation("Authentication failed for username: {username}, reason: invalid credentials", context.UserName);
                    errorDescription = Localizer["InvalidUserNameOrPassword"];
                }

                await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext
                {
                    Identity = IdentityServerSecurityLogIdentityConsts.IdentityServer,
                    Action   = result.ToIdentitySecurityLogAction(),
                    UserName = context.UserName,
                    ClientId = clientId
                });
            }
            else
            {
                Logger.LogInformation("No user found matching username: {username}", context.UserName);
                errorDescription = Localizer["InvalidUsername"];

                await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
                {
                    Identity = IdentityServerSecurityLogIdentityConsts.IdentityServer,
                    Action   = IdentityServerSecurityLogActionConsts.LoginInvalidUserName,
                    UserName = context.UserName,
                    ClientId = clientId
                });
            }

            context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, errorDescription);
        }
Пример #8
0
        public async Task <OperationDataResult <EformAuthorizeResult> > AuthenticateUser(LoginModel model)
        {
            Log.LogEvent("AuthService.AuthenticateUser: called");
            if (string.IsNullOrEmpty(model.Username) || string.IsNullOrEmpty(model.Password))
            {
                return(new OperationDataResult <EformAuthorizeResult>(false, "Empty username or password"));
            }

            var user = await _userService.GetByUsernameAsync(model.Username);

            if (user == null)
            {
                return(new OperationDataResult <EformAuthorizeResult>(false,
                                                                      $"User with username {model.Username} not found"));
            }

            var signInResult =
                await _signInManager.CheckPasswordSignInAsync(user, model.Password, true);

            if (!signInResult.Succeeded && !signInResult.RequiresTwoFactor)
            {
                if (signInResult.IsLockedOut)
                {
                    return(new OperationDataResult <EformAuthorizeResult>(false,
                                                                          "Locked Out. Please, try again after 10 min"));
                }

                // Credentials are invalid, or account doesn't exist
                return(new OperationDataResult <EformAuthorizeResult>(false, "Incorrect password."));
            }

            // Confirmed email check
            if (!user.EmailConfirmed)
            {
                return(new OperationDataResult <EformAuthorizeResult>(false, $"Email {user.Email} not confirmed"));
            }

            // TwoFactor check
            var psk  = user.GoogleAuthenticatorSecretKey;
            var code = model.Code;
            var isTwoFactorAuthForced = _appSettings.Value.IsTwoFactorForced;

            if (user.TwoFactorEnabled || isTwoFactorAuthForced)
            {
                // check input params
                if (string.IsNullOrEmpty(psk) || string.IsNullOrEmpty(code))
                {
                    return(new OperationDataResult <EformAuthorizeResult>(false, "PSK or code is empty"));
                }

                if (psk != user.GoogleAuthenticatorSecretKey)
                {
                    return(new OperationDataResult <EformAuthorizeResult>(false, "PSK is invalid"));
                }

                // check code
                var otp         = new Totp(Base32.FromBase32String(user.GoogleAuthenticatorSecretKey));
                var isCodeValid = otp.VerifyTotp(code, out _, new VerificationWindow(300, 300));
                if (!isCodeValid)
                {
                    return(new OperationDataResult <EformAuthorizeResult>(false, "Invalid code"));
                }

                // update user entity
                if (!user.IsGoogleAuthenticatorEnabled)
                {
                    user.IsGoogleAuthenticatorEnabled = true;
                    var updateResult = _userManager.UpdateAsync(user).Result;
                    if (!updateResult.Succeeded)
                    {
                        return(new OperationDataResult <EformAuthorizeResult>(false, "PSK or code is empty"));
                    }
                }
            }

            var token = await GenerateToken(user);

            var roleList = _userManager.GetRolesAsync(user).Result;

            if (!roleList.Any())
            {
                return(new OperationDataResult <EformAuthorizeResult>(false,
                                                                      $"Role for user {model.Username} not found"));
            }

            return(new OperationDataResult <EformAuthorizeResult>(true, new EformAuthorizeResult
            {
                Id = user.Id,
                access_token = token,
                userName = user.UserName,
                role = roleList.FirstOrDefault(),
                FirstName = user.FirstName,
                LastName = user.LastName,
            }));
        }
Пример #9
0
        public virtual async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            await ReplaceEmailToUsernameOfInputIfNeeds(context);

            var user = await _userManager.FindByNameAsync(context.UserName);

            string errorDescription;

            if (user != null)
            {
                var result = await _signInManager.CheckPasswordSignInAsync(user, context.Password, true);

                if (result.Succeeded)
                {
                    var sub = await _userManager.GetUserIdAsync(user);

                    _logger.LogInformation("Credentials validated for username: {username}", context.UserName);
                    await _events.RaiseAsync(new UserLoginSuccessEvent(context.UserName, sub, context.UserName, interactive : false));

                    var additionalClaims = new List <Claim>();

                    await AddCustomClaimsAsync(additionalClaims, user, context);

                    context.Result = new GrantValidationResult(
                        sub,
                        OidcConstants.AuthenticationMethods.Password,
                        additionalClaims.ToArray()
                        );

                    return;
                }
                else if (result.IsLockedOut)
                {
                    _logger.LogInformation("Authentication failed for username: {username}, reason: locked out", context.UserName);
                    await _events.RaiseAsync(new UserLoginFailureEvent(context.UserName, "locked out", interactive : false));

                    errorDescription = _localizer["UserLockedOut"];
                }
                else if (result.IsNotAllowed)
                {
                    _logger.LogInformation("Authentication failed for username: {username}, reason: not allowed", context.UserName);
                    await _events.RaiseAsync(new UserLoginFailureEvent(context.UserName, "not allowed", interactive : false));

                    errorDescription = _localizer["LoginIsNotAllowed"];
                }
                else
                {
                    _logger.LogInformation("Authentication failed for username: {username}, reason: invalid credentials", context.UserName);
                    await _events.RaiseAsync(new UserLoginFailureEvent(context.UserName, "invalid credentials", interactive : false));

                    errorDescription = _localizer["InvalidUserNameOrPassword"];
                }
            }
            else
            {
                _logger.LogInformation("No user found matching username: {username}", context.UserName);
                await _events.RaiseAsync(new UserLoginFailureEvent(context.UserName, "invalid username", interactive : false));

                errorDescription = _localizer["InvalidUsername"];
            }

            context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, errorDescription);
        }
Пример #10
0
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;

            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (TryValidateModel(model) && ModelState.IsValid)
            {
                var disableLocalLogin = (await _siteService.GetSiteSettingsAsync()).As <LoginSettings>().DisableLocalLogin;
                if (disableLocalLogin)
                {
                    ModelState.AddModelError("", S["Local login is disabled."]);
                }
                else
                {
                    await _accountEvents.InvokeAsync((e, model, modelState) => e.LoggingInAsync(model.UserName, (key, message) => modelState.AddModelError(key, message)), model, ModelState, _logger);

                    if (ModelState.IsValid)
                    {
                        var user = await _userManager.FindByNameAsync(model.UserName) ?? await _userManager.FindByEmailAsync(model.UserName);

                        if (user != null)
                        {
                            var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, lockoutOnFailure : true);

                            if (result.Succeeded)
                            {
                                if (!await AddConfirmEmailError(user) && !AddUserEnabledError(user))
                                {
                                    result = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, lockoutOnFailure : true);

                                    if (result.Succeeded)
                                    {
                                        _logger.LogInformation(1, "User logged in.");
                                        await _accountEvents.InvokeAsync((e, user) => e.LoggedInAsync(user), user, _logger);

                                        return(await LoggedInActionResult(user, returnUrl));
                                    }
                                }
                            }

                            if (result.IsLockedOut)
                            {
                                ModelState.AddModelError(string.Empty, S["The account is locked out"]);
                                await _accountEvents.InvokeAsync((e, user) => e.IsLockedOutAsync(user), user, _logger);

                                return(View());
                            }

                            // Login failed with a known user.
                            await _accountEvents.InvokeAsync((e, user) => e.LoggingInFailedAsync(user), user, _logger);
                        }

                        ModelState.AddModelError(string.Empty, S["Invalid login attempt."]);
                    }

                    // Login failed unknown user.
                    await _accountEvents.InvokeAsync((e, model) => e.LoggingInFailedAsync(model.UserName), model, _logger);
                }
            }
            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #11
0
 public async Task <SignInResult> CheckPasswordAsync(User user, string password)
 {
     return(await _signinManager.CheckPasswordSignInAsync(user, password, false));
 }
        public async Task <IActionResult> Exchange()
        {
            var request = HttpContext.GetOpenIddictServerRequest();

            if (request.IsPasswordGrantType())
            {
                var user = await _userManager.FindByNameAsync(request.Username);

                if (user == null)
                {
                    var properties = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error]            = Errors.InvalidGrant,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                            "The username/password couple is invalid."
                    });

                    return(Forbid(properties, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));
                }

                // Validate the username/password parameters and ensure the account is not locked out.
                var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, lockoutOnFailure : true);

                if (!result.Succeeded)
                {
                    var properties = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error]            = Errors.InvalidGrant,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                            "The username/password couple is invalid."
                    });

                    return(Forbid(properties, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));
                }

                // Create a new ClaimsPrincipal containing the claims that
                // will be used to create an id_token, a token or a code.
                var principal = await _signInManager.CreateUserPrincipalAsync(user);

                // Set the list of scopes granted to the client application.
                // Note: the offline_access scope must be granted
                // to allow OpenIddict to return a refresh token.
                principal.SetScopes(new[]
                {
                    Scopes.OpenId,
                    Scopes.Email,
                    Scopes.Profile,
                    Scopes.OfflineAccess,
                    Scopes.Roles
                }.Intersect(request.GetScopes()));

                foreach (var claim in principal.Claims)
                {
                    claim.SetDestinations(GetDestinations(claim, principal));
                }

                return(SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));
            }

            else if (request.IsRefreshTokenGrantType())
            {
                // Retrieve the claims principal stored in the refresh token.
                var info = await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);

                // Retrieve the user profile corresponding to the refresh token.
                // Note: if you want to automatically invalidate the refresh token
                // when the user password/roles change, use the following line instead:
                // var user = _signInManager.ValidateSecurityStampAsync(info.Principal);
                var user = await _userManager.GetUserAsync(info.Principal);

                if (user == null)
                {
                    var properties = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error]            = Errors.InvalidGrant,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The refresh token is no longer valid."
                    });

                    return(Forbid(properties, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));
                }

                // Ensure the user is still allowed to sign in.
                if (!await _signInManager.CanSignInAsync(user))
                {
                    var properties = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error]            = Errors.InvalidGrant,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The user is no longer allowed to sign in."
                    });

                    return(Forbid(properties, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));
                }

                // Create a new ClaimsPrincipal containing the claims that
                // will be used to create an id_token, a token or a code.
                var principal = await _signInManager.CreateUserPrincipalAsync(user);

                foreach (var claim in principal.Claims)
                {
                    claim.SetDestinations(GetDestinations(claim, principal));
                }

                return(SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));
            }

            throw new NotImplementedException("The specified grant type is not implemented.");
        }
Пример #13
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!Input.TermAccount)
            {
                ModelState.ClearValidationState("Input.CreditLimit");
                ModelState.ClearValidationState("Input.RegistrationNumber");
                ModelState.ClearValidationState("Input.CompanyVAT");
                ModelState.MarkFieldValid("Input.CreditLimit");
                ModelState.MarkFieldValid("Input.RegistrationNumber");
                ModelState.MarkFieldValid("Input.CompanyVAT");

                for (int i = 0; i < 3; i++)
                {
                    ModelState.ClearValidationState($"Input.References[{i}].Email");
                    ModelState.ClearValidationState($"Input.References[{i}].SureName");
                    ModelState.ClearValidationState($"Input.References[{i}].FirstName");
                    ModelState.ClearValidationState($"Input.References[{i}].Telephone");
                    ModelState.ClearValidationState($"Input.References[{i}].CompanyName");
                    ModelState.MarkFieldValid($"Input.References[{i}].Email");
                    ModelState.MarkFieldValid($"Input.References[{i}].SureName");
                    ModelState.MarkFieldValid($"Input.References[{i}].FirstName");
                    ModelState.MarkFieldValid($"Input.References[{i}].Telephone");
                    ModelState.MarkFieldValid($"Input.References[{i}].CompanyName");
                }
            }
            else
            {
                if (string.IsNullOrEmpty(Input.References[2].CompanyName))
                {
                    ModelState.ClearValidationState("Input.References[2].Email");
                    ModelState.ClearValidationState("Input.References[2].SureName");
                    ModelState.ClearValidationState("Input.References[2].FirstName");
                    ModelState.ClearValidationState("Input.References[2].Telephone");
                    ModelState.ClearValidationState("Input.References[2].CompanyName");
                    ModelState.MarkFieldValid("Input.References[2].Email");
                    ModelState.MarkFieldValid("Input.References[2].SureName");
                    ModelState.MarkFieldValid("Input.References[2].FirstName");
                    ModelState.MarkFieldValid("Input.References[2].Telephone");
                    ModelState.MarkFieldValid("Input.References[2].CompanyName");
                }
            }

            var user = new ApplicationUser
            {
                FirstName   = Input.FirstName,
                LastName    = Input.LastName,
                UserName    = Input.Email,
                Email       = Input.Email,
                PhoneNumber = Input.PhoneNumber,
                Type        = Domain.Enums.UserType.SuperUser
            };

            foreach (var item in _userManager.PasswordValidators)
            {
                var password = await item.ValidateAsync(_userManager, user, Input.Password);

                if (!password.Succeeded)
                {
                    foreach (var error in password.Errors)
                    {
                        ModelState.AddModelError("Input.Password", string.Format("[{0}] - {1}", error.Code, error.Description));
                    }
                }
            }

            if (!ModelState.IsValid)
            {
                return(Page());
            }


            //Input.ContractNumber = ContractNumber;
            //Input.ContractNumber = Input.PhoneNumber;

            var existingUser = _ctx.Users
                               .Include(x => x.Accounts)
                               .FirstOrDefault(x => x.Email == Input.Email);

            if (existingUser != null)
            {
                var canSignIn = await _signInManager.CheckPasswordSignInAsync(existingUser, Input.Password, false);

                if (canSignIn.Succeeded)
                {
                    await _signInManager.SignInAsync(existingUser, false);

                    await new CreateAccount(_ctx, _emailSender)
                    .Do(new CreateAccount.Request {
                        UserId = existingUser.Id, Input = Input
                    });

                    _cookiesHelper.Set("PreviouslyLoggedInUser", "true", 365);
                    if (Input.TermAccount)
                    {
                        return(RedirectToPage("/Accounts/BusinessRegistered"));
                    }
                    else
                    {
                        return(RedirectToPage("/BusinessProfile/Index"));
                    }
                }
                return(Page());
            }

            var result = await _userManager.CreateAsync(user, Input.Password);

            if (result.Succeeded)
            {
                await _userManager.AddClaimAsync(user, new Claim("type", "superuser"));

                await _signInManager.SignInAsync(user, false);

                await new CreateAccount(_ctx, _emailSender)
                .Do(new CreateAccount.Request
                {
                    UserId = user.Id,
                    Input  = Input
                });

                _cookiesHelper.Set("PreviouslyLoggedInUser", "true", 365);
                if (Input.TermAccount)
                {
                    return(RedirectToPage("/Accounts/BusinessRegistered"));
                }
                else
                {
                    return(RedirectToPage("/BusinessProfile/Index"));
                }
            }

            return(Page());
        }
        public async Task <IActionResult> Login([FromBody] LoginViewModel loginViewModel)
        {
            try
            {
                var user = await _userManager.FindByEmailAsync(loginViewModel.UserName);

                if (user is null)
                {
                    _logger.LogError(LoggingEvents.GetItemNotFound, "Login failed: User not found");
                    return(StatusCode(500, new AuthenticationResultDto()
                    {
                        FailureReason = AuthenticationFailureReason.Other
                    }));
                }

                if (user.EmailConfirmed == false)
                {
                    _logger.LogInformation("EmailNotConfirmed", "You cannot login until you confirm your email.");
                    return(StatusCode(500, new AuthenticationResultDto()
                    {
                        FailureReason = AuthenticationFailureReason.EmailConfirmationRequired
                    }));
                }

                var result = await _signInManager.CheckPasswordSignInAsync(user, loginViewModel.Password, false);

                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(StatusCode(500, new AuthenticationResultDto()
                    {
                        FailureReason = AuthenticationFailureReason.LockedOut
                    }));
                }

                //ToDo: move to separate Service?
                if (result.Succeeded)
                {
                    var claims = new List <Claim>
                    {
                        new Claim(JwtRegisteredClaimNames.Email, user.Email),
                        new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
                        new Claim("ImageUrl", user.Avatar),
                        new Claim("DefaultLatitude", user.DefaultLocationLatitude.ToString()),
                        new Claim("DefaultLongitude", user.DefaultLocationLongitude.ToString()),
                        new Claim("FlickrKey", _configuration["FlickrApiKey"]),
                        new Claim("MapKey", _configuration["MapApiKey"]),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    };

                    var secretKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["TokenKey"]));
                    var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                    var baseUrl = string.Concat(_configuration["Scheme"], _configuration["Domain"]);

                    var tokenOptions = new JwtSecurityToken(
                        issuer: baseUrl,
                        audience: baseUrl,
                        claims: claims,
                        expires: _systemClock.GetNow.AddDays(2),
                        signingCredentials: signinCredentials);

                    var viewModel = new AuthenticationResultDto()
                    {
                        FailureReason       = AuthenticationFailureReason.None,
                        AuthenticationToken = new JwtSecurityTokenHandler().WriteToken(tokenOptions)
                    };

                    return(Ok(viewModel));
                }

                _logger.LogWarning(LoggingEvents.GenerateItems, "Other authentication failure");
                return(StatusCode(500, new AuthenticationResultDto()
                {
                    FailureReason = AuthenticationFailureReason.Other
                }));
            }
            catch (Exception ex)
            {
                _logger.LogError(LoggingEvents.Exception, ex, "An unexpeceted error occurred");
                return(StatusCode(500, new AuthenticationResultDto()
                {
                    FailureReason = AuthenticationFailureReason.Other
                }));
            }
        }
Пример #15
0
        public async Task <IActionResult> Post([FromBody] Login model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(model.Email);

                if (user != null)
                {
                    if (user.IsLocked)
                    {
                        return(BadRequest("User is currently locked, ask administrator to unlock you!"));
                    }

                    if (user.IsDeleted)
                    {
                        return(BadRequest("User is deleted, ask administrator for reinstatement!"));
                    }

                    var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);

                    if (result.Succeeded)
                    {
                        var claims = new[]
                        {
                            new Claim(JwtRegisteredClaimNames.Sub, user.Id),
                            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                            new Claim(JwtRegisteredClaimNames.UniqueName, user.Email),
                            new Claim(JwtRegisteredClaimNames.Email, user.UserName)
                        };

                        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("mysupersedkjhulfgyuerfw344cret"));

                        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                        var token = new JwtSecurityToken(
                            issuer: "http://binmakdev.dedicated.co.za:81",
                            audience: "http://binmakdev.dedicated.co.za:80",
                            claims: claims,
                            expires: DateTime.UtcNow.AddDays(29),
                            signingCredentials: creds);

                        var results = new
                        {
                            token              = new JwtSecurityTokenHandler().WriteToken(token),
                            expiration         = token.ValidTo,
                            userId             = token.Subject,
                            username           = user.UserName,
                            firstName          = user.FirstName,
                            lastName           = user.LastName,
                            isSuperAdmin       = user.IsSuperAdmin,
                            isBinmak           = user.IsBinmak,
                            isUser             = user.IsUser,
                            isGuest            = user.IsGuest,
                            isAdmin            = user.IsAdmin,
                            role               = user.RoleId,
                            binmakModules      = GetBinmakModulesByUser(user.Id),
                            assignedAssetNodes = GetAssetNodesByUser(user.Id),
                            topAssetNode       = GetTopAssetNodesByUser(user.Id),
                        };

                        return(Created("", results));
                    }
                    else
                    {
                        return(BadRequest("Login Failed, Wrong Username/Password"));
                    }
                }
                else
                {
                    return(BadRequest("Account Does Not Exist, Please Register First"));
                }
            }
            return(BadRequest("Login Failed"));
        }
Пример #16
0
        //TODO shoud be moved to another layer
        private async Task <User> CreateUser(User user)
        {
            User newUser = null;
            // users created by non-administrators must be verified
            bool verified = !(!User.IsInRole(Constants.AdminRole) && user.Username != Constants.HostUser);

            IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username);

            if (identityuser == null)
            {
                identityuser                = new IdentityUser();
                identityuser.UserName       = user.Username;
                identityuser.Email          = user.Email;
                identityuser.EmailConfirmed = verified;
                var result = await _identityUserManager.CreateAsync(identityuser, user.Password);

                if (result.Succeeded)
                {
                    user.LastLoginOn   = null;
                    user.LastIPAddress = "";
                    newUser            = _users.AddUser(user);
                    if (!verified)
                    {
                        Notification notification = new Notification();
                        notification.SiteId     = user.SiteId;
                        notification.FromUserId = null;
                        notification.ToUserId   = newUser.UserId;
                        notification.ToEmail    = "";
                        notification.Subject    = "User Account Verification";
                        string token = await _identityUserManager.GenerateEmailConfirmationTokenAsync(identityuser);

                        string url = HttpContext.Request.Scheme + "://" + _tenants.GetAlias().Name + "/login?name=" + user.Username + "&token=" + WebUtility.UrlEncode(token);
                        notification.Body        = "Dear " + user.DisplayName + ",\n\nIn Order To Complete The Registration Of Your User Account Please Click The Link Displayed Below:\n\n" + url + "\n\nThank You!";
                        notification.ParentId    = null;
                        notification.CreatedOn   = DateTime.UtcNow;
                        notification.IsDelivered = false;
                        notification.DeliveredOn = null;
                        _notifications.AddNotification(notification);
                    }

                    // assign to host role if this is the host user ( initial installation )
                    if (user.Username == Constants.HostUser)
                    {
                        int      hostroleid = _roles.GetRoles(user.SiteId, true).Where(item => item.Name == Constants.HostRole).FirstOrDefault().RoleId;
                        UserRole userrole   = new UserRole();
                        userrole.UserId        = newUser.UserId;
                        userrole.RoleId        = hostroleid;
                        userrole.EffectiveDate = null;
                        userrole.ExpiryDate    = null;
                        _userRoles.AddUserRole(userrole);
                    }

                    // add folder for user
                    Folder folder = _folders.GetFolder(user.SiteId, "Users\\");
                    if (folder != null)
                    {
                        _folders.AddFolder(new Folder
                        {
                            SiteId      = folder.SiteId, ParentId = folder.FolderId, Name = "My Folder", Path = folder.Path + newUser.UserId.ToString() + "\\", Order = 1, IsSystem = true,
                            Permissions = "[{\"PermissionName\":\"Browse\",\"Permissions\":\"[" + newUser.UserId.ToString() + "]\"},{\"PermissionName\":\"View\",\"Permissions\":\"All Users\"},{\"PermissionName\":\"Edit\",\"Permissions\":\"[" +
                                          newUser.UserId.ToString() + "]\"}]"
                        });
                    }
                }
            }
            else
            {
                var result = await _identitySignInManager.CheckPasswordSignInAsync(identityuser, user.Password, false);

                if (result.Succeeded)
                {
                    newUser = _users.GetUser(user.Username);
                }
            }

            if (newUser != null && user.Username != Constants.HostUser)
            {
                // add auto assigned roles to user for site
                List <Role> roles = _roles.GetRoles(user.SiteId).Where(item => item.IsAutoAssigned).ToList();
                foreach (Role role in roles)
                {
                    UserRole userrole = new UserRole();
                    userrole.UserId        = newUser.UserId;
                    userrole.RoleId        = role.RoleId;
                    userrole.EffectiveDate = null;
                    userrole.ExpiryDate    = null;
                    _userRoles.AddUserRole(userrole);
                }
            }

            if (newUser != null)
            {
                newUser.Password = ""; // remove sensitive information
                _logger.Log(user.SiteId, LogLevel.Information, this, LogFunction.Create, "User Added {User}", newUser);
            }

            return(newUser);
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (String.IsNullOrEmpty(Input.References[2].CompanyName))
            {
                ModelState.ClearValidationState("Input.References[2].Email");
                ModelState.ClearValidationState("Input.References[2].SureName");
                ModelState.ClearValidationState("Input.References[2].FirstName");
                ModelState.ClearValidationState("Input.References[2].Telephone");
                ModelState.ClearValidationState("Input.References[2].CompanyName");
                ModelState.MarkFieldValid("Input.References[2].Email");
                ModelState.MarkFieldValid("Input.References[2].SureName");
                ModelState.MarkFieldValid("Input.References[2].FirstName");
                ModelState.MarkFieldValid("Input.References[2].Telephone");
                ModelState.MarkFieldValid("Input.References[2].CompanyName");
            }

            var user = new ApplicationUser
            {
                FirstName = Input.FirstName,
                LastName  = Input.LastName,
                UserName  = Input.Email,
                Email     = Input.Email,
                Type      = Domain.Enums.UserType.SuperUser
            };

            foreach (var item in _userManager.PasswordValidators)
            {
                var password = await item.ValidateAsync(_userManager, user, Input.Password);

                if (!password.Succeeded)
                {
                    foreach (var error in password.Errors)
                    {
                        ModelState.AddModelError("Input.Password", string.Format("[{0}] - {1}", error.Code, error.Description));
                    }
                }
            }

            if (!ModelState.IsValid)
            {
                return(Page());
            }

            Input.TradingName = TermInput.TradingName;
            Input.AvgMonthly  = TermInput.AvgMonthly;
            Input.AgreeTOC    = TermInput.AgreeTOC;

            var existingUser = _ctx.Users
                               .Include(x => x.Accounts)
                               .FirstOrDefault(x => x.Email == Input.Email);

            if (existingUser != null)
            {
                var canSignIn = await _signInManager.CheckPasswordSignInAsync(existingUser, Input.Password, false);

                if (canSignIn.Succeeded)
                {
                    await _signInManager.SignInAsync(existingUser, false);

                    var accountId = await new CreateAccount(_ctx, _emailSender)
                                    .Do(new CreateAccount.Request
                    {
                        UserId = existingUser.Id,
                        Input  = Input
                    });

                    await SetCartAddress(accountId);

                    await PlaceOrder(accountId, existingUser.Id);

                    return(RedirectToPage("/Index"));
                }
                return(Page());
            }

            var result = await _userManager.CreateAsync(user, Input.Password);

            if (result.Succeeded)
            {
                await _userManager.AddClaimAsync(user, new Claim("type", "superuser"));

                await _signInManager.SignInAsync(user, false);

                var accountId = await new CreateAccount(_ctx, _emailSender)
                                .Do(new CreateAccount.Request
                {
                    UserId = user.Id,
                    Input  = Input
                });

                await SetCartAddress(accountId);

                await PlaceOrder(accountId, user.Id);
            }

            return(RedirectToPage("/Accounts/GuestBusinessTermProfile"));
        }
Пример #18
0
        public async Task <bool> ValidateUser(User user, string password)
        {
            var result = await _signInManager.CheckPasswordSignInAsync(user, password, false);

            return(result.Succeeded);
        }
        public async Task <SignInResult> SignInUser(User user, string password)
        {
            var result = await _signInManager.CheckPasswordSignInAsync(user, password, false);

            return(result);
        }
Пример #20
0
        /// <inheritdoc cref="ILoginService{TEntity}.ValidateCredentialsAsync" />
        public async Task <SignInResult> ValidateCredentialsAsync(Customer user, string password)
        {
            var result = await signInManager.CheckPasswordSignInAsync(user, password, false);

            return(result);
        }
Пример #21
0
 public async Task <SignInResult> CheckPasswordSignInAsync(User user, string password, bool lockoutOnFailure)
 {
     return(await _signInManager.CheckPasswordSignInAsync(user, password, lockoutOnFailure));
 }
Пример #22
0
        private async Task <User> CreateUser(User user)
        {
            User newUser = null;

            bool verified;
            bool allowregistration;

            if (user.Username == UserNames.Host || User.IsInRole(RoleNames.Admin))
            {
                verified          = true;
                allowregistration = true;
            }
            else
            {
                verified          = false;
                allowregistration = _sites.GetSite(user.SiteId).AllowRegistration;
            }

            if (allowregistration)
            {
                IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username);

                if (identityuser == null)
                {
                    identityuser                = new IdentityUser();
                    identityuser.UserName       = user.Username;
                    identityuser.Email          = user.Email;
                    identityuser.EmailConfirmed = verified;
                    var result = await _identityUserManager.CreateAsync(identityuser, user.Password);

                    if (result.Succeeded)
                    {
                        user.LastLoginOn   = null;
                        user.LastIPAddress = "";
                        newUser            = _users.AddUser(user);
                        if (!verified)
                        {
                            string token = await _identityUserManager.GenerateEmailConfirmationTokenAsync(identityuser);

                            string url          = HttpContext.Request.Scheme + "://" + _alias.Name + "/login?name=" + user.Username + "&token=" + WebUtility.UrlEncode(token);
                            string body         = "Dear " + user.DisplayName + ",\n\nIn Order To Complete The Registration Of Your User Account Please Click The Link Displayed Below:\n\n" + url + "\n\nThank You!";
                            var    notification = new Notification(user.SiteId, null, newUser, "User Account Verification", body, null);
                            _notifications.AddNotification(notification);
                        }

                        // assign to host role if this is the host user ( initial installation )
                        if (user.Username == UserNames.Host)
                        {
                            int      hostroleid = _roles.GetRoles(user.SiteId, true).Where(item => item.Name == RoleNames.Host).FirstOrDefault().RoleId;
                            UserRole userrole   = new UserRole();
                            userrole.UserId        = newUser.UserId;
                            userrole.RoleId        = hostroleid;
                            userrole.EffectiveDate = null;
                            userrole.ExpiryDate    = null;
                            _userRoles.AddUserRole(userrole);
                        }

                        // add folder for user
                        Folder folder = _folders.GetFolder(user.SiteId, Utilities.PathCombine("Users", Path.DirectorySeparatorChar.ToString()));
                        if (folder != null)
                        {
                            _folders.AddFolder(new Folder
                            {
                                SiteId      = folder.SiteId,
                                ParentId    = folder.FolderId,
                                Name        = "My Folder",
                                Type        = FolderTypes.Private,
                                Path        = Utilities.PathCombine(folder.Path, newUser.UserId.ToString(), Path.DirectorySeparatorChar.ToString()),
                                Order       = 1,
                                IsSystem    = true,
                                Permissions = new List <Permission>
                                {
                                    new Permission(PermissionNames.Browse, newUser.UserId, true),
                                    new Permission(PermissionNames.View, RoleNames.Everyone, true),
                                    new Permission(PermissionNames.Edit, newUser.UserId, true)
                                }.EncodePermissions()
                            });
                        }
                    }
                }
                else
                {
                    var result = await _identitySignInManager.CheckPasswordSignInAsync(identityuser, user.Password, false);

                    if (result.Succeeded)
                    {
                        newUser = _users.GetUser(user.Username);
                    }
                }

                if (newUser != null && user.Username != UserNames.Host)
                {
                    // add auto assigned roles to user for site
                    List <Role> roles = _roles.GetRoles(user.SiteId).Where(item => item.IsAutoAssigned).ToList();
                    foreach (Role role in roles)
                    {
                        UserRole userrole = new UserRole();
                        userrole.UserId        = newUser.UserId;
                        userrole.RoleId        = role.RoleId;
                        userrole.EffectiveDate = null;
                        userrole.ExpiryDate    = null;
                        _userRoles.AddUserRole(userrole);
                    }
                }

                if (newUser != null)
                {
                    newUser.Password = ""; // remove sensitive information
                    _logger.Log(user.SiteId, LogLevel.Information, this, LogFunction.Create, "User Added {User}", newUser);
                }
            }
            else
            {
                _logger.Log(user.SiteId, LogLevel.Error, this, LogFunction.Create, "User Registration Is Not Enabled For Site. User Was Not Added {User}", user);
            }

            return(newUser);
        }
Пример #23
0
        public async Task <IActionResult> Exchange(OpenIdConnectRequest request)
        {
            if (request.IsPasswordGrantType())
            {
                var user = await _userManager.FindByEmailAsync(request.Username) ?? await _userManager.FindByNameAsync(request.Username);

                if (user == null)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "Please check that your email and password is correct"
                    }));
                }

                // Ensure the user is enabled.
                if (!user.IsEnabled)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The specified user account is disabled"
                    }));
                }


                // Validate the username/password parameters and ensure the account is not locked out.
                var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, true);

                // Ensure the user is not already locked out.
                if (result.IsLockedOut)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The specified user account has been suspended"
                    }));
                }

                // Reject the token request if two-factor authentication has been enabled by the user.
                if (result.RequiresTwoFactor)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "Invalid login procedure"
                    }));
                }

                // Ensure the user is allowed to sign in.
                if (result.IsNotAllowed)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The specified user is not allowed to sign in"
                    }));
                }

                if (!result.Succeeded)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "Please check that your email and password is correct"
                    }));
                }



                // Create a new authentication ticket.
                var ticket = await CreateTicketAsync(request, user);

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }
            else if (request.IsRefreshTokenGrantType())
            {
                // Retrieve the claims principal stored in the refresh token.
                var info = await HttpContext.AuthenticateAsync(OpenIddictServerDefaults.AuthenticationScheme);

                // Retrieve the user profile corresponding to the refresh token.
                // Note: if you want to automatically invalidate the refresh token
                // when the user password/roles change, use the following line instead:
                // var user = _signInManager.ValidateSecurityStampAsync(info.Principal);
                var user = await _userManager.GetUserAsync(info.Principal);

                if (user == null)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The refresh token is no longer valid"
                    }));
                }

                // Ensure the user is still allowed to sign in.
                if (!await _signInManager.CanSignInAsync(user))
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The user is no longer allowed to sign in"
                    }));
                }

                // Create a new authentication ticket, but reuse the properties stored
                // in the refresh token, including the scopes originally granted.
                var ticket = await CreateTicketAsync(request, user);

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }
            return(BadRequest(new OpenIdConnectResponse
            {
                Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
                ErrorDescription = "The specified grant type is not supported"
            }));
        }
        public async Task <IActionResult> Exchange(OpenIdConnectRequest request)
        {
            if (request.IsPasswordGrantType())
            {
                var user = await _userManager.FindByNameAsync(request.Username);

                if (user == null)
                {
                    return(BadRequest(Constants.Errors.UsernamePasswordInvalid));
                }

                if (user.LockoutEnd.HasValue && user.LockoutEnd.Value >= DateTimeOffset.Now)
                {
                    return(BadRequest(user.LockoutEnd.Value == DateTimeOffset.MaxValue ? Constants.Errors.UserBlockedError : Constants.Errors.LoginAttemptsExceededError));
                }

                // Validate the username/password parameters and ensure the account is not locked out.
                var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, lockoutOnFailure : true);

                if (!result.Succeeded)
                {
                    return(BadRequest(Constants.Errors.UsernamePasswordInvalid));
                }

                // Create a new authentication ticket.
                var ticket = await CreateTicketAsync(request, user);

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }

            else if (request.IsRefreshTokenGrantType())
            {
                // Retrieve the claims principal stored in the refresh token.
                var info = await HttpContext.AuthenticateAsync(OpenIdConnectServerDefaults.AuthenticationScheme);

                // Retrieve the user profile corresponding to the refresh token.
                // Note: if you don't want to automatically invalidate the refresh token
                // when the user password/roles change, use the following line instead:
                // var user = await _userManager.GetUserAsync(info.Principal);
                var user = await _signInManager.ValidateSecurityStampAsync(info.Principal);

                if (user == null)
                {
                    return(BadRequest(Constants.Errors.RefreshTokenExpired));
                }

                // Ensure the user is still allowed to sign in.
                if (!await _signInManager.CanSignInAsync(user))
                {
                    return(BadRequest(Constants.Errors.LoginRequired));
                }

                // Create a new authentication ticket, but reuse the properties stored
                // in the refresh token, including the scopes originally granted.
                var ticket = await CreateTicketAsync(request, user, info.Properties);

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }

            return(BadRequest(Constants.Errors.UnsupportedGrantType));
        }
Пример #25
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // the user clicked the "cancel" button
            if (button != "login")
            {
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    if (context.IsNativeClient())
                    {
                        // The client is native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(this.LoadingPage("Redirect", model.ReturnUrl));
                    }

                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                // validate username/password against in-memory store

                /*if (_users.ValidateCredentials(model.Username, model.Password))
                 * {
                 *  var user = _users.FindByUsername(model.Username);
                 *  await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username, clientId: context?.Client.ClientId));
                 *
                 *  // only set explicit expiration here if user chooses "remember me".
                 *  // otherwise we rely upon expiration configured in cookie middleware.
                 *  AuthenticationProperties props = null;
                 *  if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                 *  {
                 *      props = new AuthenticationProperties
                 *      {
                 *          IsPersistent = true,
                 *          ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                 *      };
                 *  };
                 *
                 *  // issue authentication cookie with subject ID and username
                 *  var isuser = new IdentityServerUser(user.SubjectId)
                 *  {
                 *      DisplayName = user.Username
                 *  };
                 *
                 *  await HttpContext.SignInAsync(isuser, props);
                 *
                 *  if (context != null)
                 *  {
                 *      if (context.IsNativeClient())
                 *      {
                 *          // The client is native, so this change in how to
                 *          // return the response is for better UX for the end user.
                 *          return this.LoadingPage("Redirect", model.ReturnUrl);
                 *      }
                 *
                 *      // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                 *      return Redirect(model.ReturnUrl);
                 *  }
                 *
                 *  // request for a local page
                 *  if (Url.IsLocalUrl(model.ReturnUrl))
                 *  {
                 *      return Redirect(model.ReturnUrl);
                 *  }
                 *  else if (string.IsNullOrEmpty(model.ReturnUrl))
                 *  {
                 *      return Redirect("~/");
                 *  }
                 *  else
                 *  {
                 *      // user might have clicked on a malicious link - should be logged
                 *      throw new Exception("invalid return URL");
                 *  }
                 * }*/

                var user = await _signInManager.UserManager.FindByNameAsync(model.Username);

                // validate username/password using ASP.NET Identity
                if (user != null && (await _signInManager.CheckPasswordSignInAsync(user, model.Password, true)) == SignInResult.Success)
                {
                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId : context?.Client.ClientId));

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    AuthenticationProperties props = null;
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }
                    ;

                    // issue authentication cookie with subject ID and username
                    var isuser = new IdentityServerUser(user.Id)
                    {
                        DisplayName = user.UserName
                    };

                    await HttpContext.SignInAsync(isuser, props);

                    if (context != null)
                    {
                        if (context.IsNativeClient())
                        {
                            // The client is native, so this change in how to
                            // return the response is for better UX for the end user.
                            return(this.LoadingPage("Redirect", model.ReturnUrl));
                        }

                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        return(Redirect(model.ReturnUrl));
                    }

                    // request for a local page
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    else if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    else
                    {
                        // user might have clicked on a malicious link - should be logged
                        throw new Exception("invalid return URL");
                    }
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials", clientId : context?.Client.ClientId));

                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Пример #26
0
 public Task <SignInResult> ValidateCredentials(User user, string password)
 {
     return(_signInManager.CheckPasswordSignInAsync(user, password, true));
 }
Пример #27
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            var user = await _userManager.FindByNameAsync(userForLoginDto.Username);

            if (user != null)
            {
                //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                //var callbackUrl = Url.Page(
                //    "/Account/ConfirmEmail",
                //    pageHandler: null,
                //    values: new { userId = user.Id, code = code },
                //    protocol: Request.Scheme);

                //await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                //    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                ////await _signInManager.SignInAsync(user, isPersistent: false);
                //return LocalRedirect(returnUrl);

                var result = await _signInManager
                             .CheckPasswordSignInAsync(user, userForLoginDto.Password, true);

                var UserLockoutDate = await _userManager.GetLockoutEndDateAsync(user);

                if (UserLockoutDate == null || UserLockoutDate < DateTime.Now)
                {
                    user.PenaltEnable = false;
                }

                if (result.Succeeded)
                {
                    user.NumberOfLockouts = 0;
                    await _userManager.SetLockoutEndDateAsync(user, null);

                    await _userManager.UpdateAsync(user);

                    var appUser = await _userManager.Users.Include(p => p.Photos)
                                  .FirstOrDefaultAsync(u => u.NormalizedUserName == userForLoginDto.Username.ToUpper());

                    var userToReturn = _mapper.Map <UserForListDto>(appUser);

                    return(Ok(new
                    {
                        token = GenerateJwtToken(appUser).Result,
                        user = userToReturn
                    }));
                }
                else if (result.IsLockedOut)
                {
                    if (!user.PenaltEnable)
                    {
                        user.PenaltEnable = true;
                        DateTimeOffset Penalt = DateTimeOffset.Now.AddMinutes(5 * user.NumberOfLockouts);
                        await _userManager.SetLockoutEndDateAsync(user, Penalt);
                    }

                    var LockoutTime = await _userManager.GetLockoutEndDateAsync(user);

                    var RemainingTime = LockoutTime.Value.Subtract(DateTime.Now).Minutes;

                    return(new CustomUnauthorizedResult(string.Format(Mensagens.LoginBloqueado,
                                                                      user.NumberOfLockouts,
                                                                      RemainingTime)));
                }
            }

            user.NumberOfLockouts++;
            await _userManager.UpdateAsync(user);

            return(Unauthorized());
        }
        public async Task <IActionResult> Exchange()
        {
            var request = HttpContext.GetOpenIddictServerRequest() ??
                          throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

            if (request.IsPasswordGrantType())
            {
                var user = await _userManager.FindByNameAsync(request.Username);

                if (user == null)
                {
                    return(Forbid(
                               authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                               properties: new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidGrant,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The username/password couple is invalid."
                    })));
                }

                // Validate the username/password parameters and ensure the account is not locked out.
                var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, lockoutOnFailure : true);

                if (!result.Succeeded)
                {
                    return(Forbid(
                               authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                               properties: new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidGrant,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The username/password couple is invalid."
                    })));
                }

                var principal = await _signInManager.CreateUserPrincipalAsync(user);

                // Note: in this sample, the granted scopes match the requested scope
                // but you may want to allow the user to uncheck specific scopes.
                // For that, simply restrict the list of scopes before calling SetScopes.
                principal.SetScopes(request.GetScopes());
                principal.SetResources(await _scopeManager.ListResourcesAsync(principal.GetScopes()).ToListAsync());

                foreach (var claim in principal.Claims)
                {
                    claim.SetDestinations(GetDestinations(claim, principal));
                }

                // Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens.
                return(SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));
            }

            else if (request.IsAuthorizationCodeGrantType() || request.IsDeviceCodeGrantType() || request.IsRefreshTokenGrantType())
            {
                // Retrieve the claims principal stored in the authorization code/device code/refresh token.
                var principal = (await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)).Principal;

                // Retrieve the user profile corresponding to the authorization code/refresh token.
                // Note: if you want to automatically invalidate the authorization code/refresh token
                // when the user password/roles change, use the following line instead:
                // var user = _signInManager.ValidateSecurityStampAsync(info.Principal);
                var user = await _userManager.GetUserAsync(principal);

                if (user == null)
                {
                    return(Forbid(
                               authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                               properties: new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidGrant,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The token is no longer valid."
                    })));
                }

                // Ensure the user is still allowed to sign in.
                if (!await _signInManager.CanSignInAsync(user))
                {
                    return(Forbid(
                               authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                               properties: new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidGrant,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The user is no longer allowed to sign in."
                    })));
                }

                foreach (var claim in principal.Claims)
                {
                    claim.SetDestinations(GetDestinations(claim, principal));
                }

                // Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens.
                return(SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));
            }

            throw new InvalidOperationException("The specified grant type is not supported.");
        }
Пример #29
0
        public async Task <IActionResult> LogIn([FromBody] UserLogin userLogin)
        {
            var user = await _userManager.FindByEmailAsync(userLogin.UserName) ?? await _userManager.FindByNameAsync(userLogin.UserName);

            if (user == null)
            {
                ModelState.AddModelError("username", "用户不存在");
                return(BadRequest(ModelState));
            }
            // Ensure the user is enabled.
            if (user.IsDisabled)
            {
                ModelState.AddModelError("username", "用户不存在");
                return(BadRequest(ModelState));
            }
            // Validate the username/password parameters and ensure the account is not locked out.
            var result = await _signInManager.CheckPasswordSignInAsync(user, userLogin.Password, true);

            // Ensure the user is not already locked out.
            if (result.IsLockedOut)
            {
                ModelState.AddModelError("username", "用户已被锁定");
                return(BadRequest(ModelState));
            }

            // Reject the token request if two-factor authentication has been enabled by the user.
            if (result.RequiresTwoFactor)
            {
                ModelState.AddModelError(string.Empty, "双因素验证失败");
                return(BadRequest(ModelState));
            }

            // Ensure the user is allowed to sign in.
            if (result.IsNotAllowed)
            {
                ModelState.AddModelError(string.Empty, "指定用户不允许登录");
                return(BadRequest(ModelState));
            }

            if (!result.Succeeded)
            {
                ModelState.AddModelError(string.Empty, "请检查用户名或密码是否正确");
                return(BadRequest(ModelState));
            }

            // var principal = await _signInManager.CreateUserPrincipalAsync(user);
            var tokenHandler = new JwtSecurityTokenHandler();
            //var key = Encoding.ASCII.GetBytes(Consts.Secret);
            var authTime        = DateTime.UtcNow;
            var expiresAt       = authTime.AddMinutes(30);
            var key             = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration["SigningKey"]));
            var roles           = _roleManager.Roles.Include(x => x.Users).Where(c => (c.Users.Select(x => x.UserId)).Contains(user.Id)).ToList();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    //new Claim(JwtClaimTypes.Audience,"api"),
                    //new Claim(JwtClaimTypes.Issuer,"http://localhost:5000"),
                    new Claim(JwtClaimTypes.Id, user.Id.ToString()),
                    new Claim(JwtClaimTypes.Name, user.Name),
                    new Claim(JwtClaimTypes.Email, user.Email),
                    new Claim(JwtClaimTypes.PhoneNumber, user.PhoneNumber),
                    new Claim(JwtClaimTypes.Role, string.Join(",", user.Roles))
                }),
                Expires            = expiresAt,
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature)
            };

            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);



            return(Ok(new
            {
                access_token = tokenString,
                token_type = "Bearer",
                id_token = user.Id.ToString(),
                profile = new
                {
                    roles = roles?.Select(x => x.Name).ToArray(),
                    auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
                    expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
                }
            }));
        }
Пример #30
0
        private async Task <IActionResult> ExchangePasswordGrantType(OpenIdConnectRequest request)
        {
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId);

            if (application == null)
            {
                return(View("Error", new ErrorViewModel
                {
                    Error = OpenIdConnectConstants.Errors.InvalidClient,
                    ErrorDescription = T["The specified 'client_id' parameter is invalid."]
                }));
            }

            var user = await _userManager.FindByNameAsync(request.Username);

            if (user == null)
            {
                return(BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = T["The username/password couple is invalid."]
                }));
            }

            var authorizations = await _authorizationManager.FindAsync(
                subject : await _userManager.GetUserIdAsync(user),
                client : await _applicationManager.GetIdAsync(application),
                status : OpenIddictConstants.Statuses.Valid,
                type : OpenIddictConstants.AuthorizationTypes.Permanent,
                scopes : ImmutableArray.CreateRange(request.GetScopes()));

            // If the application is configured to use external consent,
            // reject the request if no existing authorization can be found.
            switch (await _applicationManager.GetConsentTypeAsync(application))
            {
            case OpenIddictConstants.ConsentTypes.External when authorizations.IsEmpty:
                return(BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.ConsentRequired,
                    ErrorDescription = T["The logged in user is not allowed to access this client application."]
                }));
            }

            var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, lockoutOnFailure : true);

            if (result.IsNotAllowed)
            {
                return(BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = T["The specified user is not allowed to sign in."]
                }));
            }
            else if (result.RequiresTwoFactor)
            {
                return(BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = T["The specified user is not allowed to sign in using the password method."]
                }));
            }
            else if (!result.Succeeded)
            {
                return(BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = T["The username/password couple is invalid."]
                }));
            }

            var ticket = await CreateTicketAsync(user, application, authorizations.LastOrDefault(), request);

            return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
        }