Exemplo n.º 1
0
        public AuthenticateResponse ExternalLogin(ExternalLoginRequest model, string ipAddress)
        {
            var account = _context.Accounts.SingleOrDefault(x => x.ExternalUserId == model.ExternalUserId);

            if (account == null)
            {
                ExternalRegister(model);
                account = _context.Accounts.SingleOrDefault(x => x.ExternalUserId == model.ExternalUserId);
            }

            // authentication successful so generate jwt and refresh tokens
            var jwtToken     = generateJwtToken(account);
            var refreshToken = generateRefreshToken(ipAddress);

            account.RefreshTokens.Add(refreshToken);

            // remove old refresh tokens from account
            removeOldRefreshTokens(account);

            // save changes to db
            _context.Update(account);
            _context.SaveChanges();

            var response = _mapper.Map <AuthenticateResponse>(account);

            response.JwtToken     = jwtToken;
            response.RefreshToken = refreshToken.Token;
            return(response);
        }
Exemplo n.º 2
0
        private void OAuth2AuthenticatorCompleted(object sender, AuthenticatorCompletedEventArgs e)
        {
            try
            {
                if (e.IsAuthenticated)
                {
                    ExternalLoginRequest externalLoginRequest = new ExternalLoginRequest
                    {
                        Provider = this.OAuth2AuthenticatorType.ToString(),
                    };
                    var tokenResult = JsonConvert.DeserializeObject <OAuth2TokenResult>(JsonConvert.SerializeObject(e.Account.Properties));

                    externalLoginRequest.AccessToken = tokenResult.AccessToken;

                    this.AuthenticationStore.RequestTokenWithExternalProviderAsync(externalLoginRequest);
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                this.OAuth2Authenticator.Completed -= this.OAuth2AuthenticatorCompleted;
                this.OAuth2Authenticator.Error     -= this.OAuth2AuthenticatorError;
            }
        }
        public async Task <IActionResult> ExternalLoginCallback([FromBody] ExternalLoginRequest request, CancellationToken cancellationToken = default)
        {
            var response = await Mediator.Send(request, cancellationToken);

            Response.Cookies.Append(JwtBearerDefaults.AuthenticationScheme, response.Token);

            return(Ok(response.CurrentUserInformation));
        }
Exemplo n.º 4
0
        /// <inheritdoc/>
        public async Task RequestTokenWithExternalProviderAsync(ExternalLoginRequest externalLoginRequest)
        {
            if (!this.IsAuthenticated)
            {
                this.authenticationResult = await this.authenticationServiceAgent.RequestTokenWithExternalProviderAsync(externalLoginRequest);

                await this.LoadUserTokensAsync();
            }
        }
        public async Task <IActionResult> GetInfoExternalAsync(ExternalLoginRequest request)
        {
            var result = await _userService.ExternalLoginCallback(request);

            if (string.IsNullOrEmpty(result.ResultObject))
            {
                return(BadRequest(result));
            }
            return(Ok(result));
        }
Exemplo n.º 6
0
        public async Task <ApiResult <string> > ExternalLoginCallback(ExternalLoginRequest request)
        {
            var json        = JsonConvert.SerializeObject(request);
            var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
            var response    = await _client.PostAsync($"/api/users/ExternalSignIn/", httpContent);

            var data = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                return(JsonConvert.DeserializeObject <ApiResultSuccess <string> >(data));
            }
            return(JsonConvert.DeserializeObject <ApiResultErrors <string> >(data));
        }
Exemplo n.º 7
0
        public async Task <ActionResult> ExternalLoginAsync([FromForm] ExternalLoginRequest model)
        {
            // describe real logic  here
            //var user = await _userManager.FindByEmailAsync(model.Email);
            var user = new
            {
                Id             = Guid.NewGuid(),
                LastName       = "Less",
                FirstName      = "Steve",
                EmailConfirmed = true,
            };

            if (user == null)
            {
                return(BadRequest("User not found.!"));
            }

            if (!user.EmailConfirmed)
            {
                return(BadRequest("User should confirm his email."));
            }

            // describe real logic  here
            //var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, lockoutOnFailure: true);
            var result = new
            {
                Succeeded = true,
            };

            if (result.Succeeded)
            {
                List <KeyValuePair <object, object> > keyValueList = new List <KeyValuePair <object, object> >
                {
                    new KeyValuePair <object, object>(ClaimTypes.Email, model.Email),
                    new KeyValuePair <object, object>(ClaimTypes.NameIdentifier, user.Id),
                };

                var accessToken = _tokenProvider.CreateAccessToken(keyValueList, _jwtTokenOptions.Value.LifetimeExternal);

                var redirectUrl = model.RedirectUri + "#state=" + HttpUtility.UrlEncode(model.State) +
                                  "&access_token=" +
                                  HttpUtility.UrlEncode(accessToken.AccessToken) + "&token_type=Bearer";

                return(new RedirectResult(redirectUrl));
            }

            return(BadRequest());
        }
Exemplo n.º 8
0
        public async Task <Result <AuthenticationProperties> > ExternalLogin(ExternalLoginRequest externalLoginRequest, string returnUrl)
        {
            ValidationResult validationResult = _externalLoginRequestValidator.Validate(externalLoginRequest);

            if (!validationResult.IsValid)
            {
                _logger.LogWarning($"Invalid {nameof(ExternalLoginRequest)} model");
                return(Result.Fail <AuthenticationProperties>(validationResult.Errors));
            }

            await _signInManager.SignOutAsync();

            string redirectUrl = _urlGenerator.GenerateActionUrl("ExternalLoginCallback", "Account", new { returnUrl });

            AuthenticationProperties properties = _signInManager.ConfigureExternalAuthenticationProperties(externalLoginRequest.Provider, redirectUrl);

            return(Result.Ok(properties));
        }
Exemplo n.º 9
0
        public async Task<IActionResult> ExternalLogin(ExternalLoginRequest externalLoginRequest, string returnUrl)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (!ModelState.IsValid)
            {
                LoginViewModel loginViewModel = await _accountDataService.GetLoginViewModel(returnUrl);
                return View(nameof(Login), loginViewModel);
            }

            Result<AuthenticationProperties> result = await _externalLoginService.ExternalLogin(externalLoginRequest, returnUrl);
            if(result.Failure)
            {
                LoginViewModel loginViewModel = await _accountDataService.GetLoginViewModel(returnUrl);
                return View(nameof(Login), loginViewModel);
            }

            return Challenge(result.Value, externalLoginRequest.Provider);
        }
Exemplo n.º 10
0
        public void ExternalRegister(ExternalLoginRequest model)
        {
            // map model to new account object
            var account = _mapper.Map <Account>(model);
            //account.Role = Role.User;
            var isFirstAccount = _context.Accounts.Count() == 0;

            account.Role              = isFirstAccount ? Role.Admin : Role.User;
            account.Created           = DateTime.UtcNow;
            account.LoginMethod       = LoginMethod.External;
            account.Verified          = DateTime.UtcNow;
            account.VerificationToken = null;
            account.AcceptTerms       = true;


            // save account
            _context.Accounts.Add(account);
            _context.SaveChanges();
        }
Exemplo n.º 11
0
        public async Task <Result <AuthenticationProperties> > ExternalLogin(ExternalLoginRequest externalLoginRequest, string returnUrl)
        {
            ValidationResult validationResult = _externalLoginRequestValidator.Validate(externalLoginRequest);

            if (!validationResult.IsValid)
            {
                _logger.LogWarning($"Invalid {nameof(ExternalLoginRequest)} model");
                return(Result.Fail <AuthenticationProperties>(validationResult.Errors));
            }

            await _signInManager.SignOutAsync();

            string callbackUrl = QueryHelpers.AddQueryString($"{_identityUIOptions.BasePath}/Account/ExternalLoginCallback", "returnUrl", returnUrl);
            string redirectUrl = HtmlEncoder.Default.Encode(callbackUrl);

            AuthenticationProperties properties = _signInManager.ConfigureExternalAuthenticationProperties(externalLoginRequest.Provider, redirectUrl);

            return(Result.Ok(properties));
        }
Exemplo n.º 12
0
 /// <inheritdoc/>
 public async Task <BearerAuthenticationResult> RequestTokenWithExternalProviderAsync(ExternalLoginRequest externalLoginRequest)
 {
     return(await this.PostAsync <ExternalLoginRequest, BearerAuthenticationResult>("/api/auth/external", externalLoginRequest));
 }
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl, string remoteError = null)
        {
            ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();

            returnUrl = returnUrl ?? Url.Content("~/");
            if (remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Error from external provider:{remoteError}");
                return(View("Index"));
            }
            var externalLoginRequest = new ExternalLoginRequest
            {
                FullName            = info.Principal.FindFirstValue(ClaimTypes.Name),
                Email               = info.Principal.FindFirstValue(ClaimTypes.Email),
                ProviderKey         = info.ProviderKey,
                LoginProvider       = info.LoginProvider,
                ProviderDisPlayName = info.ProviderDisplayName,
                ImagePath           = info.Principal.Claims.FirstOrDefault(c => c.Type == "picture").Value,
            };
            var result = await _userAPIClient.ExternalLoginCallback(externalLoginRequest);

            if (result.IsSuccessed == false)
            {
                TempData["message"] = result.Message;
                ModelState.AddModelError("", result.Message);
                ViewBag.ErrorServerSide = true;
                return(View());
            }
            TempData["Succes"] = "Login Succsess!";
            //HttpContext.Session.SetString("Token", result.ResultObject);
            CookieHelpers.SetObjectAsJson(Response.Cookies, "Token", result.ResultObject, 10);

            var userPrincipal = this.ValidateToken(result.ResultObject);
            var UserId        = new Guid(userPrincipal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value);
            var cartResult    = await _cartService.GetById(UserId);

            if (cartResult.IsSuccessed == true)
            {
                var CartSessionKey = _configuration.GetSection("CartSessionKey").Value;
                CookieHelpers.RemoveCookie(Response.Cookies, CartSessionKey);
                CookieHelpers.SetObjectAsJson(HttpContext.Response.Cookies, CartSessionKey, cartResult.ResultObject.CartItems, null);
            }
            var authProperties = new AuthenticationProperties
            {
                ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(10),
                IsPersistent = false // có sử dụng persistent cookie
            };

            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                userPrincipal,
                authProperties);

            if (!string.IsNullOrEmpty(returnUrl))
            {
                return(Redirect(returnUrl));
            }
            else
            {
                return(RedirectToAction("index", "home"));
            }
        }
Exemplo n.º 14
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            if (result.Succeeded != true)
            {
                return(Unauthorized(new { message = "External authentication error" }));
            }
            var externalUser = result.Principal;

            if (externalUser == null)
            {
                return(Unauthorized("External authentication error"));
            }

            var claims = externalUser.Claims.ToList();

            // try to determine the unique id of the external user - the most common claim type for that are the sub claim and the NameIdentifier
            // depending on the external provider, some other claim type might be used
            //var userIdClaim = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject);
            var userIdClaim = claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);

            if (userIdClaim == null)
            {
                return(Unauthorized(new { message = "Unknown userId" }));
            }

            var externalUserId    = userIdClaim.Value;
            var externalProvider  = userIdClaim.Issuer;
            var userEmailClaim    = claims.FirstOrDefault(x => x.Type == ClaimTypes.Email);
            var externalUserEmail = userEmailClaim?.Value;
            var userNameClaim     = claims.FirstOrDefault(x => x.Type == ClaimTypes.Name);

            if (userNameClaim == null)
            {
                userNameClaim = claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName);
            }
            var externalUserName = userNameClaim.Value;

            Claim  userPhotoUriClaim;
            string externalUserPhoto;

            if (externalProvider == "Vkontakte")
            {
                userPhotoUriClaim = claims.FirstOrDefault(x => x.Type == "urn:vkontakte:photo:link");
                externalUserPhoto = userPhotoUriClaim.Value;
            }
            else
            {
                externalUserPhoto = null;
            }


            ExternalLoginRequest request = new ExternalLoginRequest
            {
                ExternalUserId    = externalUserId,
                Email             = externalUserEmail,
                Name              = externalUserName,
                Provider          = externalProvider,
                ExternalPhotoLink = externalUserPhoto
            };
            var response = _accountService.ExternalLogin(request, ipAddress());

            setTokenCookie(response.RefreshToken, "refreshToken", DateTime.UtcNow.AddDays(7));
            setTokenCookie(response.JwtToken, "jwt", DateTime.UtcNow.AddDays(1));

            return(Redirect("https://usa-invest.ru"));
        }
Exemplo n.º 15
0
        public async Task <ApiResult <string> > ExternalLoginCallback(ExternalLoginRequest request)
        {
            var signInResult = await _signInManager.ExternalLoginSignInAsync(request.LoginProvider,
                                                                             request.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (signInResult.Succeeded)
            {
                var user = await _userManager.FindByEmailAsync(request.Email);

                var role = await _roleManager.FindByIdAsync(user.RoleID.ToString());

                var cart = await _context.Carts.FirstOrDefaultAsync(x => x.UserId == user.Id);

                var userToken = new UserToken
                {
                    CartId    = cart.Id.ToString(),
                    UserId    = user.Id.ToString(),
                    UserName  = user.UserName,
                    Role      = string.Join(";", role.Name),
                    ImagePath = user.ImagePath,
                    Email     = user.Email,
                };
                var token = CreateToken(userToken);
                return(new ApiResultSuccess <string>(token));
            }
            else
            {
                var email = request.Email;
                if (email != null)
                {
                    var user = await _userManager.FindByEmailAsync(email);

                    var roleDefault = await _roleManager.FindByNameAsync("client");

                    if (user == null)
                    {
                        user = new UserApp
                        {
                            FullName  = request.FullName,
                            ImagePath = request.ImagePath,
                            Email     = request.Email,
                            RoleID    = roleDefault.Id,
                            UserName  = request.Email,
                        };
                        var result = await _userManager.CreateAsync(user);

                        if (result.Succeeded)
                        {
                            var cartadd = new Cart
                            {
                                Created_At   = DateTime.Now,
                                UserId       = user.Id,
                                Price        = 0,
                                CartProducts = new List <CartProduct>(),
                            };
                            _context.Carts.Add(cartadd);
                            await _context.SaveChangesAsync();
                        }
                    }
                    var cart = await _context.Carts.FirstOrDefaultAsync(x => x.UserId == user.Id);

                    var info = new UserLoginInfo(request.LoginProvider, request.ProviderKey, request.ProviderDisPlayName);
                    await _userManager.AddLoginAsync(user, info);

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    var role      = _roleManager.FindByIdAsync(user.RoleID.ToString());
                    var userToken = new UserToken
                    {
                        CartId    = cart.Id.ToString(),
                        UserId    = user.Id.ToString(),
                        UserName  = user.UserName,
                        Role      = string.Join(";", role.Result.Name),
                        ImagePath = user.ImagePath,
                        Email     = user.Email,
                    };
                    var token = CreateToken(userToken);
                    return(new ApiResultSuccess <string>(token));
                }
                return(new ApiResultErrors <string>($"Email claim not received from:{request.LoginProvider}"));
            }
        }