Esempio n. 1
0
        public async Task <ActionResult> GoogleLoginCallBack()
        {
            var code         = HttpContext.Request.Query["code"];
            var userInfo     = new UserInfo();
            var userId       = "";
            var clientID     = _config.GetSection("Authentication:Google:ClientId").Value;
            var clientSecret = _config.GetSection("Authentication:Google:ClientSecret").Value;
            var redirectUri  = new Uri(Url.Action("GoogleLoginCallBack", "Auth", null, "https"));

            var googleClient = new GoogleClient(new RequestFactory(), new OAuth2.Configuration.ClientConfiguration
            {
                ClientId     = clientID?.Trim(),
                ClientSecret = clientSecret?.Trim(),
                RedirectUri  = redirectUri.ToString(),
                Scope        = "profile email"
            });

            try
            {
                userInfo = await googleClient.GetUserInfoAsync(new NameValueCollection()
                {
                    { "code", code }
                });
            }
            catch (Exception ex)
            {
                return(RedirectToAction("LoginError", new { error = ex.Message }));
            }

            if (userInfo.Id != null)
            {
                var newUser = _mapper.Map <ApplicationUser>(userInfo);
                var user    = await _userService.GetOrCreateUserAsync(newUser);

                userId = user.Id.ToString();
            }

            HttpContext.Response.Cookies.Append(
                AUTHORIZATION_TOKEN,
                googleClient.AccessToken,
                new CookieOptions {
                HttpOnly = false
            });

            HttpContext.Response.Cookies.Append(
                USER_ID,
                userId,
                new CookieOptions {
                HttpOnly = false
            });

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