示例#1
0
        public async Task <ActionResult <UserDto> > ExternalLogin([FromBody] ExternalAuthDto externalAuth)
        {
            var payload = await _googleAuth.VerifyGoogleToken(externalAuth);

            if (payload == null)
            {
                return(BadRequest("Invalid External Authentication."));
            }

            var info = new UserLoginInfo(externalAuth.Provider, payload.Subject, externalAuth.Provider);

            var user = await _userManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey);

            if (user == null)
            {
                user = await _userManager.FindByEmailAsync(payload.Email);

                if (user == null)
                {
                    user = new AppUser {
                        Email = payload.Email, UserName = payload.Email, DisplayName = payload.Email
                    };
                    await _userManager.CreateAsync(user);

                    //prepare and send an email for the email confirmation

                    await _userManager.AddLoginAsync(user, info);
                }
                else
                {
                    await _userManager.AddLoginAsync(user, info);
                }
            }

            if (user == null)
            {
                return(BadRequest("Invalid External Authentication."));
            }

            //check for the Locked out account

            var token = _tokenService.CreateToken(user);

            return(new UserDto
            {
                Email = user.Email,
                Token = token,
                DisplayName = user.Email
            });

            //return Ok(new AuthResponseDto { Token = token, IsAuthSuccessful = true });
        }
示例#2
0
        public async Task<GoogleJsonWebSignature.Payload> VerifyGoogleToken(ExternalAuthDto externalAuth)
		{
			try
			{
				var settings = new GoogleJsonWebSignature.ValidationSettings()
				{
					Audience = new List<string>() { _goolgeSettings.GetSection("clientId").Value }
				};

				var payload = await GoogleJsonWebSignature.ValidateAsync(externalAuth.IdToken, settings);
				return payload;
			}
			catch (Exception ex)
			{
				//log an exception
				return null;
			}
		}
示例#3
0
        public async Task <IActionResult> ExternalLogin([FromBody] ExternalAuthDto externalAuth)
        {
            var info = new UserLoginInfo(externalAuth.Provider, externalAuth.IdToken, externalAuth.Provider);

            var userApp = await _userManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey);

            if (userApp == null)
            {
                userApp = await _userManager.FindByEmailAsync(externalAuth.Email);

                //Nếu đã có tài khoản mà chưa có thông tin bảng Asp.netLogins thì thêm mới vào
                if (userApp != null)
                {
                    await _userManager.AddLoginAsync(userApp, info);
                }
                else
                {
                    var newUserApp = new ApplicationUser {
                        Email = externalAuth.Email, UserName = externalAuth.Email
                    };
                    await _userManager.CreateAsync(newUserApp);

                    var roleExist = await _roleManager.RoleExistsAsync("User");

                    if (!roleExist)
                    {
                        await _roleManager.CreateAsync(new IdentityRole("User"));
                    }

                    await _userManager.AddToRoleAsync(newUserApp, "User");

                    await _userManager.AddLoginAsync(newUserApp, info);

                    await _userManager.SetLockoutEnabledAsync(newUserApp, false);

                    var refreshToken = _tokenService.GenerateRefreshToken();
                    var newUser      = new User()
                    {
                        Quyen                  = externalAuth.Quyen,
                        UserName               = externalAuth.UserName,
                        ApplicationUserID      = newUserApp.Id,
                        RefreshToken           = refreshToken,
                        RefreshTokenExpiryTime = DateTime.Now.AddMinutes(Convert.ToDouble(_config[$"{NamePars.JwtSettings}:{NamePars.ExpireTime}"]))
                    };

                    var userCreated = _repository.User.CreateUser(newUser);
                    if (userCreated != null)
                    {
                        _repository.Save();
                    }
                    else
                    {
                        _logger.LogError($"Lỗi khi đăng ký user với email {externalAuth.Email}");
                    }

                    newUserApp = await _userManager.FindByEmailAsync(externalAuth.Email);

                    var claims = await _jwtHandler.GenerateClaims(newUserApp, userCreated);

                    var accessToken = _tokenService.GenerateAccessToken(claims, _config);

                    return(Ok(new
                    {
                        Token = accessToken,
                        RefreshToken = refreshToken
                    }));
                }
            }

            //check for the Locked out account
            await _userManager.SetLockoutEnabledAsync(userApp, false);

            //login
            userApp = await _userManager.FindByEmailAsync(externalAuth.Email);

            var user = await _repository.User.GetUserByApplicationUserIDAsync(userApp.Id);

            var             refreshTokenForLogin = _tokenService.GenerateRefreshToken();
            ResponseDetails response             = _repository.User.UpdateUserRefreshToken(
                user,
                refreshTokenForLogin,
                DateTime.Now.AddMinutes(Convert.ToDouble(_config[$"{NamePars.JwtSettings}:{NamePars.ExpireTime}"]))
                );

            if (response.StatusCode == ResponseCode.Success)
            {
                _repository.Save();
            }
            else
            {
                _logger.LogError($"Lỗi khi cấp refresh token khi xác thực đăng nhập cho user với id {user.UserID}");
            }
            var claimsForLogin = await _jwtHandler.GenerateClaims(userApp, user);

            var accessTokenForLogin = _tokenService.GenerateAccessToken(claimsForLogin, _config);

            return(Ok(new
            {
                Token = accessTokenForLogin,
                RefreshToken = refreshTokenForLogin
            }));
        }