Exemplo n.º 1
0
        public IEnumerable <ExternalLoginModel> GetExternalLogins(string returnUrl, bool generateState = false)
        {
            var providers = Authentication.GetExternalAuthenticationTypes();
            var logins    = new List <ExternalLoginModel>();

            string state = null;

            foreach (var description in providers)
            {
                var login = new ExternalLoginModel
                {
                    Name = description.Caption,
                    Url  = Url.Link("ExternalLogin", new
                    {
                        provider      = description.AuthenticationType,
                        response_type = "token",
                        client_id     = PublicClientId,
                        redirect_uri  = new Uri(Request.RequestUri, returnUrl).AbsoluteUri,
                        state
                    }),
                    State = state
                };

                logins.Add(login);
            }

            return(logins);
        }
        public async Task <IActionResult> ExternalLoginFormAction(ExternalLoginModel model)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                ExternalLoginInfo info = await _authentication.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    throw new ApplicationException("Error loading external login information during confirmation.");
                }
                //var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                //var result = await _userManager.CreateAsync(user);
                RegistrationResult result = await _registration.RegisterAsync(model.Login, model.Email);

                if (result == RegistrationResult.Success)
                {
                    IdentityResult identResult = await _moneyUserManager.AddLoginAsync(model.Login, info);

                    if (identResult.Succeeded)
                    {
                        //await _signInManager.SignInAsync(user, isPersistent: false);
                        await _authentication.SignInAsync(model.Login, false);

                        await _logManager.WriteAsync(model.Login, $"New user '{model.Login}' was registered with {info.ProviderDisplayName}.");

                        //_logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        //return RedirectToLocal(returnUrl);
                        return(RedirectToAction(nameof(HomeController.Index), "Home"));
                    }
                }
                //AddErrors(result);
            }
            return(View(nameof(ExternalLogin), model));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                var info = await _signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(BadRequest("Error loading external login information during confirmation."));
                }
                var user = new IdentityUser {
                    UserName = model.Username, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user);

                result = await _userManager.AddLoginAsync(user, info);

                if (result.Succeeded)
                {
                    await SendEmailConfirmation(user, returnUrl);

                    return(View(nameof(ConfirmEmail)));
                }
                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(nameof(ExternalLogin), model));
        }
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginModel elm)
        {
            if (ModelState.IsValid)
            {
                var info = await _signInManager.GetExternalLoginInfoAsync();



                if (info == null)
                {
                    return(RedirectToAction(nameof(Login)));
                }

                var user = new ApplicationUser {
                    UserName = elm.Email, Email = elm.Email
                };

                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }

            return(View(nameof(ExternalLogin), elm));
        }
        public static void SingIn(IOwinContext owinContext, ExternalLoginModel externalLogin)
        {
            var claimsMapper = new NotRegisteredExternal(externalLogin);
            var identity     = CreateIdentity(claimsMapper, OAuthDefaults.AuthenticationType);

            owinContext.Authentication.SignIn(identity);
        }
Exemplo n.º 6
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var ctx    = Request.GetOwinContext();
            var result = await ctx.Authentication.AuthenticateAsync("ExternalCookie");

            ctx.Authentication.SignOut("ExternalCookie");



            var externalLogin = ExternalLoginModel.FromIdentity(result.Identity);

            if (externalLogin == null)
            {
                return(new HttpStatusCodeResult(500));
            }

            var claims = result.Identity.Claims.ToList();

            claims.Add(new Claim(ClaimTypes.AuthenticationMethod, "Google"));

            var ci = new ClaimsIdentity(claims, "Cookie");

            ctx.Authentication.SignIn(ci);

            Session["ExternalLoginModel"] = externalLogin;

            if (!String.IsNullOrEmpty(returnUrl))
            {
                return(new RedirectResult(returnUrl));
            }

            return(RedirectToAction("Index", "Dashboard", new { area = "Account" }));
        }
Exemplo n.º 7
0
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    throw new ApplicationException("Error loading external login information during confirmation.");
                }
                var user = new User {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(nameof(ExternalLogin), model));
        }
        public async Task <IActionResult> ConfirmationAsync(ExternalLoginModel model, string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                model.ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToAction("Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new User {
                    UserName = model.Input.Email, Email = model.Input.Email
                };

                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Action("ConfirmEmail", values: new { userId = userId, code = code });

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

                        // If account confirmation is required, we need to show the link if we don't have a real email sender
                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return(RedirectToAction("RegisterConfirmation", new { Email = model.Input.Email }));
                        }

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

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            model.ProviderDisplayName = info.ProviderDisplayName;
            model.ReturnUrl           = returnUrl;
            return(View(model));
        }
Exemplo n.º 9
0
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginModel model, string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(StatusCode(500));
            }

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

            IdentityResult result;

            if (user != null)
            {
                result = await _userManager.AddLoginAsync(user, info);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(RedirectToAction("Index", "Home"));
                }
            }
            else
            {
                var newUser = new User
                {
                    UserName = model.Email,
                    Email    = model.Email
                };
                result = await _userManager.CreateAsync(newUser);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(newUser, info);

                    if (result.Succeeded)
                    {
                        //TODO: Send an emal for the email confirmation and add a default role as in the Register action
                        await _signInManager.SignInAsync(newUser, isPersistent : false);

                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }

            foreach (var error in result.Errors)
            {
                ModelState.TryAddModelError(error.Code, error.Description);
            }

            return(View(nameof(ExternalLoginConfirmation), model));
        }
Exemplo n.º 10
0
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginModel model, string returnUrl = null)
        {
            if (await Configurations.GetBooleanAsync("enable_register") == false)
            {
                return(ExternalRegisterClosed());
            }

            var check = new RegisterNotification(model.Username);
            await Mediator.Publish(check);

            if (check.Failed)
            {
                ModelState.AddModelError("xys::custom_rule", "The username is invalid. Please change another one.");
            }

            if (!ModelState.IsValid)
            {
                ViewData["ReturnUrl"] = returnUrl;
                return(View(nameof(ExternalLogin), model));
            }

            // Get the information about the user from the external login provider
            var info = await SignInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(Message(
                           title: "External login",
                           message: "Error loading external login information during confirmation.",
                           type: BootstrapColor.danger));
            }

            var user = UserManager.CreateEmpty(model.Username);

            user.Email        = model.Email;
            user.RegisterTime = DateTimeOffset.Now;
            var result = await UserManager.CreateAsync(user);

            if (result.Succeeded)
            {
                result = await UserManager.AddLoginAsync(user, info);
            }

            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent : false);

                await HttpContext.AuditAsync(
                    "registered",
                    user.Id.ToString(),
                    $"at {HttpContext.Connection.RemoteIpAddress} via {info.LoginProvider}");

                return(RedirectToLocal(returnUrl));
            }
            else
            {
                return(ErrorView(result, model, nameof(ExternalLogin)));
            }
        }
Exemplo n.º 11
0
        //[ValidateAntiForgeryToken]
        public IActionResult ExternalLogin([FromBody] ExternalLoginModel model)
        {
            // Request a redirect to the external login provider.
            var redirectUrl = Url.Action(nameof(RegisterFBUser), "Account", new { model.ReturnUrl });
            var properties  = _signInManager.ConfigureExternalAuthenticationProperties(model.Provider, redirectUrl);

            return(Challenge(properties, model.Provider));
        }
Exemplo n.º 12
0
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginModel model, string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(View(nameof(Error)));
            }

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

            IdentityResult result;

            if (user != null)
            {
                result = await _userManager.AddLoginAsync(user, info);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(RedirectToLocal(returnUrl));
                }
            }
            else
            {
                model.Principal = info.Principal;
                user            = _mapper.Map <User>(model);
                result          = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        //TODO: Send an emal for the email confirmation and add a default role as in the Register action
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(RedirectToLocal(returnUrl));
                    }
                }
            }

            foreach (var error in result.Errors)
            {
                ModelState.TryAddModelError(error.Code, error.Description);
            }

            return(View(nameof(ExternalLogin), model));
        }
Exemplo n.º 13
0
        public void ExternalLoginModelIsString()
        {
            ExternalLoginModel external = new ExternalLoginModel
            {
                Email = "*****@*****.**"
            };
            var test = external.Email;

            Assert.IsType <string>(test);
        }
        public static void SingIn(IOwinContext owinContext, User user, ExternalLoginModel externalLogin)
        {
            owinContext.Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var claimsMapper   = new RegisteredExternal(user, externalLogin);
            var oAuthIdentity  = CreateIdentity(claimsMapper, OAuthDefaults.AuthenticationType);
            var cookieIdentity = CreateIdentity(claimsMapper, CookieAuthenticationDefaults.AuthenticationType);
            var properties     = CreateProperties(user);

            owinContext.Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
        }
Exemplo n.º 15
0
        public void ExternalLoginModel()
        {
            ExternalLoginModel external = new ExternalLoginModel
            {
                Email = "*****@*****.**"
            };
            var test = external.Email;

            Assert.Equal(test, "*****@*****.**");
        }
Exemplo n.º 16
0
        private static Task <byte[]> GetExternalAvatarAsync(ExternalLoginModel externalInfo)
        {
            if (string.IsNullOrEmpty(externalInfo.AvatarUrl))
            {
                return(null);
            }

            var client = HttpHelper.CreateHttpClient();

            return(client.GetByteArrayAsync(externalInfo.AvatarUrl));
        }
Exemplo n.º 17
0
 public static UserViewModel MapUserToViewModel(User user, ExternalLoginModel externalLogin)
 {
     return(new UserViewModel
     {
         Email = user.Email,
         FullName = user.FullName,
         IsVerified = user.IsVerified,
         AvatarUrl = GetAvatarUrl(user),
         IsRegistered = true,
         LoginProvider = externalLogin.Provider.ToString()
     });
 }
 public RegisteredExternal(User user, ExternalLoginModel extLogin)
 {
     this.Id             = user.Id.ToString();
     this.Email          = user.Email;
     this.FullName       = user.FullName ?? string.Empty;
     this.AvatarUrl      = UserProvider.GetAvatarUrl(user);
     this.Sid            = extLogin.ProviderKey;
     this.Version        = this.GetVersion(user.TimeStamp);
     this.IsVerified     = user.IsVerified.ToString();
     this.Issuer         = ClaimsIdentity.DefaultIssuer;
     this.OriginalIssuer = extLogin.Provider.ToString();
 }
        public void Validate_ValidModel()
        {
            var model = new ExternalLoginModel
            {
                Email = "*****@*****.**"
            };

            var result = target.Validate(model);

            Assert.IsTrue(result.IsValid);
            target.ShouldNotHaveValidationErrorFor(x => x.Email, model);
        }
 public NotRegisteredExternal(ExternalLoginModel extLogin)
 {
     this.Id             = string.Empty;
     this.Email          = extLogin.Email ?? string.Empty;
     this.FullName       = extLogin.FullName ?? string.Empty;
     this.AvatarUrl      = extLogin.AvatarUrl ?? string.Empty;
     this.Sid            = extLogin.ProviderKey;
     this.Version        = string.Empty;
     this.IsVerified     = false.ToString();
     this.Issuer         = extLogin.Provider.ToString();
     this.OriginalIssuer = this.Issuer;
 }
Exemplo n.º 21
0
        public async Task <IActionResult> ExternalLogin(string remoteError = null)
        {
            if (remoteError != null)
            {
                return(RedirectToAction("Error", "Home"));
            }

            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(RedirectToAction("Error", "Home"));
            }
            var returnUrl = info.AuthenticationProperties.Items["returnUrl"] ?? Url.Content("~/AccountManage");

            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                return(Redirect(returnUrl));
            }
            if (result.IsLockedOut)
            {
                return(RedirectToAction("Error", "Home"));
            }
            else
            {
                var externalLoginModel = new ExternalLoginModel();
                externalLoginModel.LoginProvider = info.LoginProvider;
                externalLoginModel.Claims        = info.Principal.Claims;
                if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
                {
                    var email = info.Principal.FindFirstValue(ClaimTypes.Email);
                    externalLoginModel.Email = email;

                    var exsistApplicationUser = await _userManager.FindByNameAsync(email);

                    if (exsistApplicationUser != null)
                    {
                        var addProviderResult = await _userManager.AddLoginAsync(exsistApplicationUser, info);

                        if (addProviderResult.Succeeded)
                        {
                            await _signInManager.SignInAsync(exsistApplicationUser, isPersistent : false);

                            return(Redirect(returnUrl));
                        }
                    }
                }
                return(View(externalLoginModel));
            }
        }
Exemplo n.º 22
0
        public IHttpActionResult PutExternalLogin(int id, ExternalLoginModel externalLogin)
        {
            // Allow only for authorized user
            var userToCheck = _userRepository.FirstOrDefault(u => u.UserName == User.Identity.Name);

            if (!userToCheck.Authorized)
            {
                return(Unauthorized());
            }

            // Validate the request
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != externalLogin.ExternalLoginID)
            {
                return(BadRequest());
            }

            // Get the DB externalLogin, update it according to the input ExternalLoginModel object,
            //   and then update the DB externalLogin in the database
            var dbExternalLogin = _externalLoginRepository.GetByID(id);

            if (dbExternalLogin == null)
            {
                return(NotFound());
            }
            dbExternalLogin.Update(externalLogin);
            _externalLoginRepository.Update(dbExternalLogin);

            // Save database changes
            try
            {
                _unitOfWork.Commit();
            }
            catch (DBConcurrencyException e)
            {
                if (!ExternalLoginExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw new Exception("Unable to update the externalLogin in the database", e);
                }
            }
            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemplo n.º 23
0
        public async Task <IHttpActionResult> ExternalLoginCallback(string provider)
        {
            _logger.Debug(string.Format("ini ExternalLoginCallback process - provider:{0}", provider));

            string redirectUri = string.Empty;

            if (!User.Identity.IsAuthenticated)
            {
                _logger.Debug("ExternalLoginCallback IsAuthenticated");
                return(new ChallengeResult(provider, this));
            }

            var redirectUriValidationResult = Helpers.ValidateClientAndRedirectUri(ref redirectUri, Request);

            if (!string.IsNullOrWhiteSpace(redirectUriValidationResult))
            {
                _logger.Debug("ExternalLoginCallback BadRequest");
                return(BadRequest(redirectUriValidationResult));
            }

            ExternalLoginModel externalLogin = ExternalLoginModel.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                _logger.Debug("ExternalLoginCallback InternalServerError");
                return(InternalServerError());
            }

            if (externalLogin.LoginProvider != provider)
            {
                _logger.Debug("ExternalLoginCallback SignOut different providers");
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }

            User user = await _appUserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered && user.Disabled)
            {
                return(BadRequest("Your account is disabled, please contact with the web master"));
            }

            redirectUri = string.Format("{0}?externalAccessToken={1}&provider={2}&haslocalaccount={3}&userName={4}&email={5}",
                                        redirectUri, externalLogin.ExternalAccessToken, externalLogin.LoginProvider,
                                        hasRegistered, externalLogin.UserName, externalLogin.Email);
            _logger.Debug(string.Format("ExternalLoginCallback Redirect info provider:{0},hasRegistered:{1},externalLogin.UserName:{2},externalLogin.Email{3}", provider, hasRegistered, externalLogin.UserName, externalLogin.Email));
            return(Redirect(redirectUri));
        }
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            ExternalLoginProvider loginProvider;

            if (!Enum.TryParse <ExternalLoginProvider>(provider, ignoreCase: true, result: out loginProvider) ||
                loginProvider == ExternalLoginProvider.None)
            {
                //Unsupported login provider
                return(InternalServerError());
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(loginProvider, this));
            }

            ExternalLoginModel externalLogin = ExternalLoginModel.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return(InternalServerError());
            }

            if (externalLogin.Provider != loginProvider)
            {
                Request.GetOwinContext().Authentication.SignOut(
                    DefaultAuthenticationTypes.ExternalCookie,
                    OAuthDefaults.AuthenticationType,
                    CookieAuthenticationDefaults.AuthenticationType);
                return(new ChallengeResult(loginProvider, this));
            }

            User user = await this.UserProvider.FindAsync(externalLogin.Provider, externalLogin.ProviderKey);

            if (user != null)
            {
                OwinHelper.SingIn(Request.GetOwinContext(), user, externalLogin);
            }
            else
            {
                OwinHelper.SingIn(Request.GetOwinContext(), externalLogin);
            }

            return(Ok());
        }
Exemplo n.º 25
0
        public IActionResult ExternalLogin([FromQuery] ExternalLoginModel model)
        {
            var authenticationProperties = new AuthenticationProperties()
            {
                RedirectUri = Url.Action(nameof(ExternalLoginCallback)),
                Items       =
                {
                    { "returnUrl", model.ReturnUrl },
                    { "scheme",    model.Provider  },
                }
            };

            return(Challenge(authenticationProperties, model.Provider));
        }
Exemplo n.º 26
0
        public async Task <string> GmailLogin(ExternalLoginModel model)
        {
            var accessTokenValidationResponse = await this.client.GetAsync(string.Format(GmailLoginVerifier, model.Token));

            try
            {
                accessTokenValidationResponse.EnsureSuccessStatusCode();
            }
            catch (Exception e)
            {
                throw new Exception("Invalid Google+ Token.");
            }

            var content = JsonConvert.DeserializeObject <GoogleApiTokenInfo>(await accessTokenValidationResponse.Content.ReadAsStringAsync());

            var user = await this.UserManager.FindByEmailAsync(content.email);

            if (user is null)
            {
                var appUser = new User
                {
                    Email          = content.email,
                    UserName       = content.email,
                    DateRegistered = DateTime.UtcNow
                };

                await this.UserManager.CreateAsync(appUser);

                await this.UserManager.AddToRoleAsync(appUser, Enum.GetName(typeof(Roles), 2));
            }
            else
            {
                if (user.UserName != content.email)
                {
                    throw new Exception("Email is already taken.");
                }
            }

            user = await this.UserManager.FindByEmailAsync(content.email);

            if (user.IsActive == false)
            {
                throw new UnauthorizedAccessException(UserBannedErrorMessage);
            }

            await this.LoginInfo(user.Id);

            return(this.GenerateToken(user));
        }
Exemplo n.º 27
0
        /// <summary>
        /// 第三方登录授权获取token
        /// </summary>
        /// <param name="loginModel"></param>
        /// <returns></returns>
        public async Task <AjaxResponse> ExternalAuthenticate(ExternalLoginModel loginModel)
        {
            if (!ModelState.IsValid)
            {
                throw new UserFriendlyException("Invalid request!");
            }

            //后续需要校验第三方服务

            var loginResult = await _logInManager.LoginAsync(new UserLoginInfo(loginModel.LoginProvider, loginModel.ProviderKey));

            string token = GetToken(loginResult);

            return(new AjaxResponse(token));
        }
Exemplo n.º 28
0
        public async Task <User> CreateExternalAsync(ExternalLoginModel externalInfo)
        {
            var userRegistration = new UserRegistration()
            {
                Email             = externalInfo.Email,
                FullName          = externalInfo.FullName,
                Avatar            = await GetExternalAvatarAsync(externalInfo),
                ExternalLoginInfo = new ExternalLoginInfo
                {
                    ProviderType = externalInfo.Provider,
                    ProviderKey  = externalInfo.ProviderKey
                }
            };

            return(await this.UsersManager.CreateUserAsync(userRegistration));
        }
Exemplo n.º 29
0
        public async Task <IActionResult> FacebookLogin(ExternalLoginModel externalLoginModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var result = await _authService.FacebookLogin(externalLoginModel.AccessToken, externalLoginModel.Id);

            if (result.Error != null)
            {
                return(Unauthorized(result));
            }

            return(Ok(result));
        }
Exemplo n.º 30
0
        public async Task <IActionResult> ExternalLoginConfrmation(ExternalLoginModel model, string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(View(nameof(Error)));
            }

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

            IdentityResult result;

            if (user != null)
            {
                result = await _userManager.AddLoginAsync(user, info);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent : true);

                    return(SignInAndRedirectToAction(returnUrl));
                }
            }
            else
            {
                result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent : true);

                    return(SignInAndRedirectToAction(returnUrl));
                }
            }

            foreach (var error in result.Errors)
            {
                ModelState.TryAddModelError(error.Code, error.Description);
            }
            return(View(nameof(ExternalAuth), model));
        }