コード例 #1
0
        public async Task <IActionResult> VerifyToken([FromBody] GoogleAuthResponse res)
        {
            /*Payload payload;
             * try
             * {
             *  payload = await ValidateAsync(res.TokenId, new ValidationSettings
             *  {
             *      Audience = new[] { "1029632734628-0hskb0pputp0bal8p8v7dif1iigfk3uo.apps.googleusercontent.com" }
             *  });
             *  return Ok();
             * }
             * catch(Exception e)
             * {
             *  return BadRequest( e );
             * }*/
            if (res != null)
            {
                InnerToken result = await _Service.CheckLoginGoogle(res);

                if (result.isValid)
                {
                    return(Ok(new { token = result.Token }));
                }
                else
                {
                    return(BadRequest(new { Errors = result.Error }));
                }
            }
            return(BadRequest(new { Error = "Check the format" }));
        }
コード例 #2
0
        public async Task <AuthentificationResult> CheckAuthentificationAsync(UserInfo userInfo = null)
        {
            if (userInfo == null)
            {
                this.logger.Debug("CheckAuthentificationAsync: trying to restore previos session.");
                var userSession = this.sessionService.GetSession();
                if (userSession != null)
                {
                    this.logger.Debug("CheckAuthentificationAsync: GetSession is not null.");

                    var cookieCollection = await this.sessionService.GetSavedCookiesAsync();

                    if (cookieCollection != null)
                    {
                        this.logger.Debug("CheckAuthentificationAsync: cookie collection is not null. Initializing web services.");
                        this.googleMusicWebService.Initialize(cookieCollection.Cast <Cookie>());
                        userSession.IsAuthenticated = true;
                        return(AuthentificationResult.SucceedResult());
                    }
                }
            }

            if (userInfo == null)
            {
                this.logger.Debug("CheckAuthentificationAsync: Trying to get user info with pasword.");
                userInfo = this.googleAccountService.GetUserInfo(retrievePassword: true);
            }

            if (userInfo == null)
            {
                this.logger.Debug("CheckAuthentificationAsync: Cannot get user info.");
                return(AuthentificationResult.FailedResult(null));
            }

            GoogleAuthResponse authResponse = await this.googleAccountWebService.AuthenticateAsync(
                new Uri(this.googleMusicWebService.GetServiceUrl()), userInfo.Email, userInfo.Password);

            if (authResponse.Success)
            {
                if (authResponse.CookieCollection != null && authResponse.CookieCollection.Count > 0)
                {
                    this.googleMusicWebService.Initialize(authResponse.CookieCollection.Cast <Cookie>());
                    await this.googleMusicWebService.SaveCurrentSessionAsync();

                    this.sessionService.GetSession().IsAuthenticated = true;
                    return(AuthentificationResult.SucceedResult());
                }
            }
            else if (authResponse.Error.HasValue)
            {
                string errorMessage = this.GetErrorMessage(authResponse.Error.Value);
                this.logger.Warning("CheckAuthentificationAsync: ErrorMessage: {0}, error code: {1}", errorMessage, authResponse.Error.Value);
                return(AuthentificationResult.FailedResult(errorMessage));
            }

            this.logger.Error("CheckAuthentificationAsync: showing 'Login_Unknown'.");
            return(AuthentificationResult.FailedResult(this.resources.GetString("Authorization_Error_Unknown")));
        }
コード例 #3
0
        public async Task <InnerToken> CheckLoginGoogle(GoogleAuthResponse res)
        {
            Payload payload;

            try
            {
                //If there is no exception , that means the token is authenticated

                payload = await ValidateAsync(res.TokenId, new ValidationSettings
                {
                    Audience = new[] { Configuration["ClientSecret"] }
                });

                ApplicationUser user = await _UserManager.FindByEmailAsync(res.ProfileObj.Email);


                //If the user exists , then return a normal token
                if (user != null)
                {
                    string jwtToken = GetAuthToken(user.UserName, user.Id, user.Email);
                    return(new InnerToken {
                        isValid = true, Token = jwtToken
                    });
                }

                bool re = await CreateUser(res);

                //If it doesn't create
                if (re)
                {
                    ApplicationUser Createduser = await _UserManager.FindByEmailAsync(res.ProfileObj.Email);

                    string jwtToken = GetAuthToken(Createduser.UserName, Createduser.Id, Createduser.Email);
                    return(new InnerToken {
                        isValid = true, Token = jwtToken
                    });
                }
                return(new InnerToken {
                    isValid = false, Error = new string[] { "Sorry token couldn't be created" }
                });
            }
            catch (Exception e)
            {
                //return BadRequest(e);
                return(new InnerToken {
                    isValid = false, Error = new string[] { e.Message }
                });
            }
        }
コード例 #4
0
        private async Task <bool> CreateUser(GoogleAuthResponse res)
        {
            try
            {
                ApplicationUser user = new ApplicationUser {
                    Email = res.ProfileObj.Email, UserName = res.ProfileObj.GivenName + res.ProfileObj.FamilyName
                };
                IdentityResult CreatedUser = await _UserManager.CreateAsync(user);

                return(CreatedUser.Succeeded);
            }
            catch
            {
                return(false);
            }
        }
コード例 #5
0
        public void Handle(LoginFromGoogle c)
        {
            GoogleAuthResponse res = null;

            using (var req = new HttpClient())
            {
                var url = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" + c.IdToken;
                req.BaseAddress = new Uri(url);
                var resx = req.SendAsync(new HttpRequestMessage(HttpMethod.Get, url)).Result;
                if (resx.StatusCode == HttpStatusCode.OK)
                {
                    res = JsonConvert.DeserializeObject <GoogleAuthResponse>(resx.Content.ReadAsStringAsync().Result);
                }
            }
            if (res == null || string.IsNullOrEmpty(res.email))
            {
                throw new Exception("Can not confirm with google");
            }
            User u;

            using (var db = new CoreDbContext())
            {
                u = db.Users.FirstOrDefault(i => i.Username.Equals(c.Email));
            }
            if (u == null)
            {
                u          = new User();
                u.Id       = Guid.NewGuid();
                u.Username = c.Email;
                u.Email    = c.Email;

                var domainUser = new DomainUser();
                domainUser.RegisterFromGoogle(u.Id, c.GoogleId, c.Name, c.Email, c.AvatarUrl, c.IdToken, c.WebsiteUrl);

                _repo.CreateNew(domainUser);
            }

            _repo.GetDoSave(u.Id, o => o.LoginFromGoogle(c.GoogleId, c.Name, c.Email, c.AvatarUrl, c.IdToken));
        }
コード例 #6
0
        public async Task <GoogleAuthResponse> AuthenticateAsync(Uri serviceUri, string email, string password)
        {
            // Check for details: https://developers.google.com/accounts/docs/AuthForInstalledApps
            var responseMessage = await this.SendAsync(
                new HttpRequestMessage(HttpMethod.Post, ClientLoginPath)
            {
                Content = new FormUrlEncodedContent(new Dictionary <string, string>
                {
                    { "accountType", "HOSTED_OR_GOOGLE" },
                    { "Email", email },
                    { "Passwd", password },
                    { "service", "sj" }
                })
            },
                HttpCompletionOption.ResponseContentRead);

            if (!responseMessage.Content.IsPlainText())
            {
                return(GoogleAuthResponse.ErrorResponse(GoogleAuthResponse.ErrorResponseCode.Unknown));
            }

            var dictionary = await responseMessage.Content.ReadAsDictionaryAsync();

            if (!responseMessage.IsSuccessStatusCode ||
                string.IsNullOrEmpty(dictionary["SID"]) ||
                string.IsNullOrEmpty(dictionary["LSID"]))
            {
                var error = GoogleAuthResponse.ErrorResponseCode.Unknown;

                string dictionaryValue;
                if (dictionary.TryGetValue("Error", out dictionaryValue))
                {
                    Enum.TryParse(dictionary["Error"], out error);
                }

                return(GoogleAuthResponse.ErrorResponse(error));
            }

            responseMessage = await this.SendAsync(
                new HttpRequestMessage(HttpMethod.Post, IssueAuthTokenPath)
            {
                Content = new FormUrlEncodedContent(new Dictionary <string, string>()
                {
                    { "SID", dictionary["SID"] },
                    { "LSID", dictionary["LSID"] },
                    { "service", "gaia" }
                })
            },
                HttpCompletionOption.ResponseContentRead);

            if (!responseMessage.IsSuccessStatusCode || !responseMessage.Content.IsPlainText())
            {
                return(GoogleAuthResponse.ErrorResponse(GoogleAuthResponse.ErrorResponseCode.Unknown));
            }

            var token = await responseMessage.Content.ReadAsStringAsync();

            var url = new StringBuilder(TokenAuthPath);

            url.Append("?");
            url.AppendFormat("auth={0}", WebUtility.UrlEncode(token));
            url.AppendFormat("&service=sj");
            url.AppendFormat("&continue={0}", WebUtility.UrlEncode(serviceUri.ToString()));
            var requestUri = url.ToString();

            responseMessage = await this.httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri));

            if (!responseMessage.IsSuccessStatusCode)
            {
                return(GoogleAuthResponse.ErrorResponse(GoogleAuthResponse.ErrorResponseCode.Unknown));
            }

            return(GoogleAuthResponse.SuccessResponse(this.httpClientHandler.CookieContainer.GetCookies(serviceUri), dictionary["Auth"]));
        }