public async Task Can_signup_user_and_change_password() { // Arrange var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // Sign up the user var signupUserRequest = new SignupUserRequest { ClientId = clientId, Connection = connection.Name, Email = $"{Guid.NewGuid().ToString("N")}@nonexistingdomain.aaa", Password = "******" }; var signupUserResponse = await authenticationApiClient.SignupUserAsync(signupUserRequest); signupUserResponse.Should().NotBeNull(); signupUserResponse.Email.Should().Be(signupUserRequest.Email); // Change the user's Email address var changePasswordRequest = new ChangePasswordRequest { ClientId = signupUserRequest.ClientId, Connection = signupUserRequest.Connection, Email = signupUserRequest.Email, Password = "******" }; string changePasswordResponse = await authenticationApiClient.ChangePasswordAsync(changePasswordRequest); changePasswordResponse.Should().Be("\"We've just sent you an Email to reset your password.\""); }
public async Task Can_get_delegation_token() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // First get the access token var token = await authenticationApiClient.GetAccessToken(new AccessTokenRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), Connection = "google-oauth2", AccessToken = accessToken, Scope = "openid" }); // Then request the delegation token var delegationToken = await authenticationApiClient.GetDelegationToken(new IdTokenDelegationRequest( GetVariable("AUTH0_CLIENT_ID"), GetVariable("AUTH0_CLIENT_ID"), token.IdToken) { Scope = "openid", GrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer", ApiType = "app" }); delegationToken.Should().NotBeNull(); delegationToken.IdToken.Should().NotBeNull(); }
public void Can_build_saml_url() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); var samlUrl = authenticationApiClient.BuildSamlUrl("myclientid") .WithConnection("my-connection-name") .Build(); samlUrl.Should().Be(@"https://auth0-dotnet-integration-tests.auth0.com/samlp/myclientid?connection=my-connection-name"); }
public async Task Can_retrieve_wsfed_metadata() { // Arrange var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // Act var response = await authenticationApiClient.GetWsFedMetadata(); // Assert response.Should().NotBeNull(); }
public void Can_build_logout_url() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); var logoutUrl = authenticationApiClient.BuildLogoutUrl() .Build(); logoutUrl.Should() .Be( @"https://auth0-dotnet-integration-tests.auth0.com/logout"); }
public void Can_build_logout_url_with_return_url() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); var logoutUrl = authenticationApiClient.BuildLogoutUrl() .WithReturnUrl("http://www.jerriepelser.com/test") .Build(); logoutUrl.Should() .Be( @"https://auth0-dotnet-integration-tests.auth0.com/logout?returnTo=http:%2F%2Fwww.jerriepelser.com%2Ftest"); }
public void Can_build_wsfed_with_relaystate_dictionary() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); var samlUrl = authenticationApiClient.BuildSamlUrl("myclientid") .WithRelayState(new Dictionary<string, string> { {"xcrf", "abc"}, {"ru", "/foo"} }) .Build(); samlUrl.Should().Be(@"https://auth0-dotnet-integration-tests.auth0.com/samlp/myclientid?relayState=xcrf%3Dabc%26ru%3D%2Ffoo"); }
public async Task Can_launch_sms_flow() { // Arrange var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_PASSWORDLESSDEMO_AUTHENTICATION_API_URL"))); // Act var request = new PasswordlessSmsRequest { ClientId = GetVariable("AUTH0_PASSWORDLESSDEMO_CLIENT_ID"), PhoneNumber = "your phone number" }; var response = await authenticationApiClient.StartPasswordlessSmsFlowAsync(request); response.Should().NotBeNull(); response.PhoneNumber.Should().Be(request.PhoneNumber); }
public async Task Can_impersonate_user() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); var uri = await authenticationApiClient.GetImpersonationUrl(new ImpersonationRequest { ImpersonateId = "impersonate id", Token = accessToken, Protocol = "oauth2", ClientId = GetVariable("AUTH0_CLIENT_ID"), ImpersonatorId = "impoersonator id" }); uri.Should().NotBeNull(); }
public async Task Can_exchange_authorization_code_for_access_token() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // Exchange the authorization code var token = await authenticationApiClient.GetTokenAsync(new AuthorizationCodeTokenRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"), RedirectUri = "http://www.blah.com/test", Code = "AaBhdAOl4OKvjX2I" }); // Assert token.Should().NotBeNull(); }
public void Can_provide_response_mode() { var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL")); var authorizationUrl = authenticationApiClient.BuildAuthorizationUrl() .WithResponseType(AuthorizationResponseType.Code) .WithClient("rLNKKMORlaDzrMTqGtSL9ZSXiBBksCQW") .WithRedirectUrl("http://www.jerriepelser.com/test") .WithScope("openid") .WithResponseMode(AuthorizationResponseMode.FormPost) .Build(); authorizationUrl.Should() .Be( @"https://auth0-dotnet-integration-tests.auth0.com/authorize?response_type=code&client_id=rLNKKMORlaDzrMTqGtSL9ZSXiBBksCQW&redirect_uri=http%3A%2F%2Fwww.jerriepelser.com%2Ftest&scope=openid&response_mode=form_post"); }
public void Can_provide_multiple_response_type() { var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL")); var authorizationUrl = authenticationApiClient.BuildAuthorizationUrl() .WithResponseType(AuthorizationResponseType.Code) .WithClient("rLNKKMORlaDzrMTqGtSL9ZSXiBBksCQW") .WithConnection("google-oauth2") .WithRedirectUrl("http://www.jerriepelser.com/test") .WithScope("openid offline_access") .Build(); authorizationUrl.Should() .Be( @"https://auth0-dotnet-integration-tests.auth0.com/authorize?response_type=code&client_id=rLNKKMORlaDzrMTqGtSL9ZSXiBBksCQW&connection=google-oauth2&redirect_uri=http%3A%2F%2Fwww.jerriepelser.com%2Ftest&scope=openid%20offline_access"); }
public async Task InitializeAsync() { string token = await GenerateManagementApiToken(); _managementApiClient = new ManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL")); // We will need a connection to add the users to... _connection = await _managementApiClient.Connections.CreateAsync(new ConnectionCreateRequest { Name = Guid.NewGuid().ToString("N"), Strategy = "auth0", EnabledClients = new[] { GetVariable("AUTH0_CLIENT_ID"), GetVariable("AUTH0_MANAGEMENT_API_CLIENT_ID") } }); _authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL")); }
public async Task Can_log_in_with_access_token() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); var token = await authenticationApiClient.GetAccessToken(new AccessTokenRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), Connection = "google-oauth2", AccessToken = accessToken, Scope = "openid" }); token.Should().NotBeNull(); token.IdToken.Should().NotBeNull(); token.AccessToken.Should().NotBeNull(); }
public async Task <object> UserInformation() { // Retrieve the access_token claim which we saved in the OnTokenValidated event string accessToken = User.Claims.FirstOrDefault(c => c.Type == "access_token").Value; // If we have an access_token, then retrieve the user's information if (!string.IsNullOrEmpty(accessToken)) { var apiClient = new AuthenticationApiClient(_configuration["auth0:domain"]); var userInfo = await apiClient.GetUserInfoAsync(accessToken); return(userInfo); } return(null); }
public async Task Can_launch_email_code_flow() { // Arrange var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // Act var request = new PasswordlessEmailRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), Email = "your email", Type = PasswordlessEmailRequestType.Code }; var response = await authenticationApiClient.StartPasswordlessEmailFlowAsync(request); response.Should().NotBeNull(); response.Email.Should().Be(request.Email); }
public async Task Can_build_authorization_uri() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); var authorizationUrl = authenticationApiClient.BuildAuthorizationUrl() .WithResponseType(AuthorizationResponseType.Code) .WithClient("rLNKKMORlaDzrMTqGtSL9ZSXiBBksCQW") .WithConnection("google-oauth2") .WithRedirectUrl("http://www.jerriepelser.com/test") .WithScope("openid offline_access") .Build(); authorizationUrl.Should() .Be( @"https://auth0-dotnet-integration-tests.auth0.com/authorize?response_type=code&client_id=rLNKKMORlaDzrMTqGtSL9ZSXiBBksCQW&connection=google-oauth2&redirect_uri=http%3A%2F%2Fwww.jerriepelser.com%2Ftest&scope=openid%20offline_access"); }
public async Task <IActionResult> Login(LoginViewModel vm, string returnUrl = null) { if (ModelState.IsValid) { try { var client = new AuthenticationApiClient(new Uri($"https://{_auth0Settings.Domain}/")); var result = await client.GetTokenAsync(new ResourceOwnerTokenRequest { ClientId = _auth0Settings.ClientId, ClientSecret = _auth0Settings.ClientSecret, Scope = "openid profile", Realm = "Username-Password-Authentication", // Specify the correct name of your DB connection Username = vm.EmailAddress, Password = vm.Password }); // Get user info from token var user = await client.GetUserInfoAsync(result.AccessToken); var id = user.UserId; var username = user.PreferredUsername; var email = user.Email; // Create claims principal var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, user.UserId), new Claim(ClaimTypes.Name, user.FullName) }, CookieAuthenticationDefaults.AuthenticationScheme)); // Sign user into cookie middleware await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal); return(RedirectToLocal(returnUrl)); } catch (Exception e) { ModelState.AddModelError("", e.Message); } } return(View("Login", vm)); }
public async Task Can_launch_sms_flow() { // Arrange using (var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_PASSWORDLESSDEMO_AUTHENTICATION_API_URL"))) { // Act var request = new PasswordlessSmsRequest { ClientId = GetVariable("AUTH0_PASSWORDLESSDEMO_CLIENT_ID"), PhoneNumber = "your phone number" }; var response = await authenticationApiClient.StartPasswordlessSmsFlowAsync(request); response.Should().NotBeNull(); response.PhoneNumber.Should().Be(request.PhoneNumber); } }
public async Task Can_authenticate_with_passwordless_email_code() { // Arrange var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // Arrange var authenticationResponse = await authenticationApiClient.AuthenticateAsync(new AuthenticationRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), Connection = "email", GrantType = "password", Scope = "openid", Username = "******", Password = "******" }); authenticationResponse.Should().NotBeNull(); }
public async Task Can_launch_email_code_flow() { // Arrange var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // Act var request = new PasswordlessEmailRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), Email = "your email", Type = PasswordlessEmailRequestType.Code }; var response = await authenticationApiClient.StartPasswordlessEmailFlowAsync(request); response.Should().NotBeNull(); response.Email.Should().Be(request.Email); }
public async Task <ActionResult> Login(LoginViewModel vm, string returnUrl = null) { if (ModelState.IsValid) { try { AuthenticationApiClient client = new AuthenticationApiClient( new Uri($"https://{ConfigurationManager.AppSettings["auth0:Domain"]}/")); var result = await client.AuthenticateAsync(new AuthenticationRequest { ClientId = ConfigurationManager.AppSettings["auth0:ClientId"], Scope = "openid", Connection = "Database-Connection", // Specify the correct name of your DB connection Username = vm.EmailAddress, Password = vm.Password }); // Get user info from token var user = await client.GetTokenInfoAsync(result.IdToken); // Create claims principal var claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, user.UserId), new Claim(ClaimTypes.Name, user.FullName ?? user.Email), new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string") }, DefaultAuthenticationTypes.ApplicationCookie); // Sign user into cookie middleware AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, claimsIdentity); return(RedirectToLocal(returnUrl)); } catch (Exception e) { ModelState.AddModelError("", e.Message); } } return(View(vm)); }
public void Can_build_authorization_uri_with_organization() { var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL")); var authorizationUrl = authenticationApiClient.BuildAuthorizationUrl() .WithResponseType(AuthorizationResponseType.Code) .WithClient("rLNKKMORlaDzrMTqGtSL9ZSXiBBksCQW") .WithRedirectUrl("http://www.jerriepelser.com/test") .WithScope("openid offline_access") .WithNonce("MyNonce") .WithState("MyState") .WithOrganization("123") .Build(); authorizationUrl.Should() .Be( new Uri("https://dx-sdks-testing.us.auth0.com/authorize?response_type=code&client_id=rLNKKMORlaDzrMTqGtSL9ZSXiBBksCQW&redirect_uri=http%3A%2F%2Fwww.jerriepelser.com%2Ftest&scope=openid%20offline_access&nonce=MyNonce&state=MyState&organization=123")); }
public async Task <LoginResponse> LoginUser(LoginRequest login) { AuthenticationApiClient auth = new AuthenticationApiClient(this.Domain); var res = await auth.GetTokenAsync(new ResourceOwnerTokenRequest() { Audience = this.Audience, ClientId = this.ClientId, ClientSecret = this.ClientSecret, Username = login.Email, Password = login.Password, Scope = "openid profile email offline_access" }); return(new LoginResponse { JwtToken = res.AccessToken }); }
public async Task Can_authenticate_with_passwordless_email_code() { // Arrange var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // Arrange var authenticationResponse = await authenticationApiClient.AuthenticateAsync(new AuthenticationRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), Connection = "email", GrantType = "password", Scope = "openid", Username = "******", Password = "******" }); authenticationResponse.Should().NotBeNull(); }
public async Task Can_exchange_email_code_for_access_token() { var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL")); // Exchange the code var token = await authenticationApiClient.GetTokenAsync(new PasswordlessEmailTokenRequest { ClientId = GetVariable("AUTH0_PASSWORDLESSDEMO_CLIENT_ID"), ClientSecret = GetVariable("AUTH0_PASSWORDLESSDEMO_CLIENT_SECRET"), Code = "...", Audience = GetVariable("BRUCKE_MANAGEMENT_API_AUDIENCE"), Scope = "openid email", Email = email }); // Assert token.Should().NotBeNull(); }
public void Can_build_authorization_uri() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); var authorizationUrl = authenticationApiClient.BuildAuthorizationUrl() .WithResponseType(AuthorizationResponseType.Code) .WithClient("rLNKKMORlaDzrMTqGtSL9ZSXiBBksCQW") .WithConnection("google-oauth2") .WithRedirectUrl("http://www.jerriepelser.com/test") .WithScope("openid offline_access") .WithAudience("https://myapi.com/v2") .WithNonce("MyNonce") .WithState("MyState") .Build(); authorizationUrl.Should() .Be( new Uri("https://auth0-dotnet-integration-tests.auth0.com/authorize?response_type=code&client_id=rLNKKMORlaDzrMTqGtSL9ZSXiBBksCQW&connection=google-oauth2&redirect_uri=http%3A%2F%2Fwww.jerriepelser.com%2Ftest&scope=openid%20offline_access&audience=https%3A%2F%2Fmyapi.com%2Fv2&nonce=MyNonce&state=MyState")); }
private UserInfo GetUserInformation() { // Retrieve the access_token claim which we saved in the OnTokenValidated event var accessToken = User.Claims.FirstOrDefault(c => c.Type == "access_token")?.Value; // If we have an access_token, then retrieve the user's information if (string.IsNullOrEmpty(accessToken)) { return(null); } var apiClient = new AuthenticationApiClient(_valueRetrieval.Get("Auth0:Domain")); var userInfo = apiClient.GetUserInfoAsync(accessToken); userInfo.Wait(); var user = userInfo.Result; return(user); }
public async Task <ManagementApiClient> GetManagementApiClient() { var authenticationApiClient = new AuthenticationApiClient(new Uri(config.Domain)); if (token == null || token.IsExpired()) { // How to generate token: https://github.com/auth0/auth0.net/issues/171 var response = await authenticationApiClient.GetTokenAsync(new ClientCredentialsTokenRequest() { ClientId = config.ClientId, ClientSecret = config.ClientSecret, Audience = $"{config.Domain}api/v2/" }); token = new Auth0ApiToken(response); } return(new ManagementApiClient(token.AccessToken, new Uri($"{config.Domain}api/v2/"))); }
public async Task Can_obtain_token_info() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // First get the access token var token = await authenticationApiClient.GetAccessToken(new AccessTokenRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), Connection = "google-oauth2", AccessToken = accessToken, Scope = "openid" }); // Get the user info var user = await authenticationApiClient.GetTokenInfo(token.IdToken); user.Should().NotBeNull(); user.Email.Should().NotBeNull(); }
public async Task Passes_Token_Validation_With_CNAME() { // Arrange var authenticationApiClient = new AuthenticationApiClient(GetVariable("BRUCKE_AUTHENTICATION_API_URL")); // Act var authenticationResponse = await authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest { ClientId = GetVariable("BRUCKE_CLIENT_ID"), ClientSecret = GetVariable("BRUCKE_CLIENT_SECRET"), Realm = GetVariable("BRUCKE_CONNECTION_NAME"), Scope = "openid", Username = GetVariable("BRUCKE_USERNAME"), Password = GetVariable("BRUCKE_PASSWORD") }); var idTokenValidation = new IdTokenRequirements($"https://{GetVariable("BRUCKE_AUTHENTICATION_API_URL")}/", GetVariable("BRUCKE_CLIENT_ID"), TimeSpan.FromMinutes(1)); await idTokenValidation.AssertTokenMeetsRequirements(authenticationResponse.IdToken); }
public async Task Passes_Token_Validation() { // Arrange var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL")); // Act var authenticationResponse = await authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"), Realm = _connection.Name, Scope = "openid", Username = _user.Email, Password = Password }); var idTokenValidation = new IdTokenRequirements($"https://{GetVariable("AUTH0_AUTHENTICATION_API_URL")}/", GetVariable("AUTH0_CLIENT_ID"), TimeSpan.FromMinutes(1)); await idTokenValidation.AssertTokenMeetsRequirements(authenticationResponse.IdToken); }
public async Task Can_authenticate_against_Auth0() { // Arrange var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // Act var authenticationResponse = await authenticationApiClient.Authenticate(new AuthenticationRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), Connection = connection.Name, GrantType = "password", Scope = "openid", Username = user.Email, Password = "******" }); // Assert authenticationResponse.Should().NotBeNull(); }
private async Task <AccessTokenResponse> GetRefreshedToken(string refreshToken) { string auth0Domain = ConfigurationManager.AppSettings["auth0:Domain"]; string auth0ClientId = ConfigurationManager.AppSettings["auth0:ClientId"]; string auth0ClientSecret = ConfigurationManager.AppSettings["auth0:ClientSecret"]; using (var client = new AuthenticationApiClient(auth0Domain)) { var refreshTokenRequest = new RefreshTokenRequest { RefreshToken = refreshToken, ClientId = auth0ClientId, ClientSecret = auth0ClientSecret }; var tokenResult = await client.GetTokenAsync(refreshTokenRequest); return(tokenResult); } }
public async Task Can_launch_sms_flow() { Skip.If(string.IsNullOrEmpty(phone), "AUTH0_PASSWORDLESSDEMO_PHONE not set"); // Arrange using (var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_PASSWORDLESSDEMO_AUTHENTICATION_API_URL"))) { // Act var request = new PasswordlessSmsRequest { ClientId = GetVariable("AUTH0_PASSWORDLESSDEMO_CLIENT_ID"), ClientSecret = GetVariable("AUTH0_PASSWORDLESSDEMO_CLIENT_SECRET"), PhoneNumber = phone }; var response = await authenticationApiClient.StartPasswordlessSmsFlowAsync(request); response.Should().NotBeNull(); response.PhoneNumber.Should().Be(request.PhoneNumber); } }
public async Task Can_obtain_token_info() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // First get the access token var token = await authenticationApiClient.GetAccessTokenAsync(new AccessTokenRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), Connection = "google-oauth2", AccessToken = accessToken, Scope = "openid" }); // Get the user info var user = await authenticationApiClient.GetTokenInfoAsync(token.IdToken); user.Should().NotBeNull(); user.Email.Should().NotBeNull(); }
public ActionResult Login(string returnUrl) { var isAuthenticated = User.Identity.IsAuthenticated; var client = new AuthenticationApiClient( new Uri(string.Format("https://{0}", ConfigurationManager.AppSettings["auth0:Domain"]))); var request = this.Request; var redirectUri = new UriBuilder(request.Url.Scheme, request.Url.Host, this.Request.Url.IsDefaultPort ? -1 : request.Url.Port, "LoginCallback.ashx"); var authorizeUrlBuilder = client.BuildAuthorizationUrl() .WithClient(ConfigurationManager.AppSettings["auth0:ClientId"]) .WithRedirectUrl(redirectUri.ToString()) .WithResponseType(AuthorizationResponseType.Code) .WithScope("openid profile") .WithConnection("Auth0-MJS-Test") //.WithValue("prompt","none") // adding this audience will cause Auth0 to use the OIDC-Conformant pipeline // you don't need it if your client is flagged as OIDC-Conformant (Advance Settings | OAuth) //.WithAudience("https://" + @ConfigurationManager.AppSettings["auth0:Domain"] + "/userinfo") ; if (!string.IsNullOrEmpty(returnUrl)) { var state = "ru=" + HttpUtility.UrlEncode(returnUrl); authorizeUrlBuilder.WithState(state); } try { var redirectUrl = authorizeUrlBuilder.Build().ToString(); var redirect = new RedirectResult(redirectUrl); //var redirect = new RedirectResult(authorizeUrlBuilder.Build().ToString()); return(redirect); } catch (Exception e) { Console.WriteLine(e); throw; } }
public static async Task AuthenticationApiMainAsync(string[] args) { try { string token = ""; var handler = new HttpClientHandler { Proxy = new WebProxy() }; var api = new AuthenticationApiClient("jerrie.auth0.com"); var tokenInfo = await api.GetTokenInfoAsync(token); Console.WriteLine(tokenInfo.Email); } catch (Exception ex) { throw; } }
public async Task Can_obtain_user_info() { var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL")); // First get the access token var token = await authenticationApiClient.AuthenticateAsync(new AuthenticationRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"), Realm = connection.Name, Username = newUser.Email, Password = "******", Scope = "openid profile" }); // Get the user info var user = await authenticationApiClient.GetUserInfoAsync(token.AccessToken); user.Should().NotBeNull(); user.UserId.Should().NotBeNull(); }
public async Task Passes_Token_Validation_With_CNAME() { // Arrange using (var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"))) { // Act var authenticationResponse = await authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"), Realm = _connection.Name, Scope = "openid", Username = _user.Email, Password = Password }); var issuer = $"https://{GetVariable("AUTH0_AUTHENTICATION_API_URL")}/"; var requirements = new IdTokenRequirements(JwtSignatureAlgorithm.RS256, issuer, GetVariable("AUTH0_CLIENT_ID"), TimeSpan.FromMinutes(1)); await new IdTokenValidator().Assert(requirements, authenticationResponse.IdToken, GetVariable("AUTH0_CLIENT_SECRET")); } }
public async Task <AuthorisationResult> ExchangeCodeForTokenAsync() { var apiClient = new AuthenticationApiClient(Config.TenantDomain); try { TokenResponse = await apiClient.GetTokenAsync(new AuthorizationCodeTokenRequest() { ClientId = Config.ClientId, ClientSecret = Config.ClientSecret, Code = VerificationCode, RedirectUri = RedirectUrl }); } catch (AggregateException ex) { (new ExceptionLogController()).AddLog(ex); } return((TokenResponse == null) ? AuthorisationResult.Denied : AuthorisationResult.Authorized); }
private static async Task <string> GetAccessTokenAsync(string clientId, string clientSecret, string audience, string domain) { try { var authenticationApiClient = new AuthenticationApiClient(domain); // Get the access token var token = await authenticationApiClient.GetTokenAsync(new ClientCredentialsTokenRequest { ClientId = clientId, ClientSecret = clientSecret, Audience = audience }).ConfigureAwait(false); return(token.AccessToken); } catch (Exception) { return(null); } }
public async Task Can_request_token_using_device_code() { var mockHandler = new Mock <HttpMessageHandler>(MockBehavior.Strict); var accessToken = "TEST_ACCESSTOKEN"; var response = new AccessTokenResponse { AccessToken = accessToken }; var domain = GetVariable("AUTH0_AUTHENTICATION_API_URL"); var deviceCode = "TEST_CODE"; var expectedParams = new Dictionary <string, string> { { "grant_type", "urn:ietf:params:oauth:grant-type:device_code" }, { "device_code", deviceCode }, { "client_id", GetVariable("AUTH0_CLIENT_ID") } }; mockHandler.Protected() .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.Is <HttpRequestMessage>(req => req.RequestUri.ToString() == $"https://{domain}/oauth/token" && ValidateRequestContent(req, expectedParams)), ItExpr.IsAny <CancellationToken>() ) .ReturnsAsync(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(response), Encoding.UTF8, "application/json"), }); var httpClient = new HttpClient(mockHandler.Object); var authenticationApiClient = new AuthenticationApiClient(domain, new HttpClientAuthenticationConnection(httpClient)); var tokenReponse = await authenticationApiClient.GetTokenAsync(new DeviceCodeTokenRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), DeviceCode = deviceCode }); tokenReponse.Should().NotBeNull(); tokenReponse.AccessToken.Should().Equals(accessToken); }
public async Task Can_start_device_flow() { var mockHandler = new Mock <HttpMessageHandler>(MockBehavior.Strict); var deviceCode = "TEST_CODE"; var response = new DeviceCodeResponse { DeviceCode = deviceCode }; var domain = GetVariable("AUTH0_AUTHENTICATION_API_URL"); var expectedParams = new Dictionary <string, string> { { "audience", "Test" }, { "scope", "openid profile" }, { "client_id", GetVariable("AUTH0_CLIENT_ID") } }; mockHandler.Protected() .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.Is <HttpRequestMessage>(req => req.RequestUri.ToString() == $"https://{domain}/oauth/device/code" && ValidateRequestContent(req, expectedParams)), ItExpr.IsAny <CancellationToken>() ) .ReturnsAsync(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(response), Encoding.UTF8, "application/json"), }); var httpClient = new HttpClient(mockHandler.Object); var authenticationApiClient = new AuthenticationApiClient(domain, new HttpClientAuthenticationConnection(httpClient)); var tokenReponse = await authenticationApiClient.StartDeviceFlowAsync(new DeviceCodeRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), Scope = "openid profile", Audience = "Test" }); tokenReponse.Should().NotBeNull(); tokenReponse.DeviceCode.Should().Equals(deviceCode); }
private static async Task Main() { const string auth0Domain = @"mova-user-id-test.auth0.com"; var httpClient = new HttpClient(); var auth = new AuthenticationApiClient( domain: auth0Domain, connection: new HttpClientAuthenticationConnection(httpClient: httpClient) ); var token = await auth.GetTokenAsync(request : new ClientCredentialsTokenRequest { ClientId = "Z7gyil733avwkafs5Aeky3XMmLtBURqy", // ReSharper disable StringLiteralTypo ClientSecret = "wISWqDR-LN-vjAuux10w-lTYayKsUDrMwfee2QtNBLFrEianzertZjZrUaj26P-n", // ReSharper restore StringLiteralTypo Audience = "https://mova-user-id-test.auth0.com/api/v2/", SigningAlgorithm = JwtSignatureAlgorithm.RS256 }); var api = new ManagementApiClient( token: token.AccessToken, domain: auth0Domain, connection: new HttpClientManagementConnection(httpClient: httpClient) ); foreach ( var u in await api.Users.GetAllAsync( request: new GetUsersRequest(), pagination: new PaginationInfo()) ) { await api.Users.DeleteAsync(id : u.UserId); } var users = new[]
public async Task Can_authenticate_against_Auth0() { // Arrange var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // Act var authenticationResponse = await authenticationApiClient.AuthenticateAsync(new AuthenticationRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), Connection = connection.Name, GrantType = "password", Scope = "openid", Username = user.Email, Password = "******" }); // Assert authenticationResponse.Should().NotBeNull(); authenticationResponse.TokenType.Should().NotBeNull(); authenticationResponse.AccessToken.Should().NotBeNull(); authenticationResponse.IdToken.Should().NotBeNull(); authenticationResponse.RefreshToken.Should().BeNull(); // No refresh token if offline access was not requested }
public void Can_build_wsfed_with_client() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); var wsfedUrl = authenticationApiClient.BuildWsFedUrl() .WithClient("my-client-id") .Build(); wsfedUrl.Should().Be(@"https://auth0-dotnet-integration-tests.auth0.com/wsfed/my-client-id"); }
public async Task Can_exchange_authorization_code_for_access_token() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // Exchange the authorization code var token = await authenticationApiClient.ExchangeCodeForAccessToken(new ExchangeCodeRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"), RedirectUri = "http://www.blah.com/test", AuthorizationCode = "AaBhdAOl4OKvjX2I" }); // Assert token.Should().NotBeNull(); }
public async Task Can_authenticate_user_with_plus_in_username() { // Arrange var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // Act var authenticationResponse = await authenticationApiClient.AuthenticateAsync(new AuthenticationRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), Connection = connection.Name, GrantType = "password", Scope = "openid", Username = plusUser.Email, Password = "******" }); // Assert authenticationResponse.Should().NotBeNull(); authenticationResponse.TokenType.Should().NotBeNull(); authenticationResponse.AccessToken.Should().NotBeNull(); authenticationResponse.IdToken.Should().NotBeNull(); }
public async Task Returns_username_and_password_login_form() { // Arrange var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // Act var authenticationResponse = await authenticationApiClient.UsernamePasswordLoginAsync(new UsernamePasswordLoginRequest { ClientId = GetVariable("AUTH0_CLIENT_ID"), Connection = connection.Name, Scope = "openid", Username = user.Email, Password = "******", RedirectUri = "http://www.blah.com/test" }); // Assert authenticationResponse.Should().NotBeNull(); authenticationResponse.HtmlForm.Should().NotBeNull(); // Load the form, and submit it var configuration = Configuration.Default.WithDefaultLoader().WithCookies(); var context = BrowsingContext.New(configuration); await context.OpenAsync(request => { request.Content(authenticationResponse.HtmlForm); }); await context.Active.QuerySelector<IHtmlFormElement>("form").Submit(); // Extract the URL and query from the postback var uri = new Uri(context.Active.Url); var code = HttpUtility.ParseQueryString(uri.Query)["code"]; // Assert that callback is made and code is passed back code.Should().NotBeNull(); }
public void Can_build_wsfed_with_wxtx_string() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); var wsfedUrl = authenticationApiClient.BuildWsFedUrl() .WithWctx("xcrf=abc&ru=/foo") .Build(); wsfedUrl.Should().Be(@"https://auth0-dotnet-integration-tests.auth0.com/wsfed?wctx=xcrf%3Dabc%26ru%3D%2Ffoo"); }
public void Can_build_wsfed_with_whr() { var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); var wsfedUrl = authenticationApiClient.BuildWsFedUrl() .WithWhr("urn:my-connection-name") .Build(); wsfedUrl.Should().Be(@"https://auth0-dotnet-integration-tests.auth0.com/wsfed?whr=urn:my-connection-name"); }