public void AuthorizationCodeGrant() {
			var coordinator = new OAuth2Coordinator<WebServerClient>(
				AuthorizationServerDescription,
				AuthorizationServerMock,
				new WebServerClient(AuthorizationServerDescription),
				client => {
					var authState = new AuthorizationState {
						Callback = ClientCallback,
					};
					client.PrepareRequestUserAuthorization(authState).Respond();
					var result = client.ProcessUserAuthorization();
					Assert.IsNotNullOrEmpty(result.AccessToken);
					Assert.IsNotNullOrEmpty(result.RefreshToken);
				},
				server => {
					var request = server.ReadAuthorizationRequest();
					server.ApproveAuthorizationRequest(request, ResourceOwnerUsername);
					var tokenRequest = server.ReadAccessTokenRequest();
					IAccessTokenRequest accessTokenRequest = tokenRequest;
					Assert.IsTrue(accessTokenRequest.ClientAuthenticated);
					var tokenResponse = server.PrepareAccessTokenResponse(tokenRequest);
					server.Channel.Respond(tokenResponse);
				});
			coordinator.Run();
		}
        public void CheckForValidAccessTokenTest()
        {
            int accessTokenCounter = 1;
            var state = new AuthorizationState();
            var client = new NativeApplicationClient(new Uri("http://example.com"));
            var auth = new OAuth2Authenticator<NativeApplicationClient>(
                client, (clt) =>
                { 
                    // Load a "cached" access token.
                    state.AccessToken = "token" + (accessTokenCounter++);
                    return state;
                });

            // Check that the initial state is null.
            Assert.IsNull(auth.State);

            // Check that the state was set when .LoadAccessToken() is called.
            auth.LoadAccessToken();
            Assert.AreEqual(state, auth.State);
            Assert.AreEqual("token1", auth.State.AccessToken);

            // Check that it wont be set again.
            auth.LoadAccessToken();
            Assert.AreEqual("token1", auth.State.AccessToken);

            // Check that it is set if our state gets invalid.
            state.AccessToken = null;
            auth.LoadAccessToken();
            Assert.AreEqual("token2", auth.State.AccessToken);
        }
		public void ImplicitGrant() {
			var coordinatorClient = new UserAgentClient(AuthorizationServerDescription);
			var coordinator = new OAuth2Coordinator<UserAgentClient>(
				AuthorizationServerDescription,
				AuthorizationServerMock,
				coordinatorClient,
				client => {
					var authState = new AuthorizationState {
						Callback = ClientCallback,
					};
					var request = client.PrepareRequestUserAuthorization(authState, implicitResponseType: true);
					Assert.AreEqual(EndUserAuthorizationResponseType.AccessToken, request.ResponseType);
					client.Channel.Respond(request);
					var incoming = client.Channel.ReadFromRequest();
					var result = client.ProcessUserAuthorization(authState, incoming);
					Assert.IsNotNullOrEmpty(result.AccessToken);
					Assert.IsNull(result.RefreshToken);
				},
				server => {
					var request = server.ReadAuthorizationRequest();
					IAccessTokenRequest accessTokenRequest = (EndUserAuthorizationImplicitRequest)request;
					Assert.IsFalse(accessTokenRequest.ClientAuthenticated);
					server.ApproveAuthorizationRequest(request, ResourceOwnerUsername);
				});

			coordinatorClient.ClientSecret = null; // implicit grant clients don't need a secret.
			coordinator.Run();
		}
		public async Task ImplicitGrant() {
			var coordinatorClient = new UserAgentClient(AuthorizationServerDescription);
			coordinatorClient.ClientCredentialApplicator = null; // implicit grant clients don't need a secret.
			Handle(AuthorizationServerDescription.AuthorizationEndpoint).By(
				async (req, ct) => {
					var server = new AuthorizationServer(AuthorizationServerMock);
					var request = await server.ReadAuthorizationRequestAsync(req, ct);
					Assert.That(request, Is.Not.Null);
					IAccessTokenRequest accessTokenRequest = (EndUserAuthorizationImplicitRequest)request;
					Assert.That(accessTokenRequest.ClientAuthenticated, Is.False);
					var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername);
					return await server.Channel.PrepareResponseAsync(response, ct);
				});
			{
				var client = new UserAgentClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories);
				var authState = new AuthorizationState(TestScopes) { Callback = ClientCallback, };
				var request = client.PrepareRequestUserAuthorization(authState, implicitResponseType: true);
				Assert.That(request.ResponseType, Is.EqualTo(EndUserAuthorizationResponseType.AccessToken));
				var authRequestRedirect = await client.Channel.PrepareResponseAsync(request);
				Uri authRequestResponse;
				this.HostFactories.AllowAutoRedirects = false;
				using (var httpClient = this.HostFactories.CreateHttpClient()) {
					using (var httpResponse = await httpClient.GetAsync(authRequestRedirect.Headers.Location)) {
						authRequestResponse = httpResponse.Headers.Location;
					}
				}

				var incoming =
					await client.Channel.ReadFromRequestAsync(new HttpRequestMessage(HttpMethod.Get, authRequestResponse), CancellationToken.None);
				var result = await client.ProcessUserAuthorizationAsync(authState, incoming, CancellationToken.None);
				Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
				Assert.That(result.RefreshToken, Is.Null);
			}
		}
        /// <summary>
        /// Return Analytics Service object
        /// </summary>
        /// <returns>Analytics Service object</returns>
        public static AnalyticsService GetAnalyticsService()
        {
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            provider.ClientIdentifier = Settings.ClientIdentifier;
            provider.ClientSecret = Settings.ClientSecret;

            if (string.IsNullOrWhiteSpace(provider.ClientIdentifier))
            {
                throw new Exception("Client identifier not found");
            }
            if (string.IsNullOrWhiteSpace(provider.ClientSecret))
            {
                throw new Exception("Client secret not found");
            }
            string refreshToken = Settings.RefreshToken;
            if (string.IsNullOrWhiteSpace(refreshToken))
            {
                throw new Exception("Refresh token not found");
            }

            var request = HttpContext.Current.Request;
            var authenticator = new OAuth2Authenticator<NativeApplicationClient>(provider, (arg) =>
            {
                IAuthorizationState state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/analytics.readonly" });
                state.Callback = new Uri(string.Format("{0}://{1}{2}/GoogleAnalytics/Callback", request.Url.Scheme, request.Url.Host, request.Url.Port == 80 ? string.Empty : ":" + request.Url.Port));
                state.RefreshToken = refreshToken;
                var result = arg.RefreshToken(state);
                return state;
            });

            return new AnalyticsService(authenticator);
        }
 public NamedAuthorizationState(Guid guid, string name, AuthorizationState authorizationState)
 {
     Guid = guid;
     Name = name;
     AuthorizationState = authorizationState;
     IsHistorical = true;
 }
		public void AuthorizationCodeGrant() {
			var coordinator = new OAuth2Coordinator<UserAgentClient>(
				AuthorizationServerDescription,
				AuthorizationServerMock,
				new UserAgentClient(AuthorizationServerDescription),
				client => {
					var authState = new AuthorizationState(TestScopes) {
						Callback = ClientCallback,
					};
					var request = client.PrepareRequestUserAuthorization(authState);
					Assert.AreEqual(EndUserAuthorizationResponseType.AuthorizationCode, request.ResponseType);
					client.Channel.Respond(request);
					var incoming = client.Channel.ReadFromRequest();
					var result = client.ProcessUserAuthorization(authState, incoming);
					Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
					Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty);
				},
				server => {
					var request = server.ReadAuthorizationRequest();
					Assert.That(request, Is.Not.Null);
					server.ApproveAuthorizationRequest(request, ResourceOwnerUsername);
					server.HandleTokenRequest().Respond();
				});
			coordinator.Run();
		}
Example #8
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);
                }
            }
        }
		public void DecodeRefreshToken() {
			var refreshTokenSource = new TaskCompletionSource<string>();
			var coordinator = new OAuth2Coordinator<WebServerClient>(
				AuthorizationServerDescription,
				AuthorizationServerMock,
				new WebServerClient(AuthorizationServerDescription),
				client => {
					try {
						var authState = new AuthorizationState(TestScopes) {
							Callback = ClientCallback,
						};
						client.PrepareRequestUserAuthorization(authState).Respond();
						var result = client.ProcessUserAuthorization();
						Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
						Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty);
						refreshTokenSource.SetResult(result.RefreshToken);
					} catch {
						refreshTokenSource.TrySetCanceled();
					}
				},
				server => {
					var request = server.ReadAuthorizationRequest();
					Assert.That(request, Is.Not.Null);
					server.ApproveAuthorizationRequest(request, ResourceOwnerUsername);
					server.HandleTokenRequest().Respond();
					var authorization = server.DecodeRefreshToken(refreshTokenSource.Task.Result);
					Assert.That(authorization, Is.Not.Null);
					Assert.That(authorization.User, Is.EqualTo(ResourceOwnerUsername));
				});
			coordinator.Run();
		}
        /// <summary>
        /// Requests an access token using a partially .initialized request message.
        /// </summary>
        /// <param name="request">The request message.</param>
        /// <param name="scopes">The scopes requested by the client.</param>
        /// <returns>The result of the request.</returns>
        private IAuthorizationState RequestAccessToken(ScopedAccessTokenRequest request, IEnumerable <string> scopes = null)
        {
            Requires.NotNull(request, "request");

            var authorizationState = new AuthorizationState(scopes);

            request.ClientIdentifier = this.ClientIdentifier;
            this.ApplyClientCredential(request);
            request.Scope.UnionWith(authorizationState.Scope);

            var response = this.Channel.Request(request);
            var success  = response as AccessTokenSuccessResponse;
            var failure  = response as AccessTokenFailedResponse;

            ErrorUtilities.VerifyProtocol(success != null || failure != null, MessagingStrings.UnexpectedMessageReceivedOfMany);
            if (success != null)
            {
                authorizationState.Scope.Clear();                 // clear the scope we requested so that the response will repopulate it.
                UpdateAuthorizationWithResponse(authorizationState, success);
            }
            else                 // failure
            {
                Logger.OAuth.Info("Credentials rejected by the Authorization Server.");
                authorizationState.Delete();
            }

            return(authorizationState);
        }
Example #11
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="scope">The scope of authorized access requested.</param>
		/// <param name="state">The client state that should be returned with the authorization response.</param>
		/// <param name="returnTo">The URL that the authorization response should be sent to via a user-agent redirect.</param>
		/// <returns>
		/// A fully-qualified URL suitable to initiate the authorization flow.
		/// </returns>
		public Uri RequestUserAuthorization(IEnumerable<string> scope = null, string state = null, Uri returnTo = null) {
			var authorization = new AuthorizationState(scope) {
				Callback = returnTo,
			};

			return this.RequestUserAuthorization(authorization);
		}
		/// <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;
		}
Example #13
0
		/// <summary>
		/// Prepares a request for user authorization from an authorization server.
		/// </summary>
		/// <param name="scopes">The scope of authorized access requested.</param>
		/// <param name="state">The state of the client that should be sent back with the authorization response.</param>
    /// <param name="returnTo">The URL the authorization server should redirect the browser (typically on this site) to when the authorization is completed.  If null, the current request's URL will be used.</param>
		/// <returns>The authorization request.</returns>
		public OutgoingWebResponse PrepareRequestUserAuthorization(IEnumerable<string> scopes = null, string state = null, Uri returnTo = null)
		{
		  var authorizationState = new AuthorizationState(scopes) {
        Callback = returnTo,
      };
			return this.PrepareRequestUserAuthorization(authorizationState, state);
		}
 /// <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,
     AuthorizationState existingState = null
     )
 {
     return Create(authBaseUri, clientId, clientSecret, scopes, existingState, false, null, null);
 }
Example #15
0
        /// <summary>
        /// Prepares a request for user authorization from an authorization server.
        /// </summary>
        /// <param name="scopes">The scope of authorized access requested.</param>
        /// <param name="returnTo">The URL the authorization server should redirect the browser (typically on this site) to when the authorization is completed.  If null, the current request's URL will be used.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The authorization request.
        /// </returns>
        public Task <HttpResponseMessage> PrepareRequestUserAuthorizationAsync(IEnumerable <string> scopes = null, Uri returnTo = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var authorizationState = new AuthorizationState(scopes)
            {
                Callback = returnTo,
            };

            return(this.PrepareRequestUserAuthorizationAsync(authorizationState, cancellationToken));
        }
Example #16
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="scope">The scope of authorized access requested.</param>
        /// <param name="state">The client state that should be returned with the authorization response.</param>
        /// <param name="returnTo">The URL that the authorization response should be sent to via a user-agent redirect.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// A fully-qualified URL suitable to initiate the authorization flow.
        /// </returns>
        public Task <Uri> RequestUserAuthorizationAsync(IEnumerable <string> scope = null, string state = null, Uri returnTo = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var authorization = new AuthorizationState(scope)
            {
                Callback = returnTo,
            };

            return(this.RequestUserAuthorizationAsync(authorization, state: state, cancellationToken: cancellationToken));
        }
Example #17
0
        /// <summary>
        /// Prepares a request for user authorization from an authorization server.
        /// </summary>
        /// <param name="scopes">The scope of authorized access requested.</param>
        /// <param name="returnTo">The URL the authorization server should redirect the browser (typically on this site) to when the authorization is completed.  If null, the current request's URL will be used.</param>
        /// <returns>The authorization request.</returns>
        public OutgoingWebResponse PrepareRequestUserAuthorization(IEnumerable <string> scopes = null, Uri returnTo = null)
        {
            var authorizationState = new AuthorizationState(scopes)
            {
                Callback = returnTo,
            };

            return(this.PrepareRequestUserAuthorization(authorizationState));
        }
 public NamedAuthorizationState(Guid guid, string name, AuthorizationState authorizationState, bool shouldRefresh, Uri url)
 {
     Guid = guid;
     Name = name;
     AuthorizationState = authorizationState;
     ShouldRefresh = shouldRefresh;
     Url = url;
     IsHistorical = true;
 }
Example #19
0
        /// <summary>
        /// Prepares a request for user authorization from an authorization server.
        /// </summary>
        /// <param name="scope">The scope of authorized access requested.</param>
        /// <param name="returnTo">The URL the authorization server should redirect the browser (typically on this site) to when the authorization is completed.  If null, the current request's URL will be used.</param>
        public void RequestUserAuthorization(IEnumerable <string> scope = null, Uri returnTo = null)
        {
            var authorizationState = new AuthorizationState(scope)
            {
                Callback = returnTo,
            };

            this.PrepareRequestUserAuthorization(authorizationState).Send();
        }
        /// <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="scope">The scope of authorized access requested.</param>
        /// <param name="state">The client state that should be returned with the authorization response.</param>
        /// <param name="returnTo">The URL that the authorization response should be sent to via a user-agent redirect.</param>
        /// <returns>
        /// A fully-qualified URL suitable to initiate the authorization flow.
        /// </returns>
        public Uri RequestUserAuthorization(IEnumerable <string> scope = null, string state = null, Uri returnTo = null)
        {
            var authorization = new AuthorizationState(scope)
            {
                Callback = returnTo,
            };

            return(this.RequestUserAuthorization(authorization, state: state));
        }
        public void DelegateTest()
        {
            var state = new AuthorizationState() { AccessToken = "Test" };
            var client = new NativeApplicationClient(new Uri("http://example.com"));
            var auth = new OAuth2Authenticator<NativeApplicationClient>(client, (clt) => state);

            // Check that the state was set.
            auth.LoadAccessToken();
            Assert.AreEqual(state, auth.State);
        }
Example #22
0
        /// <summary>
        /// Processes the authorization response from an authorization server, if available.
        /// </summary>
        /// <param name="request">The incoming HTTP request that may carry an authorization response.</param>
        /// <returns>The authorization state that contains the details of the authorization.</returns>
        public IAuthorizationState ProcessUserAuthorization(HttpRequestBase request = null)
        {
            Requires.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier), Strings.RequiredPropertyNotYetPreset, "ClientIdentifier");
            Requires.ValidState(this.ClientCredentialApplicator != null, Strings.RequiredPropertyNotYetPreset, "ClientCredentialApplicator");

            if (request == null)
            {
                request = this.Channel.GetRequestFromContext();
            }

            IMessageWithClientState response;

            if (this.Channel.TryReadFromRequest <IMessageWithClientState>(request, out response))
            {
                Uri callback = MessagingUtilities.StripMessagePartsFromQueryString(request.GetPublicFacingUrl(), this.Channel.MessageDescriptions.Get(response));
                IAuthorizationState authorizationState;
                if (this.AuthorizationTracker != null)
                {
                    authorizationState = this.AuthorizationTracker.GetAuthorizationState(callback, response.ClientState);
                    ErrorUtilities.VerifyProtocol(authorizationState != null, ClientStrings.AuthorizationResponseUnexpectedMismatch);
                }
                else
                {
                    var context = this.Channel.GetHttpContext();
                    if (context.Session != null)
                    {
                        ErrorUtilities.VerifyProtocol(string.Equals(response.ClientState, context.Session.SessionID, StringComparison.Ordinal), ClientStrings.AuthorizationResponseUnexpectedMismatch);
                    }
                    else
                    {
                        Logger.OAuth.WarnFormat("No request context discovered, so no client state parameter could be checked to mitigate XSRF attacks.");
                    }

                    authorizationState = new AuthorizationState {
                        Callback = callback
                    };
                }
                var success = response as EndUserAuthorizationSuccessAuthCodeResponse;
                var failure = response as EndUserAuthorizationFailedResponse;
                ErrorUtilities.VerifyProtocol(success != null || failure != null, MessagingStrings.UnexpectedMessageReceivedOfMany);
                if (success != null)
                {
                    this.UpdateAuthorizationWithResponse(authorizationState, success);
                }
                else                     // failure
                {
                    Logger.OAuth.Info("User refused to grant the requested authorization at the Authorization Server.");
                    authorizationState.Delete();
                }

                return(authorizationState);
            }

            return(null);
        }
Example #23
0
 public HomeController()
 {
     var a = Guid.NewGuid().ToString("N");
     var authServer = new AuthorizationServerDescription()
     {
         AuthorizationEndpoint = new Uri("http://localhost:4251/OAuth/Authorize"),
         TokenEndpoint = new Uri("http://localhost:4251/OAuth/Token"),
     };
     Client = new UserAgentClient(authServer, "samplewebapiconsumer", "samplesecret");
     Authorization = new AuthorizationState { Callback = new Uri("http://localhost:4494/") };
 }
        public static GoogleAuthenticator GetAuthenticator(string authorizationCode)
        {
            var client = new NativeApplicationClient(GoogleAuthenticationServer.Description, _clientId, _clientSecret);
            IAuthorizationState state = new AuthorizationState() { Callback = new Uri(_redirectUri) };
            state = client.ProcessUserAuthorization(authorizationCode, state);

            var auth = new OAuth2Authenticator<NativeApplicationClient>(client, (c) => state);
            auth.LoadAccessToken();

            return new GoogleAuthenticator(auth);
        }
        public async Task<ActionResult> Index()
        {
            ViewBag.AccessToken = Request.Form["AccessToken"] ?? "";
            ViewBag.RefreshToken = Request.Form["RefreshToken"] ?? "";
            ViewBag.Action = "";
            ViewBag.ApiResponse = "";

            InitializeWebServerClient();
            var accessToken = Request.Form["AccessToken"];
            if (string.IsNullOrEmpty(accessToken))
            {
                var authorizationState = _webServerClient.ProcessUserAuthorization(Request);
                if (authorizationState != null)
                {
                    ViewBag.AccessToken = authorizationState.AccessToken;
                    ViewBag.RefreshToken = authorizationState.RefreshToken;
                    ViewBag.Action = Request.Path;
                }
            }

            if (!string.IsNullOrEmpty(Request.Form.Get("submit.Authorize")))
            {
                var userAuthorization = _webServerClient.PrepareRequestUserAuthorization(new[] { "bio", "notes" });
                userAuthorization.Send(HttpContext);
                Response.End();
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.Refresh")))
            {
                var state = new AuthorizationState
                {
                    AccessToken = Request.Form["AccessToken"],
                    RefreshToken = Request.Form["RefreshToken"]
                };
                if (_webServerClient.RefreshAuthorization(state))
                {
                    ViewBag.AccessToken = state.AccessToken;
                    ViewBag.RefreshToken = state.RefreshToken;
                }
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.CallApi")))
            {
                Raml.RamlApi api = new Raml.RamlApi("http://localhost:11625");
                api.OAuthAccessToken = accessToken;

                //api.AddDefaultRequestHeader("Authorization", "Bearer " + accessToken);

                var response = await api.ApiMe.Get();
                var body = await response.RawContent.ReadAsStringAsync();
                                
                ViewBag.ApiResponse = body;
            }

            return View();
        }
        public void ApplyAuthenticationToRequestTest()
        {
            var request = (HttpWebRequest)WebRequest.Create("http://example.com");
            var state = new AuthorizationState() { AccessToken = "Test" };
            var client = new NativeApplicationClient(new Uri("http://example.com"));
            var auth = new OAuth2Authenticator<NativeApplicationClient>(client, (clt) => state);

            // Confirm that the request header gets modified.
            auth.ApplyAuthenticationToRequest(request);
            Assert.AreEqual(1, request.Headers.Count);
        }
Example #27
0
 /// <summary>
 /// The CreateState function will generate a state that can be
 /// used to initialize the PlusWrapper.
 /// </summary>
 /// <param name="accessToken">An access token string from an
 /// OAuth2 flow.</param>
 /// <param name="refreshToken">A refresh token string from an
 /// OAuth2 flow.</param>
 /// <param name="issued">A DateTime object representing the time
 /// that the token was issued.</param>
 /// <param name="expires">A DateTime object indicating when the
 /// token expires.</param>
 /// <returns></returns>
 public static IAuthorizationState CreateState(
     string accessToken, string refreshToken, DateTime issued,
     DateTime expires)
 {
     IAuthorizationState state = new AuthorizationState();
     state.AccessToken = accessToken;
     state.RefreshToken = refreshToken;
     state.AccessTokenIssueDateUtc = issued;
     state.AccessTokenExpirationUtc = expires;
     return state;
 }
Example #28
0
        private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            // Get the auth URL:
            IAuthorizationState state = new AuthorizationState(new[] { DriveService.Scopes.Drive.GetStringValue() });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            if (!String.IsNullOrWhiteSpace(RefreshToken)) {
                state.RefreshToken = RefreshToken;

                if (arg.RefreshToken(state))
                    return state;
            }
            return state;
        }
Example #29
0
        /// <summary>
        /// Requests authorization on a native client by using a predefined set of authorization flows.
        /// </summary>
        /// <param name="client">The client used for authorization.</param>
        /// <param name="scopes">The requested set of scopes.</param>
        /// <returns>The authorized state.</returns>
        /// <exception cref="AuthenticationException">Thrown if the request was cancelled by the user.</exception>
        public static IAuthorizationState RequestNativeAuthorization(NativeApplicationClient client,
                                                                     params string[] scopes)
        {
            IAuthorizationState state = new AuthorizationState(scopes);
            string authCode = RequestNativeAuthorization(client, state);

            if (string.IsNullOrEmpty(authCode))
            {
                throw new AuthenticationException("The authentication request was cancelled by the user.");
            }

            return client.ProcessUserAuthorization(authCode, state);
        }
Example #30
0
 private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
 {
     // Get the auth URL:
     IAuthorizationState state = new AuthorizationState(new[] { TasksService.Scopes.Tasks.GetStringValue() });
     state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
     Uri authUri = arg.RequestUserAuthorization(state);
     // Request authorization from the user (by opening a browser window):
     Process.Start(authUri.ToString());
     Console.Write("  Authorization Code: ");
     string authCode = Console.ReadLine();
     Console.WriteLine();
     // Retrieve the access token by using the authorization code:
     return arg.ProcessUserAuthorization(authCode, state);
 }
Example #31
0
        public HomeController()
        {
            var authServer = new AuthorizationServerDescription
                {
                    AuthorizationEndpoint = new Uri(AuthorizationEndpoint),
                    TokenEndpoint = new Uri(TokenEndpoint),
                };

            Client = new UserAgentClient(authServer, ClientId, ClientSecret);
            Authorization = new AuthorizationState
                {
                    Callback = new Uri(AuthorizationCallback)
                };
        }
Example #32
0
        public ActionResult Index()
        {
            ViewBag.AccessToken = Request.Form["AccessToken"] ?? "";
            ViewBag.RefreshToken = Request.Form["RefreshToken"] ?? "";
            ViewBag.Action = "";
            ViewBag.ApiResponse = "";

            InitializeWebServerClient();
            var accessToken = Request.Form["AccessToken"];
            if (string.IsNullOrEmpty(accessToken))
            {
                var authorizationState = _webServerClient.ProcessUserAuthorization(Request);
                if (authorizationState != null)
                {
                    ViewBag.AccessToken = authorizationState.AccessToken;
                    ViewBag.RefreshToken = authorizationState.RefreshToken;
                    ViewBag.Action = Request.Path;
                }
            }

            if (!string.IsNullOrEmpty(Request.Form.Get("submit.Authorize")))
            {
                var userAuthorization = _webServerClient.PrepareRequestUserAuthorization(new[] { "bio", "notes" });
                userAuthorization.Send(HttpContext);
                Response.End();
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.Refresh")))
            {
                var state = new AuthorizationState
                {
                    AccessToken = Request.Form["AccessToken"],
                    RefreshToken = Request.Form["RefreshToken"]
                };
                if (_webServerClient.RefreshAuthorization(state))
                {
                    ViewBag.AccessToken = state.AccessToken;
                    ViewBag.RefreshToken = state.RefreshToken;
                }
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.CallApi")))
            {
                var resourceServerUri = new Uri(Paths.ResourceServerBaseAddress);
                var client = new HttpClient(_webServerClient.CreateAuthorizingHandler(accessToken));
                var body = client.GetStringAsync(new Uri(resourceServerUri, Paths.MePath)).Result;
                ViewBag.ApiResponse = body;
            }

            return View();
        }
        public static GoogleAuthenticator RefreshAuthenticator(string refreshToken)
        {
            var state = new AuthorizationState(_scopes)
            {
                RefreshToken = refreshToken
            };

            var client = new NativeApplicationClient(GoogleAuthenticationServer.Description, _clientId, _clientSecret);
            bool result = client.RefreshToken(state);

            var auth = new OAuth2Authenticator<NativeApplicationClient>(client, (c) => state);
            auth.LoadAccessToken();

            return new GoogleAuthenticator(auth);
        }
        /// <summary>
        /// Initializes the request for authorization
        /// </summary>
        /// <returns></returns>
        private ActionResult InitAuth()
        {
            var state = new AuthorizationState();

            var uri = Request.Url.AbsoluteUri;
            uri = RemoveQueryStringFromUri(uri);
            state.Callback = new Uri(uri);

            //In the scope, please add only a single element, which is the Transaction amount, else the request will be rejected.
            state.Scope.Add("15");

            var r = client.PrepareRequestUserAuthorization(state);
            return r.AsActionResult();

        }
        public static string GetAuthorizationUrl(string emailAddress)
        {
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, _clientId, _clientSecret);
            IAuthorizationState authorizationState = new AuthorizationState(_scopes);
            authorizationState.Callback = new Uri(_redirectUri);

            UriBuilder builder = new UriBuilder(provider.RequestUserAuthorization(authorizationState));
            NameValueCollection queryParameters = HttpUtility.ParseQueryString(builder.Query);

            queryParameters.Set("access_type", "offline");
            queryParameters.Set("approval_prompt", "force");
            queryParameters.Set("user_id", emailAddress);

            builder.Query = queryParameters.ToString();
            return builder.Uri.ToString();
        }
        private ActionResult InitAuth()
        {
            var state = new AuthorizationState();
            if (Request.Url != null)
            {
                var uri = Request.Url.AbsoluteUri;
                uri = RemoveQueryStringFromUri(uri);
                state.Callback = new Uri(uri);
            }

            state.Scope.Add("https://www.googleapis.com/auth/userinfo.profile");
            state.Scope.Add("https://www.googleapis.com/auth/userinfo.email");
            state.Scope.Add("https://www.googleapis.com/auth/calendar");

            var outgoingWebResponse = GoogleClient.PrepareRequestUserAuthorization(state);
            return outgoingWebResponse.AsActionResult();
        }
Example #37
0
        /// <summary>
        /// Processes the authorization response from an authorization server, if available.
        /// </summary>
        /// <param name="request">The incoming HTTP request that may carry an authorization response.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The authorization state that contains the details of the authorization.</returns>
        public async Task <IAuthorizationState> ProcessUserAuthorizationAsync(HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken))
        {
            Requires.NotNull(request, "request");
            RequiresEx.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier), Strings.RequiredPropertyNotYetPreset, "ClientIdentifier");
            RequiresEx.ValidState(this.ClientCredentialApplicator != null, Strings.RequiredPropertyNotYetPreset, "ClientCredentialApplicator");

            var response = await this.Channel.TryReadFromRequestAsync <IMessageWithClientState>(request, cancellationToken);

            if (response != null)
            {
                Uri callback = request.RequestUri.StripMessagePartsFromQueryString(this.Channel.MessageDescriptions.Get(response));
                IAuthorizationState authorizationState;
                if (this.AuthorizationTracker != null)
                {
                    authorizationState = this.AuthorizationTracker.GetAuthorizationState(callback, response.ClientState);
                    ErrorUtilities.VerifyProtocol(authorizationState != null, ClientStrings.AuthorizationResponseUnexpectedMismatch);
                }
                else
                {
                    var xsrfCookieValue = (from cookieHeader in request.Headers.GetCookies()
                                           from cookie in cookieHeader.Cookies
                                           where cookie.Name == XsrfCookieName
                                           select cookie.Value).FirstOrDefault();
                    ErrorUtilities.VerifyProtocol(xsrfCookieValue != null && string.Equals(response.ClientState, xsrfCookieValue, StringComparison.Ordinal), ClientStrings.AuthorizationResponseUnexpectedMismatch);
                    authorizationState = new AuthorizationState {
                        Callback = callback
                    };
                }
                var success = response as EndUserAuthorizationSuccessAuthCodeResponse;
                var failure = response as EndUserAuthorizationFailedResponse;
                ErrorUtilities.VerifyProtocol(success != null || failure != null, MessagingStrings.UnexpectedMessageReceivedOfMany);
                if (success != null)
                {
                    await this.UpdateAuthorizationWithResponseAsync(authorizationState, success, cancellationToken);
                }
                else                     // failure
                {
                    Logger.OAuth.Info("User refused to grant the requested authorization at the Authorization Server.");
                    authorizationState.Delete();
                }

                return(authorizationState);
            }

            return(null);
        }
        /// <summary>
        /// Uses the provided authorization code to create an authorization state.
        /// </summary>
        /// <param name="authCode">The authorization code for getting an access token.</param>
        /// <param name="authorizationState">The authorization.  Optional.</param>
        /// <returns>The granted authorization, or <c>null</c> if the authorization was null or rejected.</returns>
        public IAuthorizationState ProcessUserAuthorization(
            string authCode,
            IAuthorizationState authorizationState)
        {
            if (authorizationState == null)
            {
                authorizationState = new AuthorizationState(null);
                authorizationState.Callback = new Uri(OutOfBandCallbackUrl);
            }

            // Build a generic URL containing the auth code.
            // This is done here as we cannot modify the DotNetOpenAuth library
            // and the underlying method only allows parsing an URL as a method
            // of retrieving the AuthorizationState.
            string url = "http://example.com/?code=" + authCode;
            return ProcessUserAuthorization(new Uri(url), authorizationState);
        }
Example #39
0
        /// <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>
        /// <param name="cancellationToken">The cancellation token.</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 async Task <IAuthorizationState> ProcessUserAuthorizationAsync(Uri actualRedirectUrl, IAuthorizationState authorizationState = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            Requires.NotNull(actualRedirectUrl, "actualRedirectUrl");

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

            var carrier = new HttpRequestMessage(HttpMethod.Get, actualRedirectUrl);
            IDirectedProtocolMessage response = await this.Channel.ReadFromRequestAsync(carrier, cancellationToken);

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

            return(await this.ProcessUserAuthorizationAsync(authorizationState, response, cancellationToken));
        }
        /// <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)
        {
            Requires.NotNull(actualRedirectUrl, "actualRedirectUrl");

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

            var carrier = new HttpRequestInfo("GET", actualRedirectUrl);
            IDirectedProtocolMessage response = this.Channel.ReadFromRequest(carrier);

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

            return(this.ProcessUserAuthorization(authorizationState, response));
        }
        /// <summary>
        /// Gets an access token that may be used for only a subset of the scope for which a given
        /// refresh token is authorized.
        /// </summary>
        /// <param name="refreshToken">The refresh token.</param>
        /// <param name="scope">The scope subset desired in the access token.</param>
        /// <returns>A description of the obtained access token, and possibly a new refresh token.</returns>
        /// <remarks>
        /// If the return value includes a new refresh token, the old refresh token should be discarded and
        /// replaced with the new one.
        /// </remarks>
        public IAuthorizationState GetScopedAccessToken(string refreshToken, HashSet <string> scope)
        {
            Requires.NotNullOrEmpty(refreshToken, "refreshToken");
            Requires.NotNull(scope, "scope");

            var request = new AccessTokenRefreshRequestC(this.AuthorizationServer)
            {
                ClientIdentifier = this.ClientIdentifier,
                RefreshToken     = refreshToken,
            };

            this.ApplyClientCredential(request);

            var response      = this.Channel.Request <AccessTokenSuccessResponse>(request);
            var authorization = new AuthorizationState();

            UpdateAuthorizationWithResponse(authorization, response);

            return(authorization);
        }
Example #42
0
        /// <summary>
        /// Requests an access token using a partially .initialized request message.
        /// </summary>
        /// <param name="request">The request message.</param>
        /// <param name="scopes">The scopes requested by the client.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The result of the request.
        /// </returns>
        private async Task <IAuthorizationState> RequestAccessTokenAsync(IDirectedProtocolMessage request, IEnumerable <string> scopes, CancellationToken cancellationToken)
        {
            Requires.NotNull(request, "request");

            var authorizationState = new AuthorizationState(scopes);

            // Process client credential and scopes if supported by request message.
            var accessTokenRequest = request as IAccessTokenRequest;

            if (accessTokenRequest != null)
            {
                var authRequest = request as AuthenticatedClientRequestBase;
                if (authRequest != null)
                {
                    authRequest.ClientIdentifier = this.ClientIdentifier;
                }
                this.ApplyClientCredential(accessTokenRequest);
                accessTokenRequest.Scope.UnionWith(authorizationState.Scope);
            }

            var response = await this.Channel.RequestAsync(request, cancellationToken);

            var success = response as AccessTokenSuccessResponse;
            var failure = response as AccessTokenFailedResponse;

            ErrorUtilities.VerifyProtocol(success != null || failure != null, MessagingStrings.UnexpectedMessageReceivedOfMany);
            if (success != null)
            {
                authorizationState.Scope.Clear(); // clear the scope we requested so that the response will repopulate it.
                UpdateAuthorizationWithResponse(authorizationState, success);
            }
            else
            { // failure
                Logger.OAuth.Info("Credentials rejected by the Authorization Server.");
                authorizationState.Delete();
            }

            return(authorizationState);
        }