public async Task <string> GenerateTokenCredential(LoginInput input)
        {
            var rpcParams = new Dictionary <string, object>()
            {
                { "input", new { input.UserName, input.Password } }
            };


            var loginResult = await _serviceProxyProvider.Invoke <LoginResult>(rpcParams, AppConfig.AuthenticationRoutePath, AppConfig.AuthenticationServiceKey);

            if (loginResult.ResultType == LoginResultType.Fail)
            {
                throw new AuthException(loginResult.ErrorMessage);
            }
            if (loginResult.ResultType == LoginResultType.Error)
            {
                throw new BusinessException(loginResult.ErrorMessage);
            }
            var jwtHader = new Dictionary <string, object>()
            {
                { "timeStamp", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") },
                { "typ", "JWT" },
                { "alg", AppConfig.JwtConfig.EncryptionAlgorithm }
            };
            var payload = loginResult.PayLoad;

            payload.Add("iss", AppConfig.JwtConfig.Iss);
            payload.Add("aud", AppConfig.JwtConfig.Aud);
            payload.Add("iat", DateTime.Now);
            payload.Add("exp", DateTime.Now.AddMinutes(AppConfig.JwtConfig.Period));
            //payload.Add("ast", accessSystemType);
            return(_jwtTokenProvider.GenerateToken(jwtHader, payload, AppConfig.JwtConfig.SecretKey, AppConfig.JwtConfig.EncryptionAlgorithm));
        }
Пример #2
0
        public async Task <BLSingleResponse <LoginRespDto> > LoginAsync(LoginDto model)
        {
            var response = new BLSingleResponse <LoginRespDto>();

            //new PasswordHasher<UserDto>().HashPassword(model.Username, pPassword);

            try
            {
                var signInResul = await _accountManager.SignInAsync(model.Username, model.Password, model.RememberMe);

                if (signInResul == SignInResult.Failed)
                {
                    response.Data = new LoginRespDto("Username or Password is invalid.");
                }
                else if (signInResul == SignInResult.TwoFactorRequired)
                {
                    response.Data = new LoginRespDto("This User does not confirmed email or phone.");
                }
                else if (signInResul == SignInResult.LockedOut)
                {
                    response.Data = new LoginRespDto("This User is currently locked out.");
                }
                else
                {
                    var user = await _accountManager.UserManager.FindByNameAsync(model.Username);

                    var role = await _accountManager.GetRoleByUserAsync(user);

                    if (role != null)
                    {
                        var tokenResul = _tokenProvider.GenerateToken(user, role);
                        response.Data = new LoginRespDto {
                            Token = tokenResul.Token, ExpirationDate = tokenResul.ExpirationDate
                        };
                    }
                    else
                    {
                        response.Data = new LoginRespDto("This User has no role assigned.");
                        await _accountManager.SignOutAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                HandleSVCException(response, ex);
            }

            return(response);
        }
Пример #3
0
        public async Task <IActionResult> Login([FromBody] Auth.LoginRequest request)
        {
            IdentityUser identityUser;

            _logger.LogInformation($"Login request from {request.Username}");

            if (!ModelState.IsValid || request == null || (identityUser = await ValidateUser(request)) == null)
            {
                _logger.LogError($"Login failed for {request.Username}");
                return(new BadRequestObjectResult(new { Message = "Login failed" }));
            }

            var newToken = _tokenProvider.GenerateToken(identityUser);

            _logger.LogInformation($"Login successful for {request.Username}");
            return(Ok(new { Token = newToken, Message = "Success" }));
        }
        public async Task <string> GenerateTokenCredential(IDictionary <string, object> rpcParams)
        {
            LoginResult loginResult;

            if (AppConfig.AuthorizationServiceKey.IsNullOrEmpty())
            {
                loginResult = await _serviceProxyProvider.Invoke <LoginResult>(rpcParams, AppConfig.AuthenticationRoutePath);
            }
            else
            {
                loginResult = await _serviceProxyProvider.Invoke <LoginResult>(rpcParams, AppConfig.AuthenticationRoutePath, AppConfig.AuthenticationServiceKey);
            }
            if (loginResult == null)
            {
                throw new BusinessException("当前系统无法登陆,请稍后重试");
            }
            if (loginResult.ResultType == LoginResultType.Fail)
            {
                throw new AuthException(loginResult.ErrorMessage);
            }
            if (loginResult.ResultType == LoginResultType.Error)
            {
                throw new BusinessException(loginResult.ErrorMessage);
            }
            var jwtHader = new Dictionary <string, object>()
            {
                { "timeStamp", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") },
                { "typ", "JWT" },
                { "alg", AppConfig.JwtConfig.EncryptionAlgorithm }
            };
            var payload = loginResult.PayLoad;

            payload.Add("iss", AppConfig.JwtConfig.Iss);
            payload.Add("aud", AppConfig.JwtConfig.Aud);
            payload.Add("iat", DateTime.Now);
            payload.Add("exp", DateTime.Now.AddMinutes(AppConfig.JwtConfig.Period));
            //payload.Add("ast", accessSystemType);
            return(_jwtTokenProvider.GenerateToken(jwtHader, payload, AppConfig.JwtConfig.SecretKey, AppConfig.JwtConfig.EncryptionAlgorithm));
        }
Пример #5
0
        public async Task <BLSingleResponse <string> > HandleExternalLoginAsync()
        {
            var response = new BLSingleResponse <string>();

            try
            {
                //retrieves user information stored in a cookie
                var extLoginInfo = await _accountManager.GetExternalLoginInfoAsync();

                //check if the user has previously logged in using the external login provider
                var result = await _accountManager.ExternalLoginSignInAsync(extLoginInfo.LoginProvider, extLoginInfo.ProviderKey, isPersistent : false);

                if (result.Succeeded) //user does already exist
                {
                    var user = await _accountManager.UserManager.FindByNameAsync(_accountManager.Context.User.Identity.Name);

                    var role = await _accountManager.GetRoleByUserAsync(user);

                    response.Data = _tokenProvider.GenerateToken(user, role).Token;
                }
                else //user does not exist yet
                {
                    var defaultRole = new ApplicationRole(RolesEnum.STUDENT.GetDescription());
                    var email       = extLoginInfo.Principal.FindFirstValue(ClaimTypes.Email);

                    ApplicationUser newUser = _userManager.Users.SingleOrDefault(u => u.Email == email);

                    if (newUser == null)
                    {
                        newUser = new ApplicationUser(email.Split('@')[0], email,
                                                      extLoginInfo.Principal.FindFirstValue(ClaimTypes.GivenName),
                                                      extLoginInfo.Principal.FindFirstValue(ClaimTypes.Surname))
                        {
                            EmailConfirmed = true
                        };

                        var createResult = await _userManager.CreateAsync(newUser, new List <ApplicationRole> {
                            defaultRole
                        });

                        if (!createResult.Succeeded)
                        {
                            throw new Exception(createResult.Errors.Select(e => e.Description)
                                                .Aggregate((errors, error) => $"{errors}, {error}"));
                        }
                    }

                    //associate the new user with the external login provider
                    await _userManager.AddLoginAsync(newUser, extLoginInfo);

                    var newUserClaims = extLoginInfo.Principal.Claims;
                    newUserClaims.Append(new Claim("userid", newUser.Id.ToString()));
                    newUserClaims.Append(new Claim(ClaimTypes.Role, defaultRole.Name));

                    await _userManager.AddClaimsAsync(newUser, newUserClaims);

                    await _accountManager.SignInAsync(newUser.UserName, newUser.PasswordHash, false);

                    response.Data = _tokenProvider.GenerateToken(newUser, defaultRole).Token;
                }
            }

            catch (Exception ex)
            {
                HandleSVCException(ex);
            }

            return(response);
        }
Пример #6
0
        public async Task <ActionResult> LoginAccount([FromBody] AuthCM authCM)
        {
            if (string.IsNullOrEmpty(authCM.LoginType))
            {
                return(BadRequest());
            }

            var    auth = FirebaseAdmin.Auth.FirebaseAuth.DefaultInstance;
            string email;

            try
            {
                var token = await auth.VerifyIdTokenAsync(authCM.IdToken);

                email = (string)token.Claims[TokenClaims.EMAIL];
            }
            catch (Exception e)
            {
                return(Unauthorized(e.Message));
            }

            AuthVM response;

            try
            {
                //string email = "*****@*****.**";
                Account accountCreated = _accountService.GetByEmail(email);

                if (accountCreated == null)
                {
                    Gallery gallery = null;
                    if (authCM.Avatar != null)
                    {
                        gallery = new Gallery()
                        {
                            Name        = authCM.LoginType + "_GALLERY",
                            Description = "GALLERY OF " + authCM.LoginType
                        };
                        Image img = new Image()
                        {
                            Description = "IMAGES OF " + authCM.LoginType,
                            ImageUrl    = authCM.Avatar
                        };
                        gallery.Images = new List <Image>();
                        gallery.Images.Add(img);
                    }

                    accountCreated = new Account()
                    {
                        DisplayName    = authCM.DisplayName,
                        Email          = email,
                        Role           = Constants.Role.ADMIN,
                        Status         = Constants.AccountStatus.ACTIVE,
                        Gallery        = gallery,
                        IsBeautyArtist = true
                    };
                    await _accountService.AddAsync(accountCreated);

                    await _accountService.Save();
                }
                else
                {
                    if (!accountCreated.Status.Equals("ACTIVE"))
                    {
                        return(BadRequest());
                    }
                }



                string role = accountCreated.Role;
                if (role != authCM.LoginType)
                {
                    return(BadRequest());
                }
                var    uid         = accountCreated.Id;
                string accessToken = await _jwtTokenProvider.GenerateToken(accountCreated);

                response = new AuthVM()
                {
                    Uid         = accountCreated.Id,
                    DisplayName = accountCreated.DisplayName,
                    Email       = accountCreated.Email,
                    Phone       = accountCreated.Phone,
                    Role        = accountCreated.Role,
                    AccessToken = accessToken,
                    ExpiresIn   = Constants.EXPIRES_IN_DAY,
                    Gallery     = _mapper.Map <GalleryVM>(accountCreated.Gallery)
                };
                if (accountCreated.Role.Equals("ADMIN"))
                {
                    response.Addresses = accountCreated.Addresses;
                }
            }
            catch (Exception e)
            {
                Response.StatusCode = StatusCodes.Status500InternalServerError;
                return(new JsonResult(e.Message));
            }
            return(Ok(response));
        }