Beispiel #1
0
        public RefreshResult Refresh(Uri url, IAuthorizationState authorizationState)
        {
            var client = GetClient(url);

            try
            {
                var refreshed = client.RefreshAuthorization(authorizationState);

                if (!refreshed)
                    return new RefreshResult
                    {
                        Error = "Uhm, not entirely sure what happened."
                    };
            }
            catch (Exception e)
            {
                var error = e.Message;

                if (e.InnerException != null)
                    error = string.Format("{0}\nInner exception: {1}", error, e.InnerException.Message);

                return new RefreshResult
                {
                    Error = error
                };
            }

            return new RefreshResult
            {
                AuthorizationState = authorizationState
            };
        }
 public NamedAuthorizationState(string name, IAuthorizationState authorizationState)
 {
     Guid = Guid.NewGuid();
     Name = name;
     AuthorizationState = authorizationState;
     IsHistorical = false;
 }
Beispiel #3
0
        private IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            // Get the auth URL:
            _state = new AuthorizationState(new[] {DriveService.Scopes.Drive.GetStringValue()});
            _state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            Uri authUri = arg.RequestUserAuthorization(_state);

            //Show Login UI. It's tip for user 
            var dlg = new AuthDlg(StorageType.GDrive);
            dlg.Top = 0;
            dlg.Show();

            // Request authorization from the user (by opening a browser window):
            //Process.Start(authUri.ToString());    
            _webViewCallback(authUri.ToString());

            dlg.Close(); //close non-modal stub dialog 

            //open another, modal dialog to block execution until user clicks OK
            dlg = new AuthDlg(StorageType.GDrive) {Top = 0};
            dlg.ShowDialog();

            // Retrieve the access token by using the authorization code:
            return arg.ProcessUserAuthorization(dlg.AuthCode, _state);
        }
Beispiel #4
0
        public void Authorize(ref IAuthorizationState authorization, string refreshToken)
        {
            if ((authorization == null))
            {
                authorization = new AuthorizationState
                {
                    Callback = _redirectUri,
                    RefreshToken = refreshToken
                };
            }

            bool refreshFailed = false;
            if (AccessTokenHasToBeRefreshed(authorization))
            {
                try
                {
                    refreshFailed = !RefreshAuthorization(authorization);
                }
                catch (ProtocolException)
                {
                    //The refreshtoken is not valid anymore
                }
            }

            if (authorization.AccessToken == null || refreshFailed)
            {
                using (var loginDialog = new LoginForm(_redirectUri))
                {
                    loginDialog.AuthorizationUri = GetAuthorizationUri(authorization);
                    loginDialog.ShowDialog();
                    ProcessUserAuthorization(loginDialog.AuthorizationUri, authorization);
                }
            }
        }
Beispiel #5
0
		/// <summary>
		/// Generates a URL that the user's browser can be directed to in order to authorize
		/// this client to access protected data at some resource server.
		/// </summary>
		/// <param name="authorization">The authorization state that is tracking this particular request.  Optional.</param>
		/// <param name="implicitResponseType">
		/// <c>true</c> to request an access token in the fragment of the response's URL;
		/// <c>false</c> to authenticate to the authorization server and acquire the access token (and possibly a refresh token) via a private channel.
		/// </param>
		/// <param name="state">The client state that should be returned with the authorization response.</param>
		/// <returns>
		/// A fully-qualified URL suitable to initiate the authorization flow.
		/// </returns>
		public Uri RequestUserAuthorization(IAuthorizationState authorization, bool implicitResponseType = false, string state = null) {
			Requires.NotNull(authorization, "authorization");
			Requires.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier));

			var request = this.PrepareRequestUserAuthorization(authorization, implicitResponseType, state);
			return this.Channel.PrepareResponse(request).GetDirectUriRequest(this.Channel);
		}
		/// <summary>
		/// Prepares a request for user authorization from an authorization server.
		/// </summary>
		/// <param name="authorization">The authorization state to associate with this particular request.</param>
		/// <returns>The authorization request.</returns>
		public OutgoingWebResponse PrepareRequestUserAuthorization(IAuthorizationState authorization) {
			Requires.NotNull(authorization, "authorization");
			Requires.ValidState(authorization.Callback != null || (HttpContext.Current != null && HttpContext.Current.Request != null), MessagingStrings.HttpContextRequired);
			Requires.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier), OAuth2Strings.RequiredPropertyNotYetPreset, "ClientIdentifier");
			Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);

			if (authorization.Callback == null) {
				authorization.Callback = this.Channel.GetRequestFromContext().GetPublicFacingUrl()
					.StripMessagePartsFromQueryString(this.Channel.MessageDescriptions.Get(typeof(EndUserAuthorizationSuccessResponseBase), Protocol.Default.Version))
					.StripMessagePartsFromQueryString(this.Channel.MessageDescriptions.Get(typeof(EndUserAuthorizationFailedResponse), Protocol.Default.Version));
				authorization.SaveChanges();
			}

			var request = new EndUserAuthorizationRequest(this.AuthorizationServer) {
				ClientIdentifier = this.ClientIdentifier,
				Callback = authorization.Callback,
			};
			request.Scope.ResetContents(authorization.Scope);

			// Mitigate XSRF attacks by including a state value that would be unpredictable between users, but
			// verifiable for the same user/session.
			// If the host is implementing the authorization tracker though, they're handling this protection themselves.
			if (this.AuthorizationTracker == null) {
				var context = this.Channel.GetHttpContext();
				if (context.Session != null) {
					request.ClientState = context.Session.SessionID;
				} else {
					Logger.OAuth.WarnFormat("No request context discovered, so no client state parameter could be set to mitigate XSRF attacks.");
				}
			}

			return this.Channel.PrepareResponse(request);
		}
		/// <summary>
		/// Scans the incoming request for an authorization response message.
		/// </summary>
		/// <param name="actualRedirectUrl">The actual URL of the incoming HTTP request.</param>
		/// <param name="authorizationState">The authorization.</param>
		/// <returns>The granted authorization, or <c>null</c> if the incoming HTTP request did not contain an authorization server response or authorization was rejected.</returns>
		public IAuthorizationState ProcessUserAuthorization(Uri actualRedirectUrl, IAuthorizationState authorizationState = null) {
			Contract.Requires<ArgumentNullException>(actualRedirectUrl != null);

			if (authorizationState == null) {
				authorizationState = new AuthorizationState();
			}

			var carrier = new HttpRequestInfo("GET", actualRedirectUrl, actualRedirectUrl.PathAndQuery, new System.Net.WebHeaderCollection(), null);
			IDirectedProtocolMessage response = this.Channel.ReadFromRequest(carrier);
			if (response == null) {
				return null;
			}

			EndUserAuthorizationSuccessAccessTokenResponse accessTokenSuccess;
			EndUserAuthorizationSuccessAuthCodeResponse authCodeSuccess;
			EndUserAuthorizationFailedResponse failure;
			if ((accessTokenSuccess = response as EndUserAuthorizationSuccessAccessTokenResponse) != null) {
				UpdateAuthorizationWithResponse(authorizationState, accessTokenSuccess);
			} else if ((authCodeSuccess = response as EndUserAuthorizationSuccessAuthCodeResponse) != null) {
				this.UpdateAuthorizationWithResponse(authorizationState, authCodeSuccess);
			} else if ((failure = response as EndUserAuthorizationFailedResponse) != null) {
				authorizationState.Delete();
				return null;
			}

			return authorizationState;
		}
Beispiel #8
0
 /// <summary>
 /// Retrieve an IAuthenticator instance using the provided state.
 /// </summary>
 /// <param name="credentials">OAuth 2.0 credentials to use.</param>
 /// <returns>Authenticator using the provided OAuth 2.0 credentials</returns>
 public static IAuthenticator GetAuthenticatorFromState(IAuthorizationState credentials)
 {
     var provider = new StoredStateClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET, credentials);
     var auth = new OAuth2Authenticator<StoredStateClient>(provider, StoredStateClient.GetState);
     auth.LoadAccessToken();
     return auth;
 }
 public void ApplyAuthenticationToRequest(HttpWebRequest request)
 {
     this.LoadAccessToken();
     try
     {
         if (this.State != null && !string.IsNullOrEmpty(this.State.AccessToken))
         {
             if (!string.IsNullOrEmpty(this.State.RefreshToken))
             {
                 this.tokenProvider.AuthorizeRequest(request, this.State);
             }
             else
             {
                 ClientBase.AuthorizeRequest(request, this.State.AccessToken);
             }
         }
     }
     finally
     {
         if (this.NoCaching)
         {
             this.State = null;
         }
     }
 }
        private cGoogle()
        {
            // Register the authenticator. The Client ID and secret have to be copied from the API Access
            // tab on the Google APIs Console.
            provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            provider.ClientIdentifier = "528532804655.apps.googleusercontent.com";
            provider.ClientSecret = "9QSFSAg0dE5CqC5F_Ot6MD8f";

            // Get the auth URL:
            state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            Uri authUri = provider.RequestUserAuthorization(state);

            // Request authorization from the user (by opening a browser window):
            Process.Start(authUri.ToString());
            // Initialize background workers
            authWorker = new BackgroundWorker();
            fetchWorker = new BackgroundWorker();
            authWorker.WorkerReportsProgress = true;
            authWorker.WorkerSupportsCancellation = true;
            authWorker.DoWork += new DoWorkEventHandler(authWorker_DoWork);
            authWorker.ProgressChanged += new ProgressChangedEventHandler(authWorker_ProgressChanged);
            fetchWorker.WorkerReportsProgress = true;
            fetchWorker.WorkerSupportsCancellation = true;
            fetchWorker.DoWork += new DoWorkEventHandler(fetchWorker_DoWork);
            fetchWorker.ProgressChanged += new ProgressChangedEventHandler(fetchWorker_ProgressChanged);
        }
        public void Authenticate(Uri responseUri)
        {
            authorization = oAuthClient.ProcessUserAuthorization(responseUri, authorization);

            exactClient = new ExactOnlineClient(endPoint, GetAccessToken);

            dropboxUserToken.UpdateOrCreateToken(HardcodedUser.Id, exactToken: authorization.AccessToken, exactTokenExpiration: authorization.AccessTokenExpirationUtc);
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="BearerTokenHttpMessageHandler" /> class.
		/// </summary>
		/// <param name="client">The client associated with the authorization.</param>
		/// <param name="authorization">The authorization.</param>
		/// <param name="innerHandler">The inner handler.</param>
		public BearerTokenHttpMessageHandler(ClientBase client, IAuthorizationState authorization, HttpMessageHandler innerHandler)
			: base(innerHandler) {
			Requires.NotNull(client, "client");
			Requires.NotNull(authorization, "authorization");
			Requires.That(!string.IsNullOrEmpty(authorization.AccessToken), "authorization.AccessToken", "AccessToken must be non-empty");
			this.Client = client;
			this.Authorization = authorization;
		}
Beispiel #13
0
        /// <summary>
        /// Retrieve an IAuthenticator instance using the provided state.
        /// </summary>
        /// <param name="credentials">OAuth 2.0 credentials to use.</param>
        /// <returns>Authenticator using the provided OAuth 2.0 credentials</returns>
        public static IAuthenticator GetAuthenticatorFromState(IAuthorizationState credentials)
        {
            var provider = new StoredStateClient(GoogleAuthenticationServer.Description, ClientCredentials.CLIENT_ID, ClientCredentials.CLIENT_SECRET, credentials);
            var auth     = new OAuth2Authenticator <StoredStateClient>(provider, StoredStateClient.GetState);

            auth.LoadAccessToken();
            return(auth);
        }
Beispiel #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StoredStateClient"/> class.
 /// </summary>
 /// <param name="authorizationServer">The token issuer.</param>
 /// <param name="clientIdentifier">The client identifier.</param>
 /// <param name="clientSecret">The client secret.</param>
 public StoredStateClient(AuthorizationServerDescription authorizationServer,
                          String clientIdentifier,
                          String clientSecret,
                          IAuthorizationState state)
     : base(authorizationServer, clientIdentifier, clientSecret)
 {
     this.State = state;
 }
Beispiel #15
0
		internal new DelegatingHandler CreateAuthorizingHandler(IAuthorizationState authorization, HttpMessageHandler innerHandler = null)
		{
			if (authorization == null)
			{
				throw new Exception("Authorization");
			}
			return new LinkedInTokenHttpMessageHandler(this, authorization, innerHandler ?? new HttpClientHandler());
		}
 private string CallAPI(IAuthorizationState authorization) {
     var webClient = new WebClient();
     webClient.Headers["Content-Type"] = "application/json";
     webClient.Headers["X-JavaScript-User-Agent"] = "Demo";
     this.Client.AuthorizeRequest(webClient, this.Authorization);
     var valueString = webClient.DownloadString("http://localhost:49810/api/values");
     return valueString;
 }
Beispiel #17
0
        /// <summary>
        /// 刷新GoogleToken信息
        /// </summary>
        private void RefreshConnectionToken(GoogleConnection connection)
        {
            _token = _googleTokenService.DeserializeToken(connection.Token);
            _googleTokenService.RefreshToken(_token);

            connection.SetToken(_googleTokenService.SerializeToken(_token));
            _accountConnectionService.Update(connection);
        }
Beispiel #18
0
        public ActionResult Login()
        {
            // COMMENT THESE TWO LINES AND MODIFY CConstants
            // with your Facebook AppId and AppSecret Keys
            Session[CConstants.SESSION_ADMNLOGGED] = true;

            return(RedirectToAction("Index", "Home", new { Area = "Admn" }));

            IAuthorizationState authorization = client.ProcessUserAuthorization();

            if (authorization == null)
            {
                // start authorization request
                // request goes to facebook to request accesstoken
                client.RequestUserAuthorization(new String[] { "email" });
            }
            else
            {
                if (null != authorization.AccessToken)
                {
                    // use that accesstoken to request information
                    // from the user's profile
                    var request = WebRequest.Create(
                        String.Format(
                            "https://graph.facebook.com/me?access_token={0}",
                            Uri.EscapeDataString(authorization.AccessToken))
                        );

                    using (var response = request.GetResponse())
                    {
                        using (var responseStream = response.GetResponseStream())
                        {
                            var graph = FacebookGraph.Deserialize(responseStream);

                            string myUserName = graph.Name;
                            string myEmail    = graph.Email;

                            // use the data in the graph object to authorise the user
                            if (
                                !String.IsNullOrEmpty(myEmail)

                                &&

                                myEmail.Equals(
                                    CConstants.ADMINISTRATOR, StringComparison.OrdinalIgnoreCase))
                            {
                                Session[CConstants.SESSION_ADMNLOGGED] = true;

                                return(RedirectToAction("Index", "Home", new { Area = "Admn" }));
                            }
                        }
                    }
                }
            }

            return(Content("Authorization Failed"));
        }
Beispiel #19
0
        /// <summary>
        /// Calculates the fraction of life remaining in an access token.
        /// </summary>
        /// <param name="authorization">The authorization to measure.</param>
        /// <returns>A fractional number no greater than 1.  Could be negative if the access token has already expired.</returns>
        private static double ProportionalLifeRemaining(IAuthorizationState authorization)
        {
            // Calculate what % of the total life this access token has left.
            TimeSpan totalLifetime               = authorization.AccessTokenExpirationUtc.Value - authorization.AccessTokenIssueDateUtc.Value;
            TimeSpan elapsedLifetime             = DateTime.UtcNow - authorization.AccessTokenIssueDateUtc.Value;
            double   proportionLifetimeRemaining = 1 - (elapsedLifetime.TotalSeconds / totalLifetime.TotalSeconds);

            return(proportionLifetimeRemaining);
        }
        /// <summary>
        /// Generates a URL that the user's browser can be directed to in order to authorize
        /// this client to access protected data at some resource server.
        /// </summary>
        /// <param name="authorization">The authorization state that is tracking this particular request.  Optional.</param>
        /// <param name="implicitResponseType">
        /// <c>true</c> to request an access token in the fragment of the response's URL;
        /// <c>false</c> to authenticate to the authorization server and acquire the access token (and possibly a refresh token) via a private channel.
        /// </param>
        /// <param name="state">The client state that should be returned with the authorization response.</param>
        /// <returns>
        /// A fully-qualified URL suitable to initiate the authorization flow.
        /// </returns>
        public Uri RequestUserAuthorization(IAuthorizationState authorization, bool implicitResponseType = false, string state = null)
        {
            Requires.NotNull(authorization, "authorization");
            RequiresEx.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier));

            var request = this.PrepareRequestUserAuthorization(authorization, implicitResponseType, state);

            return(this.Channel.PrepareResponse(request).GetDirectUriRequest(this.Channel));
        }
Beispiel #21
0
 public NamedAuthorizationState(string name, IAuthorizationState authorizationState, bool shouldRefresh, Uri url)
 {
     Guid = Guid.NewGuid();
     Name = name;
     AuthorizationState = authorizationState;
     ShouldRefresh      = shouldRefresh;
     Url          = url;
     IsHistorical = false;
 }
Beispiel #22
0
        /// <summary>
        /// Retrieve an IAuthenticator instance using the provided state.
        /// </summary>
        /// <param name="credentials">OAuth 2.0 credentials to use.</param>
        /// <returns>Authenticator using the provided OAuth 2.0 credentials</returns>
        public static IAuthenticator GetAuthenticatorFromState(IAuthorizationState credentials)
        {
            var provider = new StoredStateClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET, credentials);
            var auth     = new OAuth2Authenticator <StoredStateClient>(provider, StoredStateClient.GetState);

            auth.LoadAccessToken();
            /*Si el access token es nuevo, hay que guardarlo*/
            return(auth);
        }
Beispiel #23
0
 /// <summary>
 ///     Create an HTTP Handler for client only auth.
 /// </summary>
 /// <param name="authBaseUri">The base auth URI e.g. https://auth.alitudeangel.com</param>
 /// <param name="clientId">Your client ID</param>
 /// <param name="clientSecret">Your client secret</param>
 /// <param name="scopes">Requested scopes</param>
 /// <param name="existingState">(optional) An existing state object from a previous session. May be null.</param>
 public static ClientHandlerInfo Create(string authBaseUri,
                                        string clientId,
                                        string clientSecret,
                                        IEnumerable <string> scopes,
                                        IAuthorizationState existingState = null
                                        )
 {
     return(Create(authBaseUri, clientId, clientSecret, scopes, existingState, false, null, null));
 }
Beispiel #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BearerTokenHttpMessageHandler" /> class.
 /// </summary>
 /// <param name="client">The client associated with the authorization.</param>
 /// <param name="authorization">The authorization.</param>
 /// <param name="innerHandler">The inner handler.</param>
 public BearerTokenHttpMessageHandler(ClientBase client, IAuthorizationState authorization, HttpMessageHandler innerHandler)
     : base(innerHandler)
 {
     Requires.NotNull(client, "client");
     Requires.NotNull(authorization, "authorization");
     Requires.That(!string.IsNullOrEmpty(authorization.AccessToken), "authorization.AccessToken", "AccessToken must be non-empty");
     this.Client        = client;
     this.Authorization = authorization;
 }
 public NamedAuthorizationState(string name, IAuthorizationState authorizationState, bool shouldRefresh, Uri url)
 {
     Guid = Guid.NewGuid();
     Name = name;
     AuthorizationState = authorizationState;
     ShouldRefresh = shouldRefresh;
     Url = url;
     IsHistorical = false;
 }
        protected void btnDeAuth_Click(object sender, EventArgs e)
        {
            Profile pf = Profile.GetUser(User.Identity.Name);

            pf.SetPreferenceForKey(LeonClient.TokenPrefKey, null, true);
            pf.SetPreferenceForKey(LeonClient.SubDomainPrefKey, null, true);
            AuthState = null;
            Response.Redirect(Request.Path);
        }
Beispiel #27
0
        /// <summary>
        /// Handle OAuth2 authorization and store the authorization in the session so it's available on all our pages
        /// </summary>
        public void Authorize(HttpSessionState session, string relativeReturnUrl)
        {
            Authorization = (IAuthorizationState)session["Authorization"];
            Uri uri = generateAuthorizationReturnUrl(relativeReturnUrl);

            Authorize(uri);
            session["Authorization"] = Authorization;

            RetrieveCurrentCompany();
        }
Beispiel #28
0
        private void GetCode()
        {
            IAuthorizationState state = DriveAuthentication.ExchangeCode(token);

            SettingsManager.ApiUserKey    = state.AccessToken;
            SettingsManager.ApiUserSecret = state.RefreshToken;

            GoogleDriveSuccess = true;
            Close();
        }
        /// <summary>
        /// Convert an authorization token for an access token.
        /// </summary>
        /// <param name="Request">The http request</param>
        /// <returns>The granted access token</returns>
        public virtual AuthorizationState ConvertToken(HttpRequest Request)
        {
            WebServerClient consumer = new WebServerClient(Description(), AppKey, AppSecret);

            consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(AppSecret);
            IAuthorizationState grantedAccess = consumer.ProcessUserAuthorization(new HttpRequestWrapper(Request));

            // Kindof a hack below, but we convert from IAuthorizationState to AuthorizationState via JSON so that we have a concrete object that we can instantiate.
            return(JsonConvert.DeserializeObject <AuthorizationState>(JsonConvert.SerializeObject(grantedAccess)));
        }
Beispiel #30
0
        /// <summary>
        /// Generates a URL that the user's browser can be directed to in order to authorize
        /// this client to access protected data at some resource server.
        /// </summary>
        /// <param name="authorization">The authorization state that is tracking this particular request.  Optional.</param>
        /// <param name="implicitResponseType"><c>true</c> to request an access token in the fragment of the response's URL;
        /// <c>false</c> to authenticate to the authorization server and acquire the access token (and possibly a refresh token) via a private channel.</param>
        /// <param name="state">The client state that should be returned with the authorization response.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// A fully-qualified URL suitable to initiate the authorization flow.
        /// </returns>
        public async Task <Uri> RequestUserAuthorizationAsync(IAuthorizationState authorization, bool implicitResponseType = false, string state = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            Requires.NotNull(authorization, "authorization");
            RequiresEx.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier));

            var request  = this.PrepareRequestUserAuthorization(authorization, implicitResponseType, state);
            var response = await this.Channel.PrepareResponseAsync(request, cancellationToken);

            return(response.GetDirectUriRequest());
        }
Beispiel #31
0
        public void SignIn(IOAuth2SignInSettings signInSettings)
        {
            var client = GetClient(signInSettings);
            IAuthorizationState authorization = client.ProcessUserAuthorization();

            if (authorization == null)
            {
                client.RequestUserAuthorization(signInSettings.DataRequestScopes, signInSettings.SignInCallbackEndpoint(_request, _urls));
            }
        }
Beispiel #32
0
 public ActionResult Index(string code, string state)
 {
     if (!string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(state))
     {
         var authorization = _client.ProcessUserAuthorization(Request);
         Authorization = authorization;
         return(View(authorization));
     }
     return(View());
 }
Beispiel #33
0
        /// <summary>
        /// Requests a new authorization state using an existing valid state, which contains a refresh token.
        /// </summary>
        /// <returns>
        /// A refreshed access token used to request resources from the Visma eAccounting web API.
        /// </returns>
        /// <param name="client">WebServerClient used to ask for access token and resources.</param>
        public static IAuthorizationState RequestAuthorizationRefresh(IAuthorizationState state)
        {
            // Creates a client in order to ask for a new authorization state
            var client = CreateClient();

            // Refreshes the old authorization state with the a refresh token
            client.RefreshAuthorization(state);

            return(state);
        }
Beispiel #34
0
        /// <summary>
        /// Returns the identity of the current user from a third-party authentication provider
        /// </summary>
        /// <returns></returns>
        public LoggedInUserIdentity GetUserIdentity(string returnUrl)
        {
            IAuthorizationState authorizationState = this.ProcessUserAuthorization();

            if (authorizationState == null)
            {
                string callbackURL = string.Empty;

                // Send the authorization request to the corresponding authorization server. If all of the providers could agree on the same format, we could
                // be doing the same code irrespective of which identity provider is being used which would be the ideal design.
                if (_identityProvider == IdentityProvider.Google)
                {
                    callbackURL = ConfigurationManager.AppSettings["GoogleCallbackURL"];

                    // TODO: Google is lame and does not support addition of extra data at the end of the call back URL. We need to use an extra
                    // state parameter for which DotNetOpenAuth does not have support yet.
                    this.RequestUserAuthorization(_requestScopes, new Uri(this.GetUrl(callbackURL)));
                }
                else if (_identityProvider == IdentityProvider.Facebook)
                {
                    callbackURL = ConfigurationManager.AppSettings["FacebookCallbackURL"];

                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        this.RequestUserAuthorization(_requestScopes, new Uri(this.GetUrl(callbackURL + "?returnUrl=" + returnUrl)));
                    }
                    else
                    {
                        this.RequestUserAuthorization(_requestScopes, new Uri(this.GetUrl(callbackURL)));
                    }
                }
            }
            else
            {
                // Check to see if the access token is valid and if not, try to refresh it using the refresh token
                if (authorizationState.AccessTokenExpirationUtc < DateTime.UtcNow && authorizationState.RefreshToken != null)
                {
                    this.RefreshAuthorization(authorizationState);
                }

                // Append the access token to the request URI to notify the server we are authenticated
                var request = HttpWebRequest.Create(_requestUri + "?access_token=" + authorizationState.AccessToken) as HttpWebRequest;

                // Parse the response and return an identity object
                using (var response = request.GetResponse())
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        return(this.HandleResponseStream(responseStream));
                    }
                }
            }

            return(null);
        }
		internal Authorize2(UserAgentClient client, IAuthorizationState authorizationState) {
			Contract.Requires(client != null, "client");
			Contract.Requires(authorizationState != null, "authorizationState");

			this.InitializeComponent();

			this.client = client;
			this.Authorization = authorizationState;
			Uri authorizationUrl = this.client.RequestUserAuthorization(this.Authorization);
			this.webBrowser.Navigate(authorizationUrl.AbsoluteUri); // use AbsoluteUri to workaround bug in WebBrowser that calls Uri.ToString instead of Uri.AbsoluteUri leading to escaping errors.
		}
Beispiel #36
0
        /// <summary>
        ///     Create an HTTP Handler that supports OAuth user authentication.
        /// </summary>
        /// <param name="authBaseUri">The base auth URI e.g. https://auth.alitudeangel.com</param>
        /// <param name="clientId">Your client ID</param>
        /// <param name="clientSecret">Your client secret</param>
        /// <param name="scopes">Requested scopes</param>
        /// <param name="existingState">(optional) An existing state object from a previous session. May be null.</param>
        /// <param name="requireUserToken">true to aquire a user token, false to get a client only token.</param>
        /// <param name="redirectUri">The redirect URI to use for user token auth. Must match the registered URI for your client ID.</param>
        /// <param name="codeProvider">Implementation to use to get an authorization code URI from an auth login URI.</param>
        /// <returns>
        ///     A <see cref="ClientHandlerInfo"/> object that contains the auth state and the handler. The auth state may be persisted and passed
        ///     back in on future runs of the application to save login state.
        /// </returns>
        public static ClientHandlerInfo Create(
            string authBaseUri,
            string clientId,
            string clientSecret,
            IEnumerable <string> scopes,
            IAuthorizationState existingState,
            bool requireUserToken,
            string redirectUri,
            IAuthorizeCodeProvider codeProvider)
        {
            var        serverDescription = GetServerDescription(authBaseUri);
            ClientBase client;
            var        state = existingState;

            if (requireUserToken)
            {
                if (codeProvider == null || string.IsNullOrEmpty(redirectUri))
                {
                    throw new ArgumentNullException(nameof(codeProvider),
                                                    $"{nameof(codeProvider)} or {nameof(redirectUri)} cannot be null if {nameof(requireUserToken)} is true.");
                }

                var userClient = new UserAgentClient(serverDescription, clientId, ClientCredentialApplicator.PostParameter(clientSecret));
                if (state == null)
                {
                    // Open browser here
                    var returnTo = new Uri(redirectUri);
                    var uri      = userClient.RequestUserAuthorization(scopes, returnTo: returnTo);
                    var result   = codeProvider.GetCodeUri(uri, returnTo).Result;

                    state = new AuthorizationState {
                        Callback = returnTo
                    };
                    state.Scope.AddRange(scopes);
                    state = userClient.ProcessUserAuthorization(result, state);
                }

                client = userClient;
            }
            else
            {
                client = new WebServerClient(serverDescription, clientId, ClientCredentialApplicator.PostParameter(clientSecret));
                state  = state ?? client.GetClientAccessToken(scopes);
            }

            return(new ClientHandlerInfo(
                       new BearerTokenHttpMessageHandler(
                           client,
                           state,
                           new HttpClientHandler {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            }),
                       state));
        }
        private string CallAPI(IAuthorizationState authorization)
        {
            var webClient = new WebClient();

            webClient.Headers["Content-Type"]            = "application/json";
            webClient.Headers["X-JavaScript-User-Agent"] = "Google APIs Explorer";
            this.Client.AuthorizeRequest(webClient, this.Authorization);
            var valueString = webClient.DownloadString("http://localhost:49810/api/values");

            return(valueString);
        }
Beispiel #38
0
 void SaveNewRefreshToken(IAuthorizationState state)
 {
     if (File.Exists(refreshTokenFile))
     {
         File.Delete(refreshTokenFile);
     }
     using (StreamWriter writer = new StreamWriter(refreshTokenFile))
     {
         writer.WriteLine(state.RefreshToken);
     }
 }
Beispiel #39
0
        public void AuthorizeRequestAsync(WebHeaderCollection requestHeaders, IAuthorizationState authorization, CancellationToken cancellationToken)
        {
            ErrorUtilities.VerifyProtocol(!authorization.AccessTokenExpirationUtc.HasValue || authorization.AccessTokenExpirationUtc >= DateTime.UtcNow || authorization.RefreshToken != null, ClientStrings.AuthorizationExpired);

            if (authorization.AccessTokenExpirationUtc.HasValue && authorization.AccessTokenExpirationUtc.Value < DateTime.UtcNow)
            {
                ErrorUtilities.VerifyProtocol(authorization.RefreshToken != null, ClientStrings.AccessTokenRefreshFailed);
                this.RefreshAuthorizationAsync(authorization, cancellationToken: cancellationToken);
            }
            AuthorizeRequest(requestHeaders, authorization.AccessToken);
        }
        /// <summary>
        /// A method that calls onto the API from the server using the code that has been retrieved using
        /// a previous oAuth call.
        /// </summary>
        /// <param name="authorization"></param>
        /// <returns></returns>
        private string CallAPI(IAuthorizationState authorization)
        {
            var webClient = new WebClient();

            webClient.Headers["Content-Type"]            = "application/json";
            webClient.Headers["X-JavaScript-User-Agent"] = "API Explorer";
            this.Client.AuthorizeRequest(webClient, this.Authorization);
            var valueString = webClient.DownloadString(API_ENDPOINT);

            return(valueString);
        }
Beispiel #41
0
        private Uri GetAuthorizationUri(IAuthorizationState authorization)
        {
            var baseUri = RequestUserAuthorization(authorization);

            var authorizationUriBuilder = new UriBuilder(baseUri)
            {
                Query = baseUri.Query.Substring(1) + "&force_login=1"
            };

            return authorizationUriBuilder.Uri;
        }
Beispiel #42
0
        private string CallAPI(IAuthorizationState authorization)
        {
            var webClient = new WebClient();

            webClient.Headers["Content-Type"]            = "application/json";
            webClient.Headers["X-JavaScript-User-Agent"] = "Demo";
            this.Client.AuthorizeRequest(webClient, this.Authorization);
            var valueString = webClient.DownloadString(HostBaseUrl + "/api/values/get");

            return(valueString);
        }
        private Uri GetAuthorizationUri(IAuthorizationState authorization)
        {
            var baseUri = RequestUserAuthorization(authorization);

            var authorizationUriBuilder = new UriBuilder(baseUri)
            {
                Query = baseUri.Query.Substring(1) + "&force_login=1"
            };

            return(authorizationUriBuilder.Uri);
        }
 public void SetUp()
 {
     client = new AssertionFlowClient(
         GoogleAuthenticationServer.Description, new X509Certificate2(@"test-key.p12", "notasecret", X509KeyStorageFlags.Exportable)) {
         Scope = Scope,
         ServiceAccountId = ServiceAccountId
     };
     state = new AuthorizationState(client.Scope.Split(' '));
     channel = new MockChannel() {
         ResponseMessage = new AssertionFlowMessage(GoogleAuthenticationServer.Description)
     };
 }
Beispiel #45
0
    /// <summary>
    /// Retrieve an IAuthenticator instance using the provided state.
    /// </summary>
    /// <param name="credentials">OAuth 2.0 credentials to use.</param>
    /// <returns>Authenticator using the provided OAuth 2.0 credentials</returns>
    public static dynamic GetAuthenticatorFromState(IAuthorizationState credentials)
    {
        var provider =
            new StoredStateClient(
                GoogleAuthenticationServer.Description, Common.ClientID, Common.ClientSecret,
                credentials);
        var auth =
            new OAuth2Authenticator <StoredStateClient>(provider, StoredStateClient.GetState);

        auth.LoadAccessToken();
        return(auth);
    }
        public ActionResult oauth2callback()
        {
            WebServerClient consumer = new WebServerClient(server, clientID, clientSecret);

            consumer.ClientCredentialApplicator =
                ClientCredentialApplicator.PostParameter(clientSecret);
            IAuthorizationState grantedAccess = consumer.ProcessUserAuthorization(null);

            string accessToken = grantedAccess.AccessToken;

            return(Content(accessToken));
        }
Beispiel #47
0
        /// <summary>
        /// Convert an authoriztion token for an access token.
        /// </summary>
        /// <param name="Request">The http request</param>
        /// <returns>The granted access token</returns>
        public static IAuthorizationState ConvertToken(HttpRequest Request)
        {
            WebServerClient consumer = new WebServerClient(Description(), MFBFacebook.FACEBOOK_API_KEY, MFBFacebook.FACEBOOK_SECRET);

            consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(MFBFacebook.FACEBOOK_SECRET);
            IAuthorizationState grantedAccess = consumer.ProcessUserAuthorization(new HttpRequestWrapper(Request));

            // Exchange for a longer lived token
            ExchangeToken(grantedAccess);

            return(grantedAccess);
        }
Beispiel #48
0
		/// <summary>
		/// Adds the OAuth authorization token to an outgoing HTTP request, renewing a
		/// (nearly) expired access token if necessary.
		/// </summary>
		/// <param name="request">The request for protected resources from the service provider.</param>
		/// <param name="authorization">The authorization for this request previously obtained via OAuth.</param>
		public void AuthorizeRequest(HttpWebRequest request, IAuthorizationState authorization) {
			Requires.NotNull(request, "request");
			Requires.NotNull(authorization, "authorization");
			Requires.True(!string.IsNullOrEmpty(authorization.AccessToken), "authorization");
			ErrorUtilities.VerifyProtocol(!authorization.AccessTokenExpirationUtc.HasValue || authorization.AccessTokenExpirationUtc < DateTime.UtcNow || authorization.RefreshToken != null, OAuth2Strings.AuthorizationExpired);

			if (authorization.AccessTokenExpirationUtc.HasValue && authorization.AccessTokenExpirationUtc.Value < DateTime.UtcNow) {
				ErrorUtilities.VerifyProtocol(authorization.RefreshToken != null, OAuth2Strings.AccessTokenRefreshFailed);
				this.RefreshAuthorization(authorization);
			}

			AuthorizeRequest(request, authorization.AccessToken);
		}
Beispiel #49
0
		/// <summary>
		/// Adds the OAuth authorization token to an outgoing HTTP request, renewing a
		/// (nearly) expired access token if necessary.
		/// </summary>
		/// <param name="request">The request for protected resources from the service provider.</param>
		/// <param name="authorization">The authorization for this request previously obtained via OAuth.</param>
		public void AuthorizeRequest(HttpWebRequest request, IAuthorizationState authorization) {
			Requires.NotNull(request, "request");
			Requires.NotNull(authorization, "authorization");
			Requires.True(!string.IsNullOrEmpty(authorization.AccessToken), "authorization");
			ErrorUtilities.VerifyProtocol(!authorization.AccessTokenExpirationUtc.HasValue || authorization.AccessTokenExpirationUtc < DateTime.UtcNow || authorization.RefreshToken != null, "authorization has expired");

			if (authorization.AccessTokenExpirationUtc.HasValue && authorization.AccessTokenExpirationUtc.Value < DateTime.UtcNow) {
				ErrorUtilities.VerifyProtocol(authorization.RefreshToken != null, "Access token has expired and cannot be automatically refreshed.");
				this.RefreshAuthorization(authorization);
			}

			AuthorizeRequest(request, authorization.AccessToken);
		}
Beispiel #50
0
		/// <summary>
		/// Adds the OAuth authorization token to an outgoing HTTP request, renewing a
		/// (nearly) expired access token if necessary.
		/// </summary>
		/// <param name="request">The request for protected resources from the service provider.</param>
		/// <param name="authorization">The authorization for this request previously obtained via OAuth.</param>
		public void AuthorizeRequest(HttpWebRequest request, IAuthorizationState authorization) {
			Contract.Requires<ArgumentNullException>(request != null);
			Contract.Requires<ArgumentNullException>(authorization != null);
			Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(authorization.AccessToken));
			Contract.Requires<ProtocolException>(!authorization.AccessTokenExpirationUtc.HasValue || authorization.AccessTokenExpirationUtc < DateTime.UtcNow || authorization.RefreshToken != null);

			if (authorization.AccessTokenExpirationUtc.HasValue && authorization.AccessTokenExpirationUtc.Value < DateTime.UtcNow) {
				ErrorUtilities.VerifyProtocol(authorization.RefreshToken != null, "Access token has expired and cannot be automatically refreshed.");
				this.RefreshAuthorization(authorization);
			}

			AuthorizeRequest(request, authorization.AccessToken);
		}
Beispiel #51
0
		public async Task<IOAuth2Graph> GetGraphAsync(IAuthorizationState authState, string[] fields = null, CancellationToken cancellationToken = default(CancellationToken)) {
			if ((authState != null) && (authState.AccessToken != null)) {
				var httpClient = new HttpClient(this.CreateAuthorizingHandler(authState));
				using (var response = await httpClient.GetAsync("https://www.googleapis.com/oauth2/v1/userinfo", cancellationToken)) {
					response.EnsureSuccessStatusCode();
					using (var responseStream = await response.Content.ReadAsStreamAsync()) {
						return GoogleGraph.Deserialize(responseStream);
					}
				}
			}

			return null;
		}
Beispiel #52
0
        protected void exchangeCredentialsButton_Click(object sender, EventArgs e) {
            try {
                var client = CreateOAuth2Client();
                var scopes = (scopesTextBox.Text ?? String.Empty).Split(' ');
                authState = client.ExchangeUserCredentialForToken(usernameTextBox.Text, passwordTextBox.Text, scopes);
                UpdateFields();
            } catch (Exception ex) {
                for (; ex != null; ex = ex.InnerException) {
                    outputTextBox.Text += ex.Message + Environment.NewLine;
                }
            }

        }
Beispiel #53
0
        /// <summary>
        /// Requests authorization on a native client by using a predefined set of authorization flows.
        /// </summary>
        /// <param name="client">The client used for authentication.</param>
        /// <param name="authState">The requested authorization state.</param>
        /// <returns>The authorization code, or null if cancelled by the user.</returns>
        /// <exception cref="NotSupportedException">Thrown if no supported flow was found.</exception>
        public static string RequestNativeAuthorization(NativeApplicationClient client, IAuthorizationState authState)
        {
            // Try each available flow until we get an authorization / error.
            foreach (INativeAuthorizationFlow flow in NativeFlows)
            {
                try
                {
                    return flow.RetrieveAuthorization(client, authState);
                } 
                catch (NotSupportedException) { /* Flow unsupported on this environment */ }
            }

            throw new NotSupportedException("Found no supported native authorization flow.");
        }
Beispiel #54
0
        private static bool AccessTokenHasToBeRefreshed(IAuthorizationState authorization)
        {
            if (authorization.AccessToken == null && authorization.RefreshToken != null)
            {
                return true;
            }

            if (authorization.AccessTokenExpirationUtc != null)
            {
                TimeSpan timeToExpire = authorization.AccessTokenExpirationUtc.Value.Subtract(DateTime.UtcNow);
                return (timeToExpire.Minutes < 1);
            }
            return false;
        }
        private OAuth2Parameters CreateOAuth2Parameters(IAuthorizationState state)
        {
            var parameters = new OAuth2Parameters()
            {
                ClientId = GoogleSyncSettings.ClientIdentifier,
                ClientSecret = GoogleSyncSettings.ClientSecret,
                RedirectUri = GoogleSyncSettings.RedirectUri,
                RefreshToken = state.RefreshToken,
                Scope = GoogleSyncSettings.ContactScope + " " + GoogleSyncSettings.ContactGroupScope
            };
            OAuthUtil.RefreshAccessToken(parameters);

            return parameters;
        }
Beispiel #56
0
 /// <summary>
 /// Store OAuth 2.0 credentials in the application's database.
 /// </summary>
 /// <param name="userId">User's ID.</param>
 /// <param name="credentials">The OAuth 2.0 credentials to store.</param>
 static void StoreCredentials(String userId, IAuthorizationState credentials)
 {
     StoredCredentialsDBContext db = new StoredCredentialsDBContext();
     StoredCredentials sc = db.StoredCredentialSet.FirstOrDefault(x => x.UserId == userId);
     if (sc != null)
     {
         sc.AccessToken = credentials.AccessToken;
         sc.RefreshToken = credentials.RefreshToken;
     }
     else
     {
         db.StoredCredentialSet.Add(new StoredCredentials { UserId = userId, AccessToken = credentials.AccessToken, RefreshToken = credentials.RefreshToken });
     }
     db.SaveChanges();
 }
		/// <summary>
		/// Generates a URL that the user's browser can be directed to in order to authorize
		/// this client to access protected data at some resource server.
		/// </summary>
		/// <param name="authorization">The authorization state that is tracking this particular request.  Optional.</param>
		/// <returns>A fully-qualified URL suitable to initiate the authorization flow.</returns>
		public Uri RequestUserAuthorization(IAuthorizationState authorization) {
			Contract.Requires<ArgumentNullException>(authorization != null);
			Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientIdentifier));

			if (authorization.Callback == null) {
				authorization.Callback = new Uri("http://localhost/");
			}

			var request = new EndUserAuthorizationRequest(this.AuthorizationServer) {
				ClientIdentifier = this.ClientIdentifier,
				Callback = authorization.Callback,
			};
			request.Scope.ResetContents(authorization.Scope);

			return this.Channel.PrepareResponse(request).GetDirectUriRequest(this.Channel);
		}
        public mGoogle()
        {
            // Register the authenticator. The Client ID and secret have to be copied from the API Access
            // tab on the Google APIs Console.
            provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            provider.ClientIdentifier = "528532804655.apps.googleusercontent.com";
            provider.ClientSecret = "9QSFSAg0dE5CqC5F_Ot6MD8f";

            // Get the auth URL:
            state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            Uri authUri = provider.RequestUserAuthorization(state);

            // Request authorization from the user (by opening a browser window):
            Process.Start(authUri.ToString());
        }
		public async Task<IOAuth2Graph> GetGraphAsync(IAuthorizationState authState, string[] fields = null, CancellationToken cancellationToken = default(CancellationToken)) {
			if ((authState != null) && (authState.AccessToken != null)) {
				var httpClient = new HttpClient(this.CreateAuthorizingHandler(authState));
				string fieldsStr = (fields == null) || (fields.Length == 0) ? FacebookGraph.Fields.Defaults : string.Join(",", fields);

				using (
					var response = await httpClient.GetAsync("https://graph.Facebook.com/me?fields=" + fieldsStr, cancellationToken)) {
					response.EnsureSuccessStatusCode();
					using (var responseStream = await response.Content.ReadAsStreamAsync()) {
						return FacebookGraph.Deserialize(responseStream);
					}
				}
			}

			return null;
		}
Beispiel #60
0
		/// <summary>
		/// Generates a URL that the user's browser can be directed to in order to authorize
		/// this client to access protected data at some resource server.
		/// </summary>
		/// <param name="authorization">The authorization state that is tracking this particular request.  Optional.</param>
		/// <param name="state">The client state that should be returned with the authorization response.</param>
		/// <returns>
		/// A fully-qualified URL suitable to initiate the authorization flow.
		/// </returns>
		public Uri RequestUserAuthorization(IAuthorizationState authorization, string state = null) {
			Requires.NotNull(authorization, "authorization");
			Requires.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier));

			if (authorization.Callback == null) {
				authorization.Callback = new Uri("http://localhost/");
			}

			var request = new EndUserAuthorizationRequest(this.AuthorizationServer) {
				ClientIdentifier = this.ClientIdentifier,
				Callback = authorization.Callback,
				ClientState = state,
			};
			request.Scope.ResetContents(authorization.Scope);

			return this.Channel.PrepareResponse(request).GetDirectUriRequest(this.Channel);
		}