private static IAuthorizationState GetAccessToken(string refresh) { var authorizationServer = new AuthorizationServerDescription { //AuthorizationEndpoint = new Uri(AUTHORIZATION_ENDPOINT), TokenEndpoint = new Uri(TOKEN_ENDPOINT), ProtocolVersion = ProtocolVersion.V20, }; // get a reference to the auth server var client = new UserAgentClient(authorizationServer, CLIENT_ID, CLIENT_SECRET); // now get a token IAuthorizationState ostate; if (refresh == null) { ostate = client.ExchangeUserCredentialForToken(TEST_USERNAME, TEST_PASSWORD, new[] { API_ENDPOINT }); } else { // we had previously authenticated so we can use the token rather than the credentials to get a new access token ostate = new AuthorizationState(new[] { API_ENDPOINT }); ostate.RefreshToken = refresh; client.RefreshAuthorization(ostate); } // return result return(ostate); }
public void ImplicitGrant() { var coordinatorClient = new UserAgentClient(AuthorizationServerDescription); var coordinator = new OAuth2Coordinator <UserAgentClient>( AuthorizationServerDescription, AuthorizationServerMock, coordinatorClient, client => { var authState = new AuthorizationState(TestScopes) { Callback = ClientCallback, }; var request = client.PrepareRequestUserAuthorization(authState, implicitResponseType: true); Assert.That(request.ResponseType, Is.EqualTo(EndUserAuthorizationResponseType.AccessToken)); 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.Null); }, server => { var request = server.ReadAuthorizationRequest(); Assert.That(request, Is.Not.Null); IAccessTokenRequest accessTokenRequest = (EndUserAuthorizationImplicitRequest)request; Assert.That(accessTokenRequest.ClientAuthenticated, Is.False); server.ApproveAuthorizationRequest(request, ResourceOwnerUsername); }); coordinatorClient.ClientCredentialApplicator = null; // implicit grant clients don't need a secret. coordinator.Run(); }
public ExactOnlineConnection(string clientId, string clientSecret, string redirectUri, string endPoint, IDropboxUserToken dropboxUserToken) { this.dropboxUserToken = dropboxUserToken; miscellaneousDocumentType = 55; generalCategory = Guid.Parse("3b6d3833-b31b-423d-bc3c-39c62b8f2b12"); //Guid.Parse(clientId); this.endPoint = endPoint; authorization = new AuthorizationState { Callback = new Uri(redirectUri) }; var token = dropboxUserToken.TryRetrieveTokenFromDatabase(HardcodedUser.Id); authorization.AccessToken = token.ExactAccessToken; authorization.AccessTokenExpirationUtc = token.ExactAccessTokenExpiration; exactClient = IsAccessTokenValid() ? new ExactOnlineClient(endPoint, GetAccessToken) : exactClient; var serverDescription = new AuthorizationServerDescription { AuthorizationEndpoint = new Uri(string.Format("{0}/api/oauth2/auth", endPoint)), TokenEndpoint = new Uri(string.Format("{0}/api/oauth2/token", endPoint)) }; oAuthClient = new UserAgentClient(serverDescription, clientId, clientSecret); oAuthClient.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(clientSecret); }
internal Authorize2(UserAgentClient client) { Contract.Requires(client != null, "client"); this.InitializeComponent(); this.clientAuthorizationView.Client = client; }
internal Authorize2(UserAgentClient client) { Requires.NotNull(client, "client"); this.InitializeComponent(); this.clientAuthorizationView.Client = client; }
private static void Main() { // DotNetOpenAuth only issues access tokens when the client uses an HTTPS connection. As we will most // likely run the server on our local development machine with only a self-signed SSL certificate, setting up // connection to the server will fail as the SSL certificate is considered invalid by the .NET framework. // To circumvent this, we add the line below that will consider all SSL certificates as valid, including // self-signed certificaties. Note: this should only be used for testing purposes. ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; // The description of the authorization server to which we will be connecting. The most important component // is the token endpoint, which is the URL at which the server listens for token requests var authorizationServerDescription = new AuthorizationServerDescription { TokenEndpoint = new Uri("https://localhost:44303/tokens"), ProtocolVersion = ProtocolVersion.V20 }; // Create the client with which we will be connecting to the server. var userAgentClient = new UserAgentClient(authorizationServerDescription, clientIdentifier: "demo-client-1", clientSecret: "demo-client-secret-1"); // The scope that we request for the client. Note: this can also be null if we don't want to request any specific // scope or more than one scope if we want to request an access token that is valid for several scopes var clientScopes = new[] { "demo-scope-client-1" }; // Request a new client access token for the specified scopes (http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-4.4) // This method will use the client identifier and client secret used when constructing the UserAgentClient instance var clientAccessToken = userAgentClient.GetClientAccessToken(clientScopes); // Output some information about the retrieved client access token Console.WriteLine("[RETRIEVED CLIENT ACCESS TOKEN]"); Console.WriteLine("Access token: {0}", clientAccessToken.AccessToken); Console.WriteLine("Expiration time: {0}", clientAccessToken.AccessTokenExpirationUtc); Console.WriteLine("Scope: {0}", OAuthUtilities.JoinScopes(clientAccessToken.Scope)); // The scope that we request for the user. Note: this can also be null if we don't want to request any specific // scope or more than one scope if we want to request an access token that is valid for several scopes var userScopes = new[] { "demo-scope-1" }; // Request a new user access token for the specified user and the specified scopes (http://tools.ietf.org/html/draft-ietf-oauth-v2-31#page-35) var userAccessToken = userAgentClient.ExchangeUserCredentialForToken("demo-user-1", "demo-user-password-1", userScopes); // Output some information about the retrieved user access token Console.WriteLine("\n[RETRIEVED USER ACCESS TOKEN]"); Console.WriteLine("Access token: {0}", userAccessToken.AccessToken); Console.WriteLine("Refresh token: {0}", userAccessToken.RefreshToken); Console.WriteLine("Expiration time: {0}", userAccessToken.AccessTokenExpirationUtc); Console.WriteLine("Scope: {0}", OAuthUtilities.JoinScopes(userAccessToken.Scope)); var refreshed = userAgentClient.RefreshAuthorization(userAccessToken); Console.WriteLine("\n[REFRESHING USER ACCESS TOKEN]"); Console.WriteLine("Access token refreshed: {0}", refreshed); Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); }
protected void Page_Load(object sender, EventArgs e) { useragent = new UserAgentClient(); if (!IsPostBack) { generateAlerts(); getUsername(); } showAlerts(); }
private void InitializeWcfConsumer() { var authServer = new AuthorizationServerDescription() { AuthorizationEndpoint = new Uri("http://localhost:50172/OAuth/Authorize"), TokenEndpoint = new Uri("http://localhost:50172/OAuth/Token"), }; this.wcf = new UserAgentClient(authServer, "sampleconsumer", "samplesecret"); }
/// <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)); }
public HomeController() { var authServer = new AuthorizationServerDescription() { AuthorizationEndpoint = new Uri(AUTHORIZATION_ENDPOINT), TokenEndpoint = new Uri(TOKEN_ENDPOINT), }; this.Client = new UserAgentClient(authServer, CLIENT_ID, CLIENT_SECRET); this.Authorization = new AuthorizationState(); this.Authorization.Callback = new Uri(AUTHORIZATION_CALLBACK); }
public HomeController() { var authServer = new AuthorizationServerDescription() { AuthorizationEndpoint = new Uri("http://localhost:49810/OAuth/Authorise"), TokenEndpoint = new Uri("http://localhost:49810/OAuth/Token"), }; this.Client = new UserAgentClient(authServer, "samplewebapiconsumer", "samplesecret"); this.Authorization = new AuthorizationState(); this.Authorization.Callback = new Uri("http://localhost:49907/"); }
public OAuth2ClientController() { var authServer = new AuthorizationServerDescription() { AuthorizationEndpoint = new Uri(HostBaseUrl + "/OAuth2/OAuth/Authorise"), TokenEndpoint = new Uri(HostBaseUrl + "/OAuth2/OAuth/Token"), }; this.Client = new UserAgentClient(authServer, "EZOper.TechTester.OAuth2WebSI", "erikzhouxin"); this.Authorization = new AuthorizationState(); this.Authorization.Callback = new Uri(ClientBaseUrl + "/OAuth2Client/Index"); }
public Authorize(UserAgentClient client) { InitializeComponent(); var clientAuthorizationViewWebBrowserOrNull = clientAuthorizationView.Controls.OfType <System.Windows.Forms.WebBrowser>().FirstOrDefault(); if (clientAuthorizationViewWebBrowserOrNull != null) { clientAuthorizationViewWebBrowserOrNull.ScriptErrorsSuppressed = true; } clientAuthorizationView.Client = client; }
public async Task ErrorResponseTest() { Handle(AuthorizationServerDescription.TokenEndpoint).By( async(req, ct) => { var server = new AuthorizationServer(AuthorizationServerMock); return(await server.HandleTokenRequestAsync(req, ct)); }); var request = new AccessTokenAuthorizationCodeRequestC(AuthorizationServerDescription) { ClientIdentifier = ClientId, ClientSecret = ClientSecret, AuthorizationCode = "foo" }; var client = new UserAgentClient(AuthorizationServerDescription, hostFactories: this.HostFactories); var response = await client.Channel.RequestAsync <AccessTokenFailedResponse>(request, CancellationToken.None); Assert.That(response.Error, Is.Not.Null.And.Not.Empty); Assert.That(response.Error, Is.EqualTo(Protocol.AccessTokenRequestErrorCodes.InvalidRequest)); }
public async Task AuthorizationCodeGrant() { 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); var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername); return(await server.Channel.PrepareResponseAsync(response, ct)); }); Handle(AuthorizationServerDescription.TokenEndpoint).By( async(req, ct) => { var server = new AuthorizationServer(AuthorizationServerMock); return(await server.HandleTokenRequestAsync(req, ct)); }); { var client = new UserAgentClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories); var authState = new AuthorizationState(TestScopes) { Callback = ClientCallback, }; var request = client.PrepareRequestUserAuthorization(authState); Assert.AreEqual(EndUserAuthorizationResponseType.AuthorizationCode, request.ResponseType); 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.Not.Null.And.Not.Empty); } }
// returns the authentication token public string Run() { string accessToken = ""; Console.WriteLine("--- Authorization---"); Console.WriteLine("Authorization endpoint: " + clo.authorizationEndpoint); Console.WriteLine("Token endpoint: " + clo.tokenEndpoint); AuthorizationServerDescription authServerDescription = new AuthorizationServerDescription() { AuthorizationEndpoint = new Uri(clo.authorizationEndpoint), TokenEndpoint = new Uri(clo.tokenEndpoint) }; Console.WriteLine("Client ID: " + clo.clientId); Console.WriteLine("Client secret: ***"); UserAgentClient client = new UserAgentClient(authServerDescription, clo.clientId, clo.clientSecret); Console.WriteLine("User: "******"Password: ***"); List <string> scopes = new List <string>(); scopes.Add("sessions.read"); scopes.Add("sessions.write"); scopes.Add("users.read"); scopes.Add("users.write"); scopes.Add("shoes.read"); scopes.Add("shoes.write"); scopes.Add("shoes.delete"); scopes.Add("settings.read"); IAuthorizationState authState = client.ExchangeUserCredentialForToken(clo.username, clo.password, scopes); if (authState != null && authState.AccessToken != null) { accessToken = authState.AccessToken; Console.WriteLine("Access token: " + accessToken); } Console.WriteLine("Success!"); Console.WriteLine(); return(accessToken); }
private IAuthorizationState GetAccessTokenFromOwnAuthSvr() { var server = new AuthorizationServerDescription { TokenEndpoint = new Uri(Config.ApiUrl + "/oauth/token"), ProtocolVersion = ProtocolVersion.V20 }; var client = new UserAgentClient(server) { //Those are the credentials for Downlords-FAF-Client ClientIdentifier = Config.ClientIdentifier, ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(Config.ClientCredentialApplicator) }; var token = client.ExchangeUserCredentialForToken( UsernameInputField.text, PasswordInputField.text); return(token); }
public void Authenticate() { var authServer = new AuthorizationServerDescription() { AuthorizationEndpoint = new Uri(AUTH_ENDPOINT), TokenEndpoint = new Uri(TOKEN_ENDPOINT) }; var client = new UserAgentClient(authServer, CLIENT_ID, CLIENT_SECRET); var authorizePopup = new Authorize(client); bool?result = authorizePopup.ShowDialog(); if (result.HasValue && result.Value) { _authorization = authorizePopup.Authorization; } else { throw new Exception("Not authorized"); } }
public string RetrieveAuthorization(UserAgentClient client, IAuthorizationState authorizationState) { if (!HttpListener.IsSupported) { throw new NotSupportedException("HttpListener is not supported by this platform."); } // Create a HttpListener for the specified url. string url = string.Format(LoopbackCallback, GetRandomUnusedPort(), Assembly.GetEntryAssembly().GetName().Name); authorizationState.Callback = new Uri(url); var webserver = new HttpListener(); webserver.Prefixes.Add(url); // Retrieve the authorization url. Uri authUrl = client.RequestUserAuthorization(authorizationState); try { // Start the webserver. webserver.Start(); // Open the browser. Process.Start(authUrl.ToString()); // Wait for the incoming connection, then handle the request. return(HandleRequest(webserver.GetContext())); } catch (HttpListenerException ex) { ErrorDump.AddError(System.IntPtr.Zero, "LoopbackServerAuthorizationFlow.cs", "RetrieveAuthorization", ex, "The HttpListener threw an exception."); return(null); //throw new NotSupportedException("The HttpListener threw an exception.", ex); } finally { // Stop the server after handling the one request. webserver.Stop(); } }
public Uri GetAuthorizationUri() { _endPoint = "https://start.exactonline.com"; _authorization = new AuthorizationState { Callback = new Uri("http://localhost:19648/home/exoauth2") }; var serverDescription = new AuthorizationServerDescription { AuthorizationEndpoint = new Uri(string.Format("{0}/api/oauth2/auth", _endPoint)), TokenEndpoint = new Uri(string.Format("{0}/api/oauth2/token", _endPoint)) }; _oAuthClient = new UserAgentClient(serverDescription, "eb93389b-9532-46ca-9b24-898a38e91c22", "jYzWXVFiE87C"); _oAuthClient.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter("jYzWXVFiE87C"); return(_oAuthClient.RequestUserAuthorization(_authorization)); }
public string RetrieveAuthorization(UserAgentClient client, IAuthorizationState authorizationState) { if (!HttpListener.IsSupported) { throw new NotSupportedException("HttpListener is not supported by this platform."); } // Create a HttpListener for the specified url. string url = string.Format(LoopbackCallback, GetRandomUnusedPort(), GDrive.Classes.Auth.Utilities.ApplicationName); authorizationState.Callback = new Uri(url); var webserver = new HttpListener(); webserver.Prefixes.Add(url); // Retrieve the authorization url. Uri authUrl = client.RequestUserAuthorization(authorizationState); try { // Start the webserver. webserver.Start(); // Open the browser. Process.Start(authUrl.ToString()); // Wait for the incoming connection, then handle the request. return(HandleRequest(webserver.GetContext())); } catch (HttpListenerException ex) { throw new NotSupportedException("The HttpListener threw an exception.", ex); } finally { // Stop the server after handling the one request. webserver.Stop(); } }
public string RetrieveAuthorization(UserAgentClient client, IAuthorizationState authorizationState) { // Create the Url. authorizationState.Callback = new Uri(OutOfBandCallback); Uri url = client.RequestUserAuthorization(authorizationState); // Show the dialog. if (!Application.RenderWithVisualStyles) { Application.EnableVisualStyles(); } Application.DoEvents(); string authCode = OAuth2AuthorizationDialog.ShowDialog(url); Application.DoEvents(); if (string.IsNullOrEmpty(authCode)) { return(null); // User cancelled the request. } return(authCode); }
public Authorize(UserAgentClient client) { InitializeComponent(); clientAuthorizationView.Client = client; }
internal Authorize2(UserAgentClient client) { this.InitializeComponent(); this.clientAuthorizationView.Client = client; }
public static void AuthorizeRequest(this UserAgentClient client, WebClient webClient, IAuthorizationState authorization) { webClient.Headers[HttpRequestHeader.Authorization] = string.Format(CultureInfo.InvariantCulture, "Bearer {0}", authorization.AccessToken); }