Esempio n. 1
0
        public ActionResult ImplicitCallback(OAuth2TokenResponse response)
        {
            if (ApplicationSettings.ResponseMode == "form_post")
            {
                ViewBag.AccessToken = string.IsNullOrEmpty(response.Access_Token) ? "none" : response.Access_Token;
                ViewBag.IdToken = string.IsNullOrEmpty(response.Id_Token) ? "none" : response.Id_Token;
                ViewBag.Error = response.Error ?? "none";
                ViewBag.ErrorDescription = response.Error_Description ?? "none";
            }
            ViewBag.ResponseMode = ApplicationSettings.ResponseMode;

            return View("ImplicitCallback");
        }
Esempio n. 2
0
        public PushpayClientTest()
        {
            _tokenService = new Mock <IPushpayTokenService>();
            _restClient   = new Mock <IRestClient>();

            _fixture = new PushpayClient(_tokenService.Object, _restClient.Object);

            var token = new OAuth2TokenResponse()
            {
                AccessToken = "123"
            };

            _tokenService.Setup(r => r.GetOAuthToken(It.IsAny <string>())).Returns(Observable.Return(token));
        }
        public static OAuth2TokenResponse Execute(string clientId, string clientSecret, string refreshToken)
        {
            try {
                //https://developers.google.com/accounts/docs/OAuth2WebServer
                //#Using a Refresh Token

                var request = new RestRequest("o/oauth2/token", Method.POST);
                request.AddParameter("client_id", clientId);
                request.AddParameter("client_secret", clientSecret);
                request.AddParameter("refresh_token", refreshToken);
                request.AddParameter("grant_type", "refresh_token");
                request.AddParameter("Content-Type", "application/x-www-form-urlencoded");

                var response = (new RestClient("https://accounts.google.com")).Execute(request);
                //valid response: { "access_token":"1/XXX", "expires_in":3920, "token_type":"Bearer",}
                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    LogIt.W("Unable to get new access token: " + response.StatusCode.ToString() + "|" + response.Content);
                    return(new OAuth2TokenResponse {
                    });
                }
                else
                {
                    var content = response.Content;
                    //LogIt.D(content);

                    dynamic json = Newtonsoft.Json.Linq.JObject.Parse(content);
                    var     tr   = new OAuth2TokenResponse {
                        access_token  = json.access_token,
                        expires_in    = json.expires_in,
                        token_type    = json.token_type,
                        refresh_token = json.refresh_token
                    };

                    //if (string.IsNullOrEmpty(tr.access_token)) {
                    //  //should I clear out refesh token?
                    //  LogIt.E("access token was null");
                    //  //} else {
                    //  //  icalgenie.lib.Db.Credential.AddOrUpdateUserCredentials(new credential_element { name = CredentialElementName.GoogleAccessToken.ToString(), value = tr.access_token }, u, SourceType.GmailAccount);
                    //  //}
                    //}
                    return(tr);
                }
            } catch (Exception ex) {
                LogIt.E(ex);
                throw ex;
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Refreshes the OAuth 2.0 access token using the refresh token provided.
        /// </summary>
        /// <param name="pluginConfiguration">The configuration for the OAuth 2.0 identity provider.</param>
        /// <param name="oAuthTokens">The OAuth 2.0 tokens.</param>
        /// <param name="setHttpHeaders">If true, <see cref="AddAuthorizationHeader"/> will be called automatically.</param>
        /// <param name="token">A cancellation token for the task.</param>
        /// <returns>The updated access token data.</returns>
        public Task <OAuth2TokenResponse> RefreshOAuth2TokenAsync(
            OAuth2Configuration pluginConfiguration,
            OAuth2TokenResponse oAuthTokens,
            bool setHttpHeaders     = true,
            CancellationToken token = default(CancellationToken))
        {
            // Sanity.
            if (null == pluginConfiguration)
            {
                throw new ArgumentNullException(nameof(pluginConfiguration));
            }
            if (null == oAuthTokens)
            {
                throw new ArgumentNullException(nameof(oAuthTokens));
            }

            // Execute the other overload.
            return(this.RefreshOAuth2TokenAsync(pluginConfiguration, oAuthTokens.RefreshToken, setHttpHeaders, token));
        }
Esempio n. 5
0
        /// <summary>
        /// Adds the default Authorization HTTP header as appropriate for the OAuth configuration.
        /// </summary>
        /// <param name="pluginConfiguration">The configuration for the OAuth 2.0 plugin.</param>
        /// <param name="oAuthTokens">The access tokens retrieved via the OAuth flow.</param>
        /// <remarks><see cref="OAuth2Configuration.UseIdTokenAsAccessToken"/> defines whether <see cref="OAuth2TokenResponse.IdToken"/> (if true) or
        /// <see cref="OAuth2TokenResponse.AccessToken"/> (if false) should be used for the bearer value.</remarks>
        public void AddAuthorizationHeader(OAuth2Configuration pluginConfiguration, OAuth2TokenResponse oAuthTokens)
        {
            // Sanity.
            if (null == pluginConfiguration)
            {
                throw new ArgumentNullException(nameof(pluginConfiguration));
            }

            // Clear the authorisation token.
            this.ClearAuthenticationToken();

            // Add the authorisation token to the headers.
            if (pluginConfiguration.UseIdTokenAsAccessToken)
            {
                this.AddDefaultHeader(MFWSClient.AuthorizationHttpHeaderName, "Bearer " + oAuthTokens.IdToken);
            }
            else
            {
                this.AddDefaultHeader(MFWSClient.AuthorizationHttpHeaderName, "Bearer " + oAuthTokens.AccessToken);
            }
        }
Esempio n. 6
0
        public ActionResult CodeFlowCallback(OAuth2TokenResponse response)
        {
            ViewBag.Message = "Response received.";
            ViewBag.ReturnUrl = ApplicationSettings.CodeFlowRedirectUri;
            ViewBag.ClientId = ApplicationSettings.CodeFlowClientId;
            ViewBag.CodeVerifier = Session["codeVerifier"];
            if (ApplicationSettings.ResponseMode == "form_post")
            {
                ViewBag.Code = string.IsNullOrEmpty(response.Code) ? "none" : response.Code;
                ViewBag.Error = response.Error ?? "none";
                ViewBag.ErrorDescription = response.Error_Description ?? "none";
            }
            else
            {
                ViewBag.Code = Request.QueryString["code"] ?? "none";
                ViewBag.Error = Request.QueryString["error"] ?? "none";
                ViewBag.ErrorDescription = Request.QueryString["error_description"] ?? "none";
            }

            return View("CodeFlowCallback");
        }
Esempio n. 7
0
        public async ValueTask <IdentityModel> LoginCallback(IdentityHttpRequest request)
        {
            var callbackBinding = OAuth2Binding.GetBindingForRequest(request, BindingDirection.Response);

            var callbackDocument = new OAuth2LoginResponse(callbackBinding);

            var callbackServiceProvider = callbackDocument.ServiceProvider;
            var code = callbackDocument.AccessCode;

            if (code == null)
            {
                return(null);
            }

            if (serviceProvider != callbackServiceProvider)
            {
                throw new IdentityProviderException("Service Providers do not match", $"Received: {serviceProvider}, Expected: {callbackServiceProvider}");
            }

            //Get Token--------------------
            var requestTokenDocument = new OAuth2TokenRequest(serviceProvider, code);
            var requestTokenBinding  = OAuth2Binding.GetBindingForDocument(requestTokenDocument, BindingType.Query);

            var requestTokenAction = requestTokenBinding.GetResponse(tokenUrl);
            var requestToken       = WebRequest.Create(requestTokenAction.RedirectUrl);
            var responseToken      = await requestToken.GetResponseAsync();

            var responseTokenBinding  = OAuth2Binding.GetBindingForResponse(responseToken, BindingDirection.Response);
            var responseTokenDocument = new OAuth2TokenResponse(responseTokenBinding);

            //Get Identity---------------
            var requestIdentityDocument = new OAuth2IdentityRequest(serviceProvider, responseTokenDocument.Token);
            var requestIdentityBinding  = OAuth2Binding.GetBindingForDocument(requestIdentityDocument, BindingType.Query);

            var requestIdentityAction = requestIdentityBinding.GetResponse(identityUrl);
            var requestIdentity       = WebRequest.Create(requestIdentityAction.RedirectUrl);
            var responseIdentity      = await requestIdentity.GetResponseAsync();

            var responseIdentityBinding  = OAuth2Binding.GetBindingForResponse(responseIdentity, BindingDirection.Response);
            var responseIdentityDocument = new OAuth2IdentityResponse(responseIdentityBinding);

            if (responseIdentityDocument.ServiceProvider != serviceProvider)
            {
                return(null);
            }

            if (String.IsNullOrWhiteSpace(responseIdentityDocument.UserID))
            {
                return(null);
            }

            var identity = new IdentityModel()
            {
                UserID          = responseIdentityDocument.UserID,
                UserName        = responseIdentityDocument.UserName,
                Name            = responseIdentityDocument.UserName,
                ServiceProvider = responseIdentityDocument.ServiceProvider,
                Roles           = responseIdentityDocument.Roles,
                OtherClaims     = null,
                State           = null,
                AccessToken     = responseTokenDocument.Token
            };

            return(identity);
        }