protected async void Button1_Click(object sender, EventArgs e) { var authServer = new AuthorizationServerDescription() { TokenEndpoint = new Uri("http://localhost:53022/OAuth/token "), ProtocolVersion = ProtocolVersion.V20 }; WebServerClient Client = new WebServerClient(authServer, "idefav", "1"); var code = await Client.GetClientAccessTokenAsync(new string[] { "http://localhost:55045/IService1/DoWork" }); string token = code.AccessToken; Service1Reference.Service1Client service1Client = new Service1Client(); var httpRequest = (HttpWebRequest)WebRequest.Create(service1Client.Endpoint.Address.Uri); ClientBase.AuthorizeRequest(httpRequest, token); var httpDetails = new HttpRequestMessageProperty(); httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization]; using (var scope = new OperationContextScope(service1Client.InnerChannel)) { if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name)) { OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails; } else { OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpDetails); } Button1.Text = service1Client.DoWork(); } }
public ViewResult ClientCredentialsGrant(ClientCredentialsGrantViewModel model) { if (this.ModelState.IsValid) { try { // Create the client with which we will be connecting to the server. var webServerClient = new WebServerClient(this.AuthorizationServerDescription, clientIdentifier: model.ClientId, clientSecret: model.ClientSecret); // 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 = OAuthUtilities.SplitScopes(model.Scope ?? string.Empty); // 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 WebServerAgentClient instance this.ViewBag.AccessToken = webServerClient.GetClientAccessToken(clientScopes); } catch (Exception ex) { this.ViewBag.Exception = ex; } } return(this.View(model)); }
public ViewResult RefreshToken(RefreshTokenViewModel model) { if (this.ModelState.IsValid) { try { // Create the client with which we will be connecting to the server. var webServerClient = new WebServerClient(this.AuthorizationServerDescription, clientIdentifier: model.ClientId, clientSecret: model.ClientSecret); // Create an AuthorizationState instance with only the refresh token set. This is all that is needed for // OAuth to be able to determine what token is to be refreshed var authorizationState = new AuthorizationState { RefreshToken = model.RefreshToken }; // Refresh an access token (http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-6) // This method will use the client identifier and client secret used when constructing the WebServerAgentClient instance webServerClient.RefreshAuthorization(authorizationState); this.ViewBag.AccessToken = authorizationState; } catch (Exception ex) { this.ViewBag.Exception = ex; } } return(this.View(model)); }
// GET: ClientCredential public async Task <ActionResult> Index() { ViewBag.ApiResult = ""; ViewBag.AccessToken = ""; if (Request.HttpMethod == "POST") { var authServer = new AuthorizationServerDescription { AuthorizationEndpoint = new Uri(Paths.AuthorizationServerBaseAddress + Paths.AuthorizePath), TokenEndpoint = new Uri(Paths.AuthorizationServerBaseAddress + Paths.TokenPath) }; var webServerClient = new WebServerClient(authServer, Clients.Client1.Id, Clients.Client1.Secret); var state = webServerClient.GetClientAccessToken(new[] { "test1", "test2", "test3" }); var token = state.AccessToken; ViewBag.AccessToken = token; var client = new HttpClient(webServerClient.CreateAuthorizingHandler(token)); var apiResult = await client.GetStringAsync(Paths.ResourceUserApiPath); ViewBag.ApiResult = apiResult; } return(View()); }
public AccountController() : this(DBContext.Create()) { this.authClient = CreateClient(); if (string.IsNullOrEmpty(AppSettings.OAuth2UserInfoEndpoint)) { throw new MissingFieldException("Trifolia is not configured correctly for OAuth2 login: OAuth2UserInfoEndpoint"); } if (string.IsNullOrEmpty(AppSettings.OAuth2AuthorizationEndpoint)) { throw new MissingFieldException("Trifolia is not configured correctly for OAuth2 login: OAuth2AuthorizationEndpoint"); } if (string.IsNullOrEmpty(AppSettings.OAuth2TokenEndpoint)) { throw new MissingFieldException("Trifolia is not configured correctly for OAuth2 login: OAuth2TokenEndpoint"); } if (string.IsNullOrEmpty(AppSettings.OAuth2ClientIdentifier)) { throw new MissingFieldException("Trifolia is not configured correctly for OAuth2 login: OAuth2ClientIdentifier"); } if (string.IsNullOrEmpty(AppSettings.OAuth2ClientSecret)) { throw new MissingFieldException("Trifolia is not configured correctly for OAuth2 login: OAuth2ClientSecret"); } }
private async Task <string> ObtainValidAccessTokenAsync() { string accessToken = null; var authServer = CreateAuthorizationServerMock(); authServer.Setup( a => a.IsAuthorizationValid(It.Is <IAuthorizationDescription>(d => d.User == null && d.ClientIdentifier == ClientId && MessagingUtilities.AreEquivalent(d.Scope, TestScopes)))) .Returns(true); authServer.Setup( a => a.CheckAuthorizeClientCredentialsGrant(It.Is <IAccessTokenRequest>(d => d.ClientIdentifier == ClientId && MessagingUtilities.AreEquivalent(d.Scope, TestScopes)))) .Returns <IAccessTokenRequest>(req => new AutomatedAuthorizationCheckResponse(req, true)); Handle(AuthorizationServerDescription.TokenEndpoint).By( async(req, ct) => { var server = new AuthorizationServer(authServer.Object); return(await server.HandleTokenRequestAsync(req, ct)); }); var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories); var authState = await client.GetClientAccessTokenAsync(TestScopes); Assert.That(authState.AccessToken, Is.Not.Null.And.Not.Empty); Assert.That(authState.RefreshToken, Is.Null); accessToken = authState.AccessToken; return(accessToken); }
public async Task ResourceOwnerPasswordCredentialGrant(bool anonymousClient) { var authHostMock = CreateAuthorizationServerMock(); if (anonymousClient) { authHostMock.Setup( m => m.IsAuthorizationValid( It.Is <IAuthorizationDescription>( d => d.ClientIdentifier == null && d.User == ResourceOwnerUsername && MessagingUtilities.AreEquivalent(d.Scope, TestScopes)))).Returns(true); } Handle(AuthorizationServerDescription.TokenEndpoint).By(async(req, ct) => { var server = new AuthorizationServer(authHostMock.Object); return(await server.HandleTokenRequestAsync(req, ct)); }); var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories); if (anonymousClient) { client.ClientIdentifier = null; } var authState = await client.ExchangeUserCredentialForTokenAsync(ResourceOwnerUsername, ResourceOwnerPassword, TestScopes); Assert.That(authState.AccessToken, Is.Not.Null.And.Not.Empty); Assert.That(authState.RefreshToken, Is.Not.Null.And.Not.Empty); }
/// <summary> /// Refreshes the access token if (a) there is a refresh token, and (b) there is not an unexpired accesstoken /// </summary> /// <returns>True if the update happened and was successful</returns> public async Task <bool> RefreshAccessToken() { return(await Task.Run <bool>(() => { // Don't refresh if no refresh token, or if current access token is still valid if (CheckAccessToken() || String.IsNullOrEmpty(AuthState.RefreshToken)) { return false; } WebServerClient client = Client(); try { client.RefreshAuthorization(AuthState); } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { GDriveError error = JsonConvert.DeserializeObject <GDriveError>(ExtractResponseString(ex.InnerException as WebException)); if (error == null) { throw; } else if (error.error.CompareCurrentCultureIgnoreCase("invalid_grant") == 0) { throw new MyFlightbookException(Branding.ReBrand(Resources.LocalizedText.GoogleDriveBadAuth), ex); } else { throw new MyFlightbookException(String.Format(CultureInfo.CurrentCulture, "Error from Google Drive: {0} {1} {2}", error.error, error.error_description, error.error_uri), ex); } } return true; })); }
public virtual IAuthorizationState ProcessUserAuthorization( WebServerClient authClient, AuthorizationServerDescription authServer, IServiceBase authService) { return(HostContext.Config.StripApplicationVirtualPath ? authClient.ProcessUserAuthorization(authService.Request.ToHttpRequestBase()) : authClient.ProcessUserAuthorization()); }
/// <summary> /// Create the web server client used for OAuth2 authentication. /// </summary> /// <returns>Exact Online web server client</returns> public static WebServerClient CreateClient() { AuthorizationServerDescription description = GetAuthServerDescription(); WebServerClient client = new WebServerClient(description, ConfigurationManager.AppSettings["exactClientId"], ConfigurationManager.AppSettings["exactClientSecret"]); return(client); }
public static string updateUser(WebServerClient webServerClient) { User user = JsonConvert.DeserializeObject <User>(webServerClient.body); UsersService.updateUser(user); return(null); }
/// <summary> /// Requests authorization from the server without an existing token. This method will parse the request url and extract the authorization code returned from Visma after /// entering valid credentials on their login site. /// </summary> /// <returns> /// An 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 RequestAuthorization(WebServerClient client) { // Processes authorization by parsing codes from the URI gotten in return from Visma and creates an authorization state. var state = client.ProcessUserAuthorization(); return(state); }
//Authentication Method public void Authenticate() { var serverDescription = new AuthorizationServerDescription(); serverDescription.AuthorizationEndpoint = new Uri(AuthorizationEndpointUrl); serverDescription.TokenEndpoint = new Uri(TokenEndpointUrl); serverDescription.ProtocolVersion = ProtocolVersion.V20; var client = new WebServerClient(serverDescription); client.ClientIdentifier = ClientIdentifier; client.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(ClientSecret); var token = client.GetClientAccessToken(); //var request = (HttpWebRequest)WebRequest.Create("http://localhost:8080/test/"); ////System.Diagnostics.Process.Start("http://localhost:8080/test/"); //request.Method = "GET"; //client.AuthorizeRequest(request, token); //var response = request.GetResponse(); //var postreqreader = new StreamReader(response.GetResponseStream()); //var json = postreqreader.ReadToEnd(); }
public IAuthorizationState RequestAccessToken(string refreshToken) { { WebServerClient consumer = new WebServerClient(ServerDescription, ClientID, ClientSecret) { AuthorizationTracker = new AuthorizationTracker(Scope) }; IAuthorizationState grantedAccess = PrepareAuthorizationState(refreshToken); if (grantedAccess != null) { try { consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(ClientSecret); consumer.RefreshAuthorization(grantedAccess, null); return(grantedAccess); } catch (Exception ex) { _log.Error("RefreshAuthorization() Exception:\r\n{0}\r\n", ex.ToString()); } } return(null); } }
protected void btnGetToken_Click(object sender, EventArgs e) { if (!Page.IsValid) { return; } try { ToSession(); WebServerClient consumer = new WebServerClient(Description(), CurrentPageState.ClientID, CurrentPageState.ClientSecret); consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(CurrentPageState.ClientSecret); IAuthorizationState grantedAccess = consumer.ProcessUserAuthorization(new HttpRequestWrapper(Request)); if (grantedAccess == null) { throw new MyFlightbook.MyFlightbookValidationException("Null access token returned - invalid authorization passed?"); } lblToken.Text = grantedAccess.AccessToken; } catch (MyFlightbook.MyFlightbookValidationException ex) { lblErr.Text = ex.Message; } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { lblErr.Text = ex.Message; } }
public async Task ResourceOwnerScopeOverride() { var clientRequestedScopes = new[] { "scope1", "scope2" }; var serverOverriddenScopes = new[] { "scope1", "differentScope" }; var authServerMock = CreateAuthorizationServerMock(); authServerMock .Setup(a => a.CheckAuthorizeResourceOwnerCredentialGrant(ResourceOwnerUsername, ResourceOwnerPassword, It.IsAny <IAccessTokenRequest>())) .Returns <string, string, IAccessTokenRequest>((un, pw, req) => { var response = new AutomatedUserAuthorizationCheckResponse(req, true, ResourceOwnerUsername); response.ApprovedScope.Clear(); response.ApprovedScope.UnionWith(serverOverriddenScopes); return(response); }); Handle(AuthorizationServerDescription.TokenEndpoint).By( async(req, ct) => { var server = new AuthorizationServer(authServerMock.Object); return(await server.HandleTokenRequestAsync(req, ct)); }); var client = new WebServerClient(AuthorizationServerDescription, hostFactories: this.HostFactories); var result = await client.ExchangeUserCredentialForTokenAsync(ResourceOwnerUsername, ResourceOwnerPassword, clientRequestedScopes); Assert.That(result.Scope, Is.EquivalentTo(serverOverriddenScopes)); }
public async Task ClientCredentialScopeOverride() { var clientRequestedScopes = new[] { "scope1", "scope2" }; var serverOverriddenScopes = new[] { "scope1", "differentScope" }; var authServerMock = CreateAuthorizationServerMock(); authServerMock .Setup(a => a.CheckAuthorizeClientCredentialsGrant(It.IsAny <IAccessTokenRequest>())) .Returns <IAccessTokenRequest>(req => { var response = new AutomatedAuthorizationCheckResponse(req, true); response.ApprovedScope.Clear(); response.ApprovedScope.UnionWith(serverOverriddenScopes); return(response); }); Handle(AuthorizationServerDescription.TokenEndpoint).By( async(req, ct) => { var server = new AuthorizationServer(authServerMock.Object); return(await server.HandleTokenRequestAsync(req, ct)); }); var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories); var result = await client.GetClientAccessTokenAsync(clientRequestedScopes); Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty); Assert.That(result.Scope, Is.EquivalentTo(serverOverriddenScopes)); }
public async Task GetClientAccessTokenReturnsApprovedScope() { string[] approvedScopes = new[] { "Scope2", "Scope3" }; var authServer = CreateAuthorizationServerMock(); authServer.Setup( a => a.IsAuthorizationValid(It.Is <IAuthorizationDescription>(d => d.User == null && d.ClientIdentifier == ClientId && MessagingUtilities.AreEquivalent(d.Scope, TestScopes)))) .Returns(true); authServer.Setup( a => a.CheckAuthorizeClientCredentialsGrant(It.Is <IAccessTokenRequest>(d => d.ClientIdentifier == ClientId && MessagingUtilities.AreEquivalent(d.Scope, TestScopes)))) .Returns <IAccessTokenRequest>(req => { var response = new AutomatedAuthorizationCheckResponse(req, true); response.ApprovedScope.ResetContents(approvedScopes); return(response); }); Handle(AuthorizationServerDescription.TokenEndpoint).By( async(req, ct) => { var server = new AuthorizationServer(authServer.Object); return(await server.HandleTokenRequestAsync(req, ct)); }); var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories); var authState = await client.GetClientAccessTokenAsync(TestScopes); Assert.That(authState.Scope, Is.EquivalentTo(approvedScopes)); }
public async Task <ActionResult> Index(string username, string password) { ViewBag.Username = username; ViewBag.Password = password; ViewBag.ApiResult = ""; ViewBag.AccessToken = ""; if (!string.IsNullOrEmpty(username)) { var authServer = new AuthorizationServerDescription { AuthorizationEndpoint = new Uri(Paths.AuthorizationServerBaseAddress + Paths.AuthorizePath), TokenEndpoint = new Uri(Paths.AuthorizationServerBaseAddress + Paths.TokenPath) }; var webServerClient = new WebServerClient(authServer, Clients.Client1.Id, Clients.Client1.Secret); var state = webServerClient.ExchangeUserCredentialForToken(username, password, new[] { "test1", "test2", "test3" }); var token = state.AccessToken; ViewBag.AccessToken = token; var client = new HttpClient(webServerClient.CreateAuthorizingHandler(token)); var apiResult = await client.GetStringAsync(Paths.ResourceUserApiPath); ViewBag.ApiResult = apiResult; } return(View()); }
private IAuthorizationState GetAuthorization(WebServerClient client) { // If this user is already authenticated, then just return the auth state. IAuthorizationState state = AuthState; if (state != null) { return(state); } // Check if an authorization request already is in progress. state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request)); if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken))) { // Store and return the credentials. HttpContext.Current.Session["AUTH_STATE"] = _state = state; return(state); } // Otherwise do a new authorization request. string scope = TasksService.Scopes.TasksReadonly.GetStringValue(); OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope }, ""); response.Send(); // Will throw a ThreadAbortException to prevent sending another response. return(null); }
public static string deleteUsers(WebServerClient webServerClient) { int id; int.TryParse(webServerClient.body, out id); UsersService.deleteUser(id); return(null); }
/// <summary> /// Writes a Google+ App Activity to Google logging that the user has voted on a PhotoHunt /// photo. /// </summary> /// <param name="user">The user who has voted.</param> /// <param name="voteTarget">The photo the user has voted on.</param> public void WriteGooglePlusVoteAppActivity(User user, Photo voteTarget) { // Write an app activity for the vote. // Set the auth state in a the superclass for the authorization call. _authState = CreateState(user.googleAccessToken, user.googleRefreshToken, user.googleExpiresAt.AddSeconds(user.googleExpiresIn * -1), user.googleExpiresAt); AuthorizationServerDescription description = GoogleAuthenticationServer.Description; var provider = new WebServerClient(description); provider.ClientIdentifier = CLIENT_ID; provider.ClientSecret = CLIENT_SECRET; var authenticator = new OAuth2Authenticator <WebServerClient>( provider, GetAuthorization) { NoCaching = true }; ps = new PlusService(new BaseClientService.Initializer() { Authenticator = authenticator }); Moment body = new Moment(); ItemScope target = new ItemScope(); ItemScope result = new ItemScope(); // The target (an image) will be parsed from this URL containing microdata. target.Url = BASE_URL + "photo.aspx?photoId=" + voteTarget.id; // Just use a static review result. result.Type = SCHEMA_REVIEW_TYPE; result.Name = "A vote for this PhotoHunt photo."; result.Url = target.Url; result.Text = "This photo embodies " + voteTarget.themeDisplayName; body.Target = target; body.Result = result; body.Type = REVIEW_ACTIVITY_TYPE; MomentsResource.InsertRequest insert = new MomentsResource.InsertRequest( ps, body, "me", MomentsResource.Collection.Vault); try { insert.Fetch(); } catch (GoogleApiRequestException gare) { Debug.WriteLine("Error while writing app activity: " + gare.InnerException.Message + "\nThis could happen if the Google+ proxy can't access your server."); } }
private void InitializeWebServerClient() { var authServer = new AuthorizationServerDescription { AuthorizationEndpoint = new Uri(Paths.AuthorizationServerBaseAddress + Paths.AuthorizePath), TokenEndpoint = new Uri(Paths.AuthorizationServerBaseAddress + Paths.TokenPath) }; webServerClient = new WebServerClient(authServer, Clients.Client1.Id, Clients.Client1.Secret); }
/// <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 IAuthorizationState ConvertToken(HttpRequest Request) { WebServerClient consumer = new WebServerClient(Description(), AppKey, AppSecret) { ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(AppSecret) }; return(consumer.ProcessUserAuthorization(new HttpRequestWrapper(Request))); }
private WebServerClient CreateOAuth2Client() { var serverDescription = new AuthorizationServerDescription { TokenEndpoint = new Uri(tokenEndpointTextBox.Text) }; var client = new WebServerClient(serverDescription, oauth2ClientIdTextBox.Text, oauth2ClientSecretTextBox.Text); return(client); }
private static void InitializeWebServerClient() { var authorizationServer = new AuthorizationServerDescription { AuthorizationEndpoint = new Uri("https://login.windows.net/e27023d0-bf6d-47f1-94be-a75cae8debcd/oauth2/authorize" /* WHAT TO PUT HERE */), TokenEndpoint = new Uri("https://login.windows.net/e27023d0-bf6d-47f1-94be-a75cae8debcd/oauth2/token" /* WHAT TO PUT HERE */) }; _webServerClient = new WebServerClient(authorizationServer, clientId, appKey); }
/// <summary> /// This Method is to Autheticate state using Refresh Token /// </summary> /// <param name="client"></param> /// <returns></returns> private IAuthorizationState Authenticatestate(WebServerClient client) { IAuthorizationState state = new AuthorizationState(new string[] { }) { RefreshToken = txtRefreshToken.Text }; client.RefreshToken(state); return(state); }
/// <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))); }
public OAuthClient(string authorizationEndpoint, string tokenEndpoint, string clientId, string clientSecret) { var authServer = new AuthorizationServerDescription { AuthorizationEndpoint = new Uri(authorizationEndpoint), TokenEndpoint = new Uri(tokenEndpoint) }; _webServerClient = new WebServerClient(authServer, clientId, clientSecret); }
private void CreateAuthZTokenClient(string clientIdentifier, string clientSecret) { Guard.NotNullOrEmpty(() => clientIdentifier, clientIdentifier); Guard.NotNullOrEmpty(() => clientSecret, clientSecret); authZTokenClient = new WebServerClient(new AuthorizationServerDescription { TokenEndpoint = new Uri(Settings.GetSetting(@"AuthZService.BaseUrl.Token")), }, clientIdentifier, clientSecret); }
private IAuthorizationState GetAuthorization(WebServerClient myWebServerClient) { var state = HttpContext.Current.Session["GA_AUTH_STATE"] as IAuthorizationState; if (state != null) { return state; } state = myWebServerClient.ProcessUserAuthorization( new HttpRequestInfo(HttpContext.Current.Request) ); if (state != null && (state.AccessToken.IsNotEmpty() || state.RefreshToken.IsNotEmpty())) { HttpContext.Current.Session["GA_AUTH_STATE"] = state; return state; } var scopes = new[] { "https://www.google.com/analytics/feeds/", "https://www.googleapis.com/auth/analytics.readonly" }; myWebServerClient.PrepareRequestUserAuthorization(scopes).Send(); return null; }