@Test public void configureWhenCustomAuthorizationRequestResolverSetThenAuthorizationRequestIncludesCustomParameters() throws Exception { // Override default resolver OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = authorizationRequestResolver; authorizationRequestResolver = mock(OAuth2AuthorizationRequestResolver.class); when(authorizationRequestResolver.resolve(any())).thenAnswer(invocation -> defaultAuthorizationRequestResolver.resolve(invocation.getArgument(0))); this.spring.register(OAuth2ClientConfig.class).autowire(); this.mockMvc.perform(get("/oauth2/authorization/registration-1")) .andExpect(status().is3xxRedirection()) .andReturn(); verify(authorizationRequestResolver).resolve(any()); }
@Test public void loadConfigWhenRequestAuthenticateThenAuthenticationEventPublished() throws Exception { this.spring.register(InMemoryAuthWithWebSecurityConfigurerAdapter.class).autowire(); this.mockMvc.perform(formLogin()) .andExpect(status().is3xxRedirection()); assertThat(InMemoryAuthWithWebSecurityConfigurerAdapter.EVENTS).isNotEmpty(); assertThat(InMemoryAuthWithWebSecurityConfigurerAdapter.EVENTS).hasSize(1); }
@Test public void annotationExplicitWhenNotAuthenticatedThenLoginRequested() throws Exception { this.mockMvc.perform(get("/annotation/explicit")) .andExpect(status().is3xxRedirection()); } }
@Test public void configureWhenRequestCacheProvidedAndClientAuthorizationRequiredExceptionThrownThenRequestCacheUsed() throws Exception { this.spring.register(OAuth2ClientConfig.class).autowire(); MvcResult mvcResult = this.mockMvc.perform(get("/resource1").with(user("user1"))) .andExpect(status().is3xxRedirection()) .andReturn(); assertThat(mvcResult.getResponse().getRedirectedUrl()).matches("https://provider.com/oauth2/authorize\\?" + "response_type=code&client_id=client-1&" + "scope=user&state=.{15,}&" + "redirect_uri=http://localhost/client-1"); verify(requestCache).saveRequest(any(HttpServletRequest.class), any(HttpServletResponse.class)); }
@Test public void loadConfigWhenInMemoryConfigureGlobalThenPasswordUpgraded() throws Exception { this.spring.register(InMemoryConfigureGlobalConfig.class).autowire(); this.mockMvc.perform(formLogin()) .andExpect(status().is3xxRedirection()); UserDetailsService uds = this.spring.getContext() .getBean(UserDetailsService.class); assertThat(uds.loadUserByUsername("user").getPassword()).startsWith("{bcrypt}"); }
@Test public void loadConfigWhenInMemoryConfigureProtectedThenPasswordUpgraded() throws Exception { this.spring.register(InMemoryConfigureProtectedConfig.class).autowire(); this.mockMvc.perform(formLogin()) .andExpect(status().is3xxRedirection()); UserDetailsService uds = this.spring.getContext() .getBean(UserDetailsService.class); assertThat(uds.loadUserByUsername("user").getPassword()).startsWith("{bcrypt}"); }
@Test void testSilentAuthentication_RuntimeException_displaysErrorFragment() throws Exception { UaaAuthorizationEndpoint uaaAuthorizationEndpoint = (UaaAuthorizationEndpoint) webApplicationContext.getBean("uaaAuthorizationEndpoint"); OpenIdSessionStateCalculator backupCalculator = uaaAuthorizationEndpoint.getOpenIdSessionStateCalculator(); try { OpenIdSessionStateCalculator openIdSessionStateCalculator = mock(OpenIdSessionStateCalculator.class); uaaAuthorizationEndpoint.setOpenIdSessionStateCalculator(openIdSessionStateCalculator); when(openIdSessionStateCalculator.calculate(anyString(), anyString(), anyString())).thenThrow(RuntimeException.class); MockHttpSession session = new MockHttpSession(); login(session); mockMvc.perform( get("/oauth/authorize?response_type=token&scope=openid&client_id=ant&prompt=none&redirect_uri=http://example.com/with/path.html") .session(session) ) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("http://example.com/with/path.html#error=internal_server_error")); } finally { uaaAuthorizationEndpoint.setOpenIdSessionStateCalculator(backupCalculator); } }
@Test void loginRedirects() throws Exception { MockHttpServletRequestBuilder getRequest = get("/login") .accept(MediaType.TEXT_HTML); mockMvc.perform(getRequest) .andExpect(status().is3xxRedirection()); }
@Test void samlMetadataRedirects() throws Exception { MockHttpServletRequestBuilder getRequest = get("/saml/metadata") .accept(MediaType.ALL); mockMvc.perform(getRequest) .andExpect(status().is3xxRedirection()); } }
@Test public void configureWhenAuthorizationCodeRequestThenRedirectForAuthorization() throws Exception { this.spring.register(OAuth2ClientConfig.class).autowire(); MvcResult mvcResult = this.mockMvc.perform(get("/oauth2/authorization/registration-1")) .andExpect(status().is3xxRedirection()) .andReturn(); assertThat(mvcResult.getResponse().getRedirectedUrl()).matches("https://provider.com/oauth2/authorize\\?" + "response_type=code&client_id=client-1&" + "scope=user&state=.{15,}&" + "redirect_uri=http://localhost/client-1"); }
@Test // http@entry-point-ref public void configureWhenAuthenticationEntryPointSetAndRequestUnauthorizedThenRedirectedToAuthenticationEntryPoint() throws Exception { this.spring.register(EntryPointRefConfig.class).autowire(); this.mockMvc.perform(get("/")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrlPattern("**/entry-point")); }
@Test public void statusRanges() throws Exception { for (HttpStatus status : HttpStatus.values()) { MockHttpServletResponse response = new MockHttpServletResponse(); response.setStatus(status.value()); MvcResult mvcResult = new StubMvcResult(request, null, null, null, null, null, response); switch (status.series().value()) { case 1: this.matchers.is1xxInformational().match(mvcResult); break; case 2: this.matchers.is2xxSuccessful().match(mvcResult); break; case 3: this.matchers.is3xxRedirection().match(mvcResult); break; case 4: this.matchers.is4xxClientError().match(mvcResult); break; case 5: this.matchers.is5xxServerError().match(mvcResult); break; default: fail("Unexpected range for status code value " + status); } } }
public static String performMfaPostVerifyWithCode(int code, MockMvc mvc, MockHttpSession session, String host) throws Exception { return mvc.perform(post("/login/mfa/verify.do") .param("code", Integer.toString(code)) .header("Host", host) .session(session) .with(cookieCsrf())) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/login/mfa/completed")) .andReturn().getResponse().getRedirectedUrl(); }
@Test void gettingOpenIdToken_andNoAccessToken_withImplicitGrantType() throws Exception { String clientId = "implicit-client" + this.generator.generate(); setUpClients(clientId, "", "openid", "implicit,refresh_token", true, TEST_REDIRECT_URI); ScimUser developer = setUpUser("testuser" + this.generator.generate(), "openid", OriginKeys.UAA, IdentityZoneHolder.get().getId()); logUserInTwice(developer.getId()); MockHttpSession session = new MockHttpSession(); setAuthentication(session, developer); MvcResult result = mockMvc.perform(get("/oauth/authorize") .session(session) .param(OAuth2Utils.RESPONSE_TYPE, "id_token") .param(OAuth2Utils.STATE, "random-state") .param(OAuth2Utils.CLIENT_ID, clientId) .param(OAuth2Utils.REDIRECT_URI, TEST_REDIRECT_URI)) .andExpect(status().is3xxRedirection()) .andReturn(); URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map<String, List<String>> tokenResponse = splitQuery(url); assertNotNull(tokenResponse.get(OAuth2Utils.STATE)); assertNotNull(tokenResponse.get("id_token")); assertEquals("random-state", tokenResponse.get(OAuth2Utils.STATE).get(0)); }
@Test public void testQRCodeCannotBeSubmittedWithoutLoggedInSession() throws Exception { getMockMvc().perform(post("/login/mfa/verify.do") .param("code", "1234") .with(cookieCsrf())) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("http://localhost/login")); }
.with(authentication(authentication)) .session(session)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("http://localhost/client-1"));
this.mvc.perform(get("/logout")).andExpect(status().is3xxRedirection());
@Test void invalidScopeErrorMessageIsNotShowingAllUserScopes() throws Exception { String clientId = "testclient" + generator.generate(); String scopes = "openid,password.write,cloud_controller.read,scim.userids,password.write,something.else"; setUpClients(clientId, scopes, scopes, GRANT_TYPE_AUTHORIZATION_CODE, true); String username = "testuser" + generator.generate(); ScimUser developer = setUpUser(username, "openid", OriginKeys.UAA, IdentityZoneHolder.getUaaZone().getId()); MockHttpSession session = getAuthenticatedSession(developer); String state = generator.generate(); MockHttpServletRequestBuilder authRequest = get("/oauth/authorize") .with(httpBasic(clientId, SECRET)) .session(session) .param(OAuth2Utils.RESPONSE_TYPE, "code") .param(SCOPE, "something.else") .param(OAuth2Utils.STATE, state) .param(OAuth2Utils.CLIENT_ID, clientId) .param(OAuth2Utils.REDIRECT_URI, TEST_REDIRECT_URI); MvcResult mvcResult = mockMvc.perform(authRequest).andExpect(status().is3xxRedirection()).andReturn(); UriComponents locationComponents = UriComponentsBuilder.fromUri(URI.create(mvcResult.getResponse().getHeader("Location"))).build(); MultiValueMap<String, String> queryParams = locationComponents.getQueryParams(); String errorMessage = URIUtil.encodeQuery("[something.else] is invalid. This user is not allowed any of the requested scopes"); assertTrue(!queryParams.containsKey("scope")); assertEquals(errorMessage, queryParams.getFirst("error_description")); }
@Test public void testConfiguredHomePage() throws Exception { mockMvc.perform(get("/home")) .andExpect(status().isOk()); String customHomePage = "http://custom.home/page"; IdentityZoneHolder.get().getConfig().getLinks().setHomeRedirect(customHomePage); mockMvc.perform(get("/home")) .andExpect(status().is3xxRedirection()) .andExpect(header().string("Location", customHomePage)); IdentityZone zone = MultitenancyFixture.identityZone("zone", "zone"); zone.setConfig(new IdentityZoneConfiguration()); IdentityZoneHolder.set(zone); mockMvc.perform(get("/home")) .andExpect(status().isOk()); zone.getConfig().getLinks().setHomeRedirect(customHomePage); mockMvc.perform(get("/home")) .andExpect(status().is3xxRedirection()) .andExpect(header().string("Location", customHomePage)); }
@Test void testAuthorizationCode_ShouldNot_Throw_500_If_Client_Doesnt_Exist() throws Exception { String redirectUri = "https://example.com/"; String clientId = "nonexistent-" + generator.generate(); String userScopes = "openid"; String state = generator.generate(); MockHttpServletRequestBuilder authRequest = get("/oauth/authorize") .accept(MediaType.TEXT_HTML) .param(OAuth2Utils.RESPONSE_TYPE, "code id_token") .param(SCOPE, userScopes) .param(OAuth2Utils.STATE, state) .param(OAuth2Utils.CLIENT_ID, clientId) .param(OAuth2Utils.REDIRECT_URI, redirectUri); MvcResult result = mockMvc.perform(authRequest).andExpect(status().is3xxRedirection()).andReturn(); String location = result.getResponse().getHeader("Location"); HttpSession session = result.getRequest().getSession(false); MockHttpServletRequestBuilder login = get("/login") .accept(MediaType.TEXT_HTML) .session((MockHttpSession) session); mockMvc.perform(login).andExpect(status().isOk()); }