public async Task <AuthResult <int> > AttemptLoginWithFacebookAsync(FacebookLoginDto dto) { var user = await _userManager.FindByEmailAsync(dto.Email); if (user == null) { user = new ImageHubUser() { UserName = dto.Email, Email = dto.Email }; var result = await _userManager.CreateAsync(user); if (!result.Succeeded) { return(new AuthResult <int>() { Successful = false, Errors = result.Errors.Select(err => err.Description) }); } await _signInManager.SignInAsync(user, isPersistent : true); } // we add the id of the user role only so that no meaningful info is sent out to the client return(new AuthResult <int>() { Successful = true, UserId = user.Id }); }
public async Task <IActionResult> ExternalLoginFacebook([FromBody] FacebookLoginDto loginInfo) { var userIp = Request.HttpContext.Connection.RemoteIpAddress; var externalData = await _externalLoginService.GetExternalFacebookLoginData(loginInfo.AccessToken); return(await HandleExternalInfo(userIp, externalData, ExternalLoginProvider.Facebook)); }
public async Task <Result <TokenDto> > LoginFacebook(FacebookLoginDto facebookLoginDto) { var loginProvider = _loginDataProviderFactory.Create(LoginProvider.Facebook); var userData = await loginProvider.GetExternalData(new FacebookExternalDataDto { AccessToken = facebookLoginDto.AccessToken }); return(await Login(userData, LoginProvider.Facebook)); }
public async Task <IActionResult> LoginCallback(FacebookLoginDto dto) { var tokenExchangeResponse = await "https://graph.facebook.com/oauth/access_token" .SetQueryParams(new { client_id = _configuration[Constants.FB_ID], client_secret = _configuration[Constants.FB_SECRET], grant_type = "client_credentials" }) .GetJsonAsync <FbAccessToken>(); var response = await "https://graph.facebook.com/debug_token" .SetQueryParams(new { input_token = dto.AccessToken, access_token = tokenExchangeResponse.Access_Token }) .GetJsonAsync(); var fbData = new FBData() { App_id = response.data.app_id, Is_valid = response.data.is_valid, User_id = response.data.user_id }; if (_authService.ValidateFbData(fbData, dto)) { return(Ok(await _authService.AttemptLoginWithFacebookAsync(dto))); } return(Unauthorized()); }
public async Task <IActionResult> LoginWithFacebook(FacebookLoginDto facebookLogin) { await _authValidatorService.ValidateForLoginWithFacebook(facebookLogin); var token = await _authService.LoginWithFacebook(facebookLogin); return(Ok(token)); }
public async Task <IActionResult> FacebookLogin(FacebookLoginDto request) { ServiceResponse <string> response = await facebookAuth.LoginWithFacebook(request.AccessToken); if (!response.Success) { return(BadRequest(response)); } return(Ok(response)); }
public async Task <IActionResult> Facebook([FromBody] FacebookLoginDto model) { var response = await externalAuthService.FacebookLogin(facebookAuthSettings.AppId, facebookAuthSettings.AppSecret, model.AccessToken); if (response != null) { return(Ok(response)); } return(BadRequest()); }
public async Task <IActionResult> Facebook([FromBody] FacebookLoginDto model) { HttpClient client = this._clientFactory.CreateClient("Facebook"); var fbAppId = this._facebookOptions.FbAppId; var fbAppSecret = this._facebookOptions.FbSecret; // 1.generate an app access token var appAccessTokenResponse = await client.GetStringAsync($"https://graph.facebook.com/oauth/access_token?client_id={fbAppId}&client_secret={fbAppSecret}&grant_type=client_credentials"); var appAccessToken = JsonConvert.DeserializeObject <FacebookAppAccessToken>(appAccessTokenResponse); // 2. validate the user access token var userAccessTokenValidationResponse = await client.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={model.Token}&access_token={appAccessToken.AccessToken}"); var userAccessTokenValidation = JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse); if (!userAccessTokenValidation.Data.IsValid) { return(BadRequest("Invalid facebook auth token")); } // 3. we've got a valid token so we can request user data from fb var userInfoResponse = await client.GetStringAsync($"https://graph.facebook.com/v2.8/me?fields=id,email,first_name,last_name,name,picture&access_token={model.Token}"); var userInfo = JsonConvert.DeserializeObject <FacebookUserData>(userInfoResponse); // 4. ready to create the local user account (if necessary) and jwt var user = await _userManager.FindByEmailAsync(userInfo.Email); if (user == null) { var appUser = new User { Email = userInfo.Email, UserName = userInfo.Email }; var result = await _userManager.CreateAsync(appUser, _tokenGenerator.GetOAuthPassword()); if (!result.Succeeded) { return(new BadRequestObjectResult(result)); } return(Ok(await this.GetSuccessfulLoginResponse(appUser, true))); } else { var appUser = _userManager.Users.Include(u => u.DeviceTokens).Include(i => i.RefreshTokens).SingleOrDefault(r => r.Email == userInfo.Email); if (appUser == null) { return(BadRequest("Could not log in")); } return(Ok(await this.GetSuccessfulLoginResponse(appUser, false))); } }
public async Task ValidateForLoginWithFacebook(FacebookLoginDto facebookLogin) { Validate(facebookLogin); var isTokenValid = await _facebookService.ValidateAccessTokenAsync(facebookLogin.AccessToken); if (isTokenValid == false) { AddValidationError("Token", "Invalid token!"); } ThrowValidationErrorsIfNotEmpty(); }
public async Task <TokenDto> LoginWithFacebook(FacebookLoginDto facebookLogin) { var userInfo = await _facebookService.GetUserInfoAsync(facebookLogin.AccessToken); var user = await _uow.Repository <Domain.Entities.User>().FindOneAsync(new UserWithRolesSpecification(username: userInfo.Email)); if (user == null) { var userToRegister = _mapper.Map <UserForRegistrationDto>(userInfo); await Register(userToRegister); user = await _uow.Repository <Domain.Entities.User>().FindOneAsync(new UserWithRolesSpecification(username: userInfo.Email)); } return(await _jwtService.GenerateJwtToken(user)); }
public async Task <IActionResult> FacebookAuth([FromBody] FacebookLoginDto facebookLoginDto) { var payLoad = await _userRepository.GetFacebookUser(facebookLoginDto.UserId, facebookLoginDto.Token); //var info = await _signInManager.GetExternalLoginInfoAsync(); if (payLoad == null) { return(Unauthorized( "Sorry, we cannot validate your info, from facebook, please try another login provider")); } // find user by email if he exists var user = await _userManager.FindByEmailAsync(payLoad.email); if (user != null) { user.EmailConfirmed = true; if (string.IsNullOrEmpty(user.ProfileImageUrl)) { user.ProfileImageUrl = payLoad.picture.data.url; } await _userRepository.Update(user); await _userRepository.Save(); var identity = await _jwtFactory.GenerateClaimsIdentity(user.UserName, user.Id); var token = await _jwtFactory.GenerateEncodedToken(user.UserName, identity); var mappedUser = _mapper.Map <UserDto>(user); var roles = await _userManager.GetRolesAsync(user); var response = new { id = identity.Claims.Single(c => c.Type == "id").Value, auth_token = token, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds, roles = roles, user = mappedUser, canLogin = true }; return(Ok(new ResponseDto { Data = response, Status = ResponseStatus.Success })); } else { // no user found create a new one and set emailConfirm to true var createdUser = await _userManager.CreateAsync(new ApplicationUser() { Email = payLoad.email, FirstName = payLoad.first_name, LastName = payLoad.last_name, UserName = payLoad.email, TwoFactorEnabled = true, EmailConfirmed = true, ProfileImageUrl = payLoad.picture.data.url }); if (createdUser.Succeeded) { // sign in the user with a token and notify the user to update his password var newUser = await _userManager.FindByEmailAsync(payLoad.email); if (newUser == null) { return(BadRequest("unable to find this user, please try again")); } var identity = await _jwtFactory.GenerateClaimsIdentity(newUser.UserName, newUser.Id); var mappedUser = _mapper.Map <UserDto>(newUser); var roles = await _userManager.GetRolesAsync(newUser); var response = new { id = identity.Claims.Single(c => c.Type == "id").Value, auth_token = await _jwtFactory.GenerateEncodedToken(newUser.UserName, identity), expires_in = (int)_jwtOptions.ValidFor.TotalSeconds, roles = roles, user = mappedUser, canLogin = true, message = "success, please redirect user to setup his password" }; return(Ok(new ResponseDto() { Data = response, Status = ResponseStatus.Success })); } } return(StatusCode(500, "something went wrong")); }
public ResultMessage RegisterFBUser(FacebookLoginDto userData) { try { var userEntity = new AspNetUsers() { Email = userData.Email, FullName = userData.Name, FacebookId = userData.Id, EmailConfirmed = true, UserName = userData.Email }; var user = _unitOfWork.UsersRepository.Get().FirstOrDefault(c => c.FacebookId == userData.Id || c.Email == userData.Email); if (user != null) { if (user.Email != userData.Email) { user.Email = userData.Email; user.UserName = userData.Email; user.FullName = userData.Name; _unitOfWork.UsersRepository.Update(user); _unitOfWork.Commit(); } else { user.FacebookId = userData.Id; user.FullName = userData.Name; CreatePasswordHash(userData.Id, out byte[] passwordHashUpdate, out byte[] passwordSaltUpdate); user.PasswordHash = passwordHashUpdate; user.PasswordSalt = passwordSaltUpdate; _unitOfWork.UsersRepository.Update(user); _unitOfWork.Commit(); } return(Authenticate(user.UserName, user.FacebookId)); } userEntity.Id = Guid.NewGuid().ToString(); userEntity.UserName = userEntity.Email; userEntity.SecurityStamp = Helper.GenerateToken(); CreatePasswordHash(userData.Id, out byte[] passwordHash, out byte[] passwordSalt); userEntity.PasswordHash = passwordHash; userEntity.PasswordSalt = passwordSalt; _unitOfWork.UsersRepository.Insert(userEntity); _unitOfWork.Commit(); AddRoleToUser(new UserRoleDto { RoleName = "RegularUser", Username = userData.Email }); var replacements = SetRegisterMailReplacements(userEntity.FullName, userEntity.Email, _settings.EmailSettings.RegisterEmail.VerifyEmailUrl, userEntity.SecurityStamp); _emailService.SendEmailAsync(userEntity.Email, _settings.EmailSettings.RegisterEmail.Subject, EmailTemplatesEnum.Register, replacements); return(Authenticate(userEntity.UserName, userEntity.FacebookId)); } catch (Exception ex) { _logger.LogError(ex, string.Empty); return(new ResultMessage { Status = HttpStatusCode.InternalServerError }); } }
public bool ValidateFbData(FBData dto, FacebookLoginDto claim) { var appId = _configuration[Constants.FB_ID]; return(dto.Is_valid && dto.App_id == appId && claim.UserId == dto.User_id); }
public async Task <IActionResult> ExternalLoginFacebook([FromBody] FacebookLoginDto externalLoginDto) { var result = await _externalLoginService.LoginFacebook(externalLoginDto); return(HandleExternalLoginResult(result)); }
public IActionResult AuthenticateFb([FromBody] FacebookLoginDto user) { return(GetStatusCodeResult(_userService.RegisterFBUser(user))); }