private void butAuthGoogle_Click(object sender, EventArgs e)
 {
     try {
         string url = Google.GetGoogleAuthorizationUrl(textUsername.Text);
         Process.Start(url);
         InputBox inputbox = new InputBox("Please enter the authorization code from your browser");
         inputbox.setTitle("Google Account Authorization");
         inputbox.ShowDialog();
         if (inputbox.DialogResult != DialogResult.OK)
         {
             return;
         }
         if (string.IsNullOrWhiteSpace(inputbox.textResult.Text))
         {
             throw new ODException(Lan.g(this, "There was no authorization code entered."));
         }
         string      authCode = inputbox.textResult.Text;
         GoogleToken tokens   = Google.MakeAccessTokenRequest(authCode);
         if (tokens.ErrorMessage != "")
         {
             throw new Exception(tokens.ErrorMessage);
         }
         textAccessToken.Text         = tokens.AccessToken;
         textRefreshToken.Text        = tokens.RefreshToken;
         groupAuthentication.Location = new Point(_groupAuthLocationXAuthorized, groupAuthentication.Location.Y);
         groupGoogleAuth.Visible      = true;
     }
     catch (ODException ae) {
         MsgBox.Show(ae.Message);
     }
     catch (Exception ex) {
         MsgBox.Show("Error: " + ex.Message);
     }
 }
        /// <inheritdoc />
        /// <summary>
        /// Link google account Links the current user account to a google account, using the acccess token from google. Can also be used to update the access token after it has expired. &lt;br&gt;&lt;br&gt;&lt;b&gt;Permissions Needed:&lt;/b&gt; Non-google user token
        /// </summary>
        /// <param name="googleToken">The token from google</param>
        public void LinkAccounts1(GoogleToken googleToken)
        {
            mWebCallEvent.WebPath = "/social/google/users";
            if (!string.IsNullOrEmpty(mWebCallEvent.WebPath))
            {
                mWebCallEvent.WebPath = mWebCallEvent.WebPath.Replace("{format}", "json");
            }

            mWebCallEvent.HeaderParams.Clear();
            mWebCallEvent.QueryParams.Clear();
            mWebCallEvent.AuthSettings.Clear();
            mWebCallEvent.PostBody = null;

            mWebCallEvent.PostBody = KnetikClient.Serialize(googleToken); // http body (model) parameter

            // authentication settings
            mWebCallEvent.AuthSettings.Add("oauth2_client_credentials_grant");

            // authentication settings
            mWebCallEvent.AuthSettings.Add("oauth2_password_grant");

            // make the HTTP request
            mLinkAccounts1StartTime   = DateTime.Now;
            mWebCallEvent.Context     = mLinkAccounts1ResponseContext;
            mWebCallEvent.RequestType = KnetikRequestType.POST;

            KnetikLogger.LogRequest(mLinkAccounts1StartTime, "LinkAccounts1", "Sending server request...");
            KnetikGlobalEventSystem.Publish(mWebCallEvent);
        }
        /// <summary>
        /// Runs the Wasabee login process to retrieve Wasabeee data
        /// </summary>
        /// <param name="googleToken">Google OAuth response object containing the AccessToken</param>
        /// <returns>Returns a WasabeeLoginResponse with account data</returns>
        public async Task <UserModel?> DoWasabeeLoginAsync(GoogleToken googleToken)
        {
            _loggingService.Trace("Executing LoginProvider.DoWasabeeLoginAsync");

            HttpResponseMessage response;
            var cookieContainer = new CookieContainer();

#if DEBUG_NETWORK_LOGS
            var httpHandler = new HttpLoggingHandler(new HttpClientHandler()
            {
                CookieContainer = cookieContainer
            });
#else
            var httpHandler = new HttpClientHandler()
            {
                CookieContainer = cookieContainer
            };
#endif

            using var client = new HttpClient(httpHandler)
                  {
                      DefaultRequestHeaders = { { "User-Agent", $"WasabeeMobile/{_versionTracking.CurrentVersion} ({_deviceInfo.Platform} {_deviceInfo.VersionString})" } }
                  };

            try
            {
                var wasabeeToken = new WasabeeToken(googleToken.AccessToken);
                var postContent  = new StringContent(JsonConvert.SerializeObject(wasabeeToken), Encoding.UTF8, "application/json");
                response = await client.PostAsync(_appSettings.WasabeeTokenUrl, postContent).ConfigureAwait(false);

                response.EnsureSuccessStatusCode();
            }
            catch (Exception e)
            {
                _loggingService.Error(e, "Error Executing LoginProvider.DoWasabeeLoginAsync");

                return(null);
            }

            var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            var wasabeeUserModel = JsonConvert.DeserializeObject <UserModel?>(responseContent);

            var uri           = new Uri(_appSettings.WasabeeBaseUrl);
            var wasabeeCookie = cookieContainer.GetCookies(uri).Cast <Cookie>()
                                .AsEnumerable()
                                .FirstOrDefault();

            if (wasabeeCookie != null)
            {
                await _secureStorage.SetAsync(SecureStorageConstants.WasabeeCookie, JsonConvert.SerializeObject(wasabeeCookie));
            }

            return(wasabeeUserModel);
        }
Beispiel #4
0
        public IActionResult Auth(string code)
        {
            GoogleToken token    = _authService.GetToken(code);
            string      id_token = token.id_token;
            bool        isValid  = _authService.ValidateToken(token.id_token);

            if (isValid)
            {
                var tokenstring = _authService.CreateJwtToken();

                return(Ok(tokenstring));
            }
            else
            {
                return(BadRequest());
            }
        }
Beispiel #5
0
        public GoogleToken GetToken(string code)
        {
            var dict = new List <KeyValuePair <string, string> >();

            dict.Add(new KeyValuePair <string, string>("code", code));
            dict.Add(new KeyValuePair <string, string>("client_id", "605865129946-9dh1mjotllviruol1b4tcrlad178io4h.apps.googleusercontent.com"));
            dict.Add(new KeyValuePair <string, string>("client_secret", "l3GY_8FhXxsMcSeWh8NUdlb3"));
            dict.Add(new KeyValuePair <string, string>("redirect_uri", "https://localhost:5001/auth"));
            dict.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));
            var client = new HttpClient();
            var req    = new HttpRequestMessage(HttpMethod.Post, "https://www.googleapis.com/oauth2/v4/token");

            req.Content = new FormUrlEncodedContent(dict);
            HttpResponseMessage response = client.SendAsync(req).Result;
            string      res   = response.Content.ReadAsStringAsync().Result;
            GoogleToken token = JsonConvert.DeserializeObject <GoogleToken>(res);

            return(token);
        }
Beispiel #6
0
        /// <summary>
        /// GoogleトークンDB登録処理
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task <bool> SetGoogleToken(Entities.GoogleEntity.Token token)
        {
            var setting = new GoogleToken()
            {
                AccessToken  = token.AccessToken,
                RefreshToken = token.RefreshToken,
                ExpiresIn    = DateTime.Now.AddHours(1)
            };

            try
            {
                await _settingContainer.UpsertItemAsync(setting);
            }
            catch (Exception e)
            {
                //TODO
                Console.Write(e.Message);
                return(false);
            }
            return(true);
        }
Beispiel #7
0
        public async Task <IActionResult> GoogleLogin(GoogleToken googleToken)
        {
            var result = await TokenValidation(googleToken.Token);

            if (result == null)
            {
                return(Unauthorized());
            }

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

            if (user == null)
            {
                return(Unauthorized());
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.Name, user.Name)
            };

            var key             = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_configuration.GetSection("AuthSetting:tokenKey").Value));
            var credential      = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddHours(12),
                SigningCredentials = credential
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new { token = tokenHandler.WriteToken(token) }));
        }
Beispiel #8
0
        public async Task <IActionResult> GoogleCallback([FromQuery] IDictionary <string, string> query)
        {
            if (query["code"] == null)
            {
                return(Redirect("/"));
            }

            Dictionary <string, string> parameters = new Dictionary <string, string>();

            parameters["code"]          = query["code"];
            parameters["client_id"]     = _oauthConfig.Value.Google.client_id;
            parameters["redirect_uri"]  = $"https://{this.Request.Host}/Auth/GoogleCallback";
            parameters["client_secret"] = _oauthConfig.Value.Google.client_secret;
            parameters["grant_type"]    = "authorization_code";

            GoogleToken userToken = await requester.Post <GoogleToken>("https://accounts.google.com/o/oauth2/token", parameters);

            if (userToken == null)
            {
                TempData["error"] = "Could not link your account.";
                return(Redirect("/"));
            }

            if (string.IsNullOrEmpty(userToken.access_token) || string.IsNullOrEmpty(userToken.id_token))
            {
                TempData["error"] = "Could not link your account. Provider returned no info.";
                return(Redirect("/"));
            }

            // An alternative for using Google's library for verifying the token would be to
            // make a GET request to https://www.googleapis.com/oauth2/v2/tokeninfo?id_token={id_token}
            // which would verify the token but would introduce one more web request in the process.
            // This does not scale well for more complex use cases; Google's library does the verification offline.
            var validPayload = await GoogleJsonWebSignature.ValidateAsync(userToken.id_token);

            if (validPayload is null)
            {
                TempData["error"] = "Identity of the provider token could not be verified.";
                return(Redirect("/"));
            }

            // Fetching data
            var userWithMatchingToken = await _context.Users.Where(c => c.Credentials.Any(cred => cred.Provider == AuthProvider.GOOGLE && cred.Token == validPayload.Subject)).FirstOrDefaultAsync();

            var userWithMatchingEmail = await _context.Users.Where(c => c.Email == validPayload.Email).FirstOrDefaultAsync();

            // If user is logged in and the auth token is not registered yet, link.
            if (HttpContext.Session.GetString("user") != null)
            {
                var user = await _context.Users.Where(c => c.Id == HttpContext.Session.GetString("user")).Include("Credentials").FirstOrDefaultAsync();

                // If someone already has that token OR there is a user that has the email but is not the same user.
                if (userWithMatchingToken != null || (userWithMatchingEmail != null && userWithMatchingEmail.Email != user.Email))
                {
                    TempData["error"] = "This Google account is already linked!";
                    return(Redirect("/"));
                }

                if (user.Credentials == null)
                {
                    user.Credentials = new List <Credential>();
                }
                // Adding the token and saving
                user.Credentials.Add(new Credential(AuthProvider.GOOGLE, validPayload.Subject));
                await _context.SaveChangesAsync();

                TempData["info"] = "You have linked your Google account!";
                return(Redirect("/"));
            }

            // If user is NOT logged in, check if linked to some account, and log user in.
            if (userWithMatchingToken != null)
            {
                HttpContext.Session.SetString("user", userWithMatchingToken.Id);
                return(Redirect("/"));
            }

            // If NOT linked, create a new account ONLY if that email is not used already.`
            if (userWithMatchingEmail?.Email == validPayload.Email)
            {
                TempData["error"] = "This Google account's email has been used to create an account here, so you can not link it!";
                return(Redirect("/"));
            }

            // Creating a new account:
            User u = new User(validPayload.Email, "", new Credential(AuthProvider.GOOGLE, validPayload.Subject));

            _context.Users.Add(u);
            await _context.SaveChangesAsync();

            // Assigning user id to session
            HttpContext.Session.SetString("user", u.Id);

            // Setting info alert
            TempData["info"] = "You have successfully created an account with Google!";

            return(Redirect("/"));
        }
Beispiel #9
0
        public async Task <IActionResult> PostGoogle(string token)
        {
            var user = await GoogleToken.ValidateCurrentToken(token);

            return(Ok(user));
        }
Beispiel #10
0
        public async Task <UserModel?> WasabeeLoginAsync(GoogleToken googleToken)
        {
            _loggingService.Trace("Executing AuthentificationService.WasabeeLoginAsync");

            return(await _loginProvider.DoWasabeeLoginAsync(googleToken));
        }
        /// <summary>
        /// Link google account Links the current user account to a google account, using the acccess token from google. Can also be used to update the access token after it has expired. &lt;br&gt;&lt;br&gt;&lt;b&gt;Permissions Needed:&lt;/b&gt; Non-google user token
        /// </summary>
        /// <exception cref="com.knetikcloud.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="googleToken">The token from google (optional)</param>
        /// <returns>ApiResponse of Object(void)</returns>
        public ApiResponse <Object> LinkAccounts1WithHttpInfo(GoogleToken googleToken = null)
        {
            var    localVarPath         = "/social/google/users";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new List <KeyValuePair <String, String> >();
            var    localVarHeaderParams = new Dictionary <String, String>(Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            if (googleToken != null && googleToken.GetType() != typeof(byte[]))
            {
                localVarPostBody = Configuration.ApiClient.Serialize(googleToken); // http body (model) parameter
            }
            else
            {
                localVarPostBody = googleToken; // byte array
            }

            // authentication (oauth2_client_credentials_grant) required
            // oauth required
            if (!String.IsNullOrEmpty(Configuration.AccessToken))
            {
                localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
            }
            // authentication (oauth2_password_grant) required
            // oauth required
            if (!String.IsNullOrEmpty(Configuration.AccessToken))
            {
                localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
            }

            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)Configuration.ApiClient.CallApi(localVarPath,
                                                                                            Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                            localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("LinkAccounts1", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <Object>(localVarStatusCode,
                                            localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                                            null));
        }
 /// <summary>
 /// Link google account Links the current user account to a google account, using the acccess token from google. Can also be used to update the access token after it has expired. &lt;br&gt;&lt;br&gt;&lt;b&gt;Permissions Needed:&lt;/b&gt; Non-google user token
 /// </summary>
 /// <exception cref="com.knetikcloud.Client.ApiException">Thrown when fails to make API call</exception>
 /// <param name="googleToken">The token from google (optional)</param>
 /// <returns></returns>
 public void LinkAccounts1(GoogleToken googleToken = null)
 {
     LinkAccounts1WithHttpInfo(googleToken);
 }