org.springframework.http.HttpStatus.FOUND

Here are the examples of the java api org.springframework.http.HttpStatus.FOUND taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

55 Examples 7

19 View Source File : SampleOAuth2ClientApplicationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void everythingShouldRedirectToLogin() {
    ResponseEnreplacedy<String> enreplacedy = this.restTemplate.getForEnreplacedy("/", String.clreplaced);
    replacedertThat(enreplacedy.getStatusCode()).isEqualTo(HttpStatus.FOUND);
    replacedertThat(enreplacedy.getHeaders().getLocation()).isEqualTo(URI.create("http://localhost:" + this.port + "/login"));
}

19 View Source File : UrlBasedViewResolverTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void customizedRedirectView() throws Exception {
    this.resolver.setRedirectViewProvider(url -> new RedirectView(url, HttpStatus.FOUND));
    Mono<View> mono = this.resolver.resolveViewName("redirect:foo", Locale.US);
    StepVerifier.create(mono).consumeNextWith(view -> {
        replacedertEquals(RedirectView.clreplaced, view.getClreplaced());
        RedirectView redirectView = (RedirectView) view;
        replacedertEquals("foo", redirectView.getUrl());
        replacedertEquals(HttpStatus.FOUND, redirectView.getStatusCode());
    }).expectComplete().verify(Duration.ZERO);
}

19 View Source File : StatusResultMatchers.java
License : MIT License
Project Creator : Vip-Augus

/**
 * replacedert the response status code is {@code HttpStatus.FOUND} (302).
 */
public ResultMatcher isFound() {
    return matcher(HttpStatus.FOUND);
}

19 View Source File : StatusAssertions.java
License : MIT License
Project Creator : Vip-Augus

/**
 * replacedert the response status code is {@code HttpStatus.FOUND} (302).
 */
public WebTestClient.ResponseSpec isFound() {
    return replacedertStatusAndReturn(HttpStatus.FOUND);
}

19 View Source File : SampleGithubApplicationTests.java
License : Apache License 2.0
Project Creator : spring-projects

@Test
public void everythingIsSecuredByDefault() throws Exception {
    ResponseEnreplacedy<Void> enreplacedy = this.restTemplate.getForEnreplacedy("/", Void.clreplaced);
    replacedertThat(enreplacedy.getStatusCode()).isEqualTo(HttpStatus.FOUND);
    replacedertThat(enreplacedy.getHeaders().getLocation().toString()).startsWith("https://github.com/login/oauth");
}

19 View Source File : RedirectToGatewayFilterFactoryTests.java
License : Apache License 2.0
Project Creator : spring-cloud

@Test
public void redirectToFilterWorks() {
    testClient.get().uri("/").header("Host", "www.redirectto.org").exchange().expectStatus().isEqualTo(HttpStatus.FOUND).expectHeader().valueEquals(HttpHeaders.LOCATION, "https://example.org");
}

19 View Source File : RedirectToGatewayFilterFactoryTests.java
License : Apache License 2.0
Project Creator : spring-cloud

@Test
public void redirectToRelativeUrlFilterWorks() {
    testClient.get().uri("/").header("Host", "www.relativeredirect.org").exchange().expectStatus().isEqualTo(HttpStatus.FOUND).expectHeader().valueEquals(HttpHeaders.LOCATION, "/index.html#/customers");
}

19 View Source File : AbstractOpenApiGeneratorWebCustomPathIntTest.java
License : Apache License 2.0
Project Creator : qaware

private void replacedertRedirectEnreplacedy(ResponseEnreplacedy<String> redirectEnreplacedy) {
    replacedertThat(redirectEnreplacedy.getStatusCode()).isEqualTo(HttpStatus.FOUND);
    replacedertThat(redirectEnreplacedy.getHeaders()).contains(entry("Location", singletonList(buildHost("https://forwarded-host:1337") + PATH_TO_INDEX_HTML)));
}

19 View Source File : WxMediaResponseBodyAdvice.java
License : Apache License 2.0
Project Creator : FastBootWeixin

@Override
public WxMediaResource beforeBodyWrite(WxMediaResource body, MethodParameter returnType, MediaType selectedContentType, Clreplaced<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    if (body == null || !body.isUrlMedia()) {
        return body;
    }
    try {
        response.getHeaders().setLocation(body.getURI());
        response.setStatusCode(HttpStatus.FOUND);
        return null;
    } catch (IOException e) {
        throw new WxAppException("系统异常");
    }
}

18 View Source File : RedirectViewTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void customStatusCode() {
    String url = "https://url.somewhere.com";
    RedirectView view = new RedirectView(url, HttpStatus.FOUND);
    view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange).block();
    replacedertEquals(HttpStatus.FOUND, this.exchange.getResponse().getStatusCode());
    replacedertEquals(URI.create(url), this.exchange.getResponse().getHeaders().getLocation());
}

18 View Source File : FileUploadIntegrationTests.java
License : Apache License 2.0
Project Creator : usdot-jpo-ode

@Ignore
@Test
public void shouldUploadFile() throws Exception {
    ClreplacedPathResource resource = new ClreplacedPathResource("testupload.txt", getClreplaced());
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
    map.add("file", resource);
    ResponseEnreplacedy<String> response = this.restTemplate.postForEnreplacedy("/", map, String.clreplaced);
    replacedertThat(response.getStatusCode()).isEqualByComparingTo(HttpStatus.FOUND);
    replacedertThat(response.getHeaders().getLocation().toString()).startsWith("http://localhost:" + this.port + "/");
    then(storageService).should().store(any(MultipartFile.clreplaced), "obulog");
}

private void doFilterWhenRequestInvalidParameterThenRedirect(MockHttpServletRequest request, String parameterName, String errorCode, String errorUri, Consumer<MockHttpServletRequest> requestConsumer) throws Exception {
    requestConsumer.accept(request);
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.clreplaced);
    this.filter.doFilter(request, response, filterChain);
    verifyNoInteractions(filterChain);
    replacedertThat(response.getStatus()).isEqualTo(HttpStatus.FOUND.value());
    replacedertThat(response.getRedirectedUrl()).matches("https://example.com\\?" + "error=" + errorCode + "&" + "error_description=OAuth%202.0%20Parameter:%20" + parameterName + "&" + "error_uri=" + errorUri + "&" + "state=state");
}

18 View Source File : ZuulApplicationTests.java
License : Apache License 2.0
Project Creator : spring-cloud

@Test
@Ignore
public void useRestTemplate() throws Exception {
    ResponseEnreplacedy<String> enreplacedy = this.restTemplate.getForEnreplacedy("http://localhost:" + this.port, String.clreplaced);
    replacedertEquals(HttpStatus.FOUND, enreplacedy.getStatusCode());
    replacedertEquals("http://localhost:" + this.port + "/login", enreplacedy.getHeaders().getLocation().toString());
}

18 View Source File : UrlBasedViewResolverTests.java
License : Apache License 2.0
Project Creator : SourceHot

@Test
public void customizedRedirectView() throws Exception {
    this.resolver.setRedirectViewProvider(url -> new RedirectView(url, HttpStatus.FOUND));
    Mono<View> mono = this.resolver.resolveViewName("redirect:foo", Locale.US);
    StepVerifier.create(mono).consumeNextWith(view -> {
        replacedertThat(view.getClreplaced()).isEqualTo(RedirectView.clreplaced);
        RedirectView redirectView = (RedirectView) view;
        replacedertThat(redirectView.getUrl()).isEqualTo("foo");
        replacedertThat(redirectView.getStatusCode()).isEqualTo(HttpStatus.FOUND);
    }).expectComplete().verify(Duration.ZERO);
}

18 View Source File : OpenApiSwaggerUiWebFluxAutoConfiguration.java
License : Apache License 2.0
Project Creator : qaware

@Bean
@Hidden
public RouterFunction<ServerResponse> redirectToSwaggerUiIndexHtml(SwaggerUiSupport swaggerUiSupport) {
    return route(GET(swaggerUiSupport.getUiPath()), req -> ServerResponse.status(HttpStatus.FOUND).location(req.uriBuilder().replacePath(swaggerUiSupport.getRedirectPath()).build()).build());
}

18 View Source File : ShortURLController.java
License : MIT License
Project Creator : penguin-statistics

private ResponseEnreplacedy<Void> redirect(String to) {
    return ResponseEnreplacedy.status(HttpStatus.FOUND).location(URI.create(to)).build();
}

18 View Source File : RedirectViewTests.java
License : MIT License
Project Creator : mindcarver

@Test
public void customStatusCode() {
    String url = "http://url.somewhere.com";
    RedirectView view = new RedirectView(url, HttpStatus.FOUND);
    view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange).block();
    replacedertEquals(HttpStatus.FOUND, this.exchange.getResponse().getStatusCode());
    replacedertEquals(URI.create(url), this.exchange.getResponse().getHeaders().getLocation());
}

18 View Source File : JenkinsRequestMockProvider.java
License : MIT License
Project Creator : ls1intum

public void mockEnablePlan(String projectKey, String planKey) throws URISyntaxException, IOException {
    final var uri = UriComponentsBuilder.fromUri(jenkinsServerUrl.toURI()).pathSegment("job", projectKey, "job", planKey, "enable").build().toUri();
    mockServer.expect(requestTo(uri)).andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.FOUND));
}

18 View Source File : FlowableUiApplicationSecurityTest.java
License : Apache License 2.0
Project Creator : flowable

@Test
public void nonAuthenticatedUserShouldBeRedirectedToLogin() {
    String rootUrl = "http://localhost:" + serverPort + "/flowable-ui/";
    ResponseEnreplacedy<String> result = restTemplate.getForEnreplacedy(rootUrl, String.clreplaced);
    replacedertThat(result.getStatusCode()).as("GET app definitions").isEqualTo(HttpStatus.FOUND);
    replacedertThat(result.getHeaders().getFirst(HttpHeaders.LOCATION)).as("redirect location").isEqualTo("http://localhost:" + serverPort + "/flowable-ui/idm/#/login");
}

18 View Source File : UrlController.java
License : MIT License
Project Creator : AnteMarin

@ApiOperation(value = "Redirect", notes = "Finds original url from short url and redirects")
@GetMapping(value = "{shortUrl}")
@Cacheable(value = "urls", key = "#shortUrl", sync = true)
public ResponseEnreplacedy<Void> getAndRedirect(@PathVariable String shortUrl) {
    var url = urlService.getOriginalUrl(shortUrl);
    return ResponseEnreplacedy.status(HttpStatus.FOUND).location(URI.create(url)).build();
}

17 View Source File : AppController.java
License : MIT License
Project Creator : woowacourse-teams

@GetMapping("/races/{raceId}")
public ResponseEnreplacedy<Void> redirectRacePage(@PathVariable final String raceId, final HttpServletResponse response) throws IOException {
    response.sendRedirect(String.format("intent:#Intent;scheme=peloton:///home/races/%s;package=com.woowaguys.peloton;end", raceId));
    return ResponseEnreplacedy.status(HttpStatus.FOUND).build();
}

17 View Source File : SpringDocApp20Test.java
License : Apache License 2.0
Project Creator : springdoc

@Test
public void testIndex() throws Exception {
    HttpStatus httpStatusMono = webClient.get().uri("/test/swagger-ui.html").exchangeToMono(clientResponse -> Mono.just(clientResponse.statusCode())).block();
    replacedertThat(httpStatusMono).isEqualTo(HttpStatus.FOUND);
    httpStatusMono = webClient.get().uri("/webjars/swagger-ui/index.html").exchangeToMono(clientResponse -> Mono.just(clientResponse.statusCode())).block();
    replacedertThat(httpStatusMono).isEqualTo(HttpStatus.OK);
    String contentreplacedtring = webClient.get().uri("/test/v3/api-docs/swagger-config").retrieve().bodyToMono(String.clreplaced).block();
    String expected = getContent("results/app20-1.json");
    replacedertEquals(expected, contentreplacedtring, true);
}

17 View Source File : SpringDocApp19Test.java
License : Apache License 2.0
Project Creator : springdoc

@Test
public void testIndex() throws Exception {
    HttpStatus httpStatusMono = webClient.get().uri("/").exchangeToMono(clientResponse -> Mono.just(clientResponse.statusCode())).block();
    replacedertThat(httpStatusMono).isEqualTo(HttpStatus.FOUND);
    httpStatusMono = webClient.get().uri("/webjars/swagger-ui/index.html").exchangeToMono(clientResponse -> Mono.just(clientResponse.statusCode())).block();
    replacedertThat(httpStatusMono).isEqualTo(HttpStatus.OK);
    String contentreplacedtring = webClient.get().uri("/v3/api-docs/swagger-config").retrieve().bodyToMono(String.clreplaced).block();
    String expected = getContent("results/app19-1.json");
    replacedertEquals(expected, contentreplacedtring, true);
}

17 View Source File : SpringDocApp18Test.java
License : Apache License 2.0
Project Creator : springdoc

@Test
public void testIndexActuator() throws Exception {
    HttpStatus httpStatusMono = webClient.get().uri("/test/doreplacedentation/swagger-ui.html").exchangeToMono(clientResponse -> Mono.just(clientResponse.statusCode())).block();
    replacedertThat(httpStatusMono).isEqualTo(HttpStatus.FOUND);
    httpStatusMono = webClient.get().uri("/test/doreplacedentation/webjars-pref/swagger-ui/index.html").exchangeToMono(clientResponse -> Mono.just(clientResponse.statusCode())).block();
    replacedertThat(httpStatusMono).isEqualTo(HttpStatus.OK);
    String contentreplacedtring = webClient.get().uri("/test/doreplacedentation/v3/api-docs/swagger-config").retrieve().bodyToMono(String.clreplaced).block();
    String expected = getContent("results/app18-1.json");
    replacedertEquals(expected, contentreplacedtring, true);
}

17 View Source File : SpringDocApp16Test.java
License : Apache License 2.0
Project Creator : springdoc

@Test
public void testIndexActuator() {
    HttpStatus httpStatusMono = webClient.get().uri("/test/application/swaggerui").exchangeToMono(clientResponse -> Mono.just(clientResponse.statusCode())).block();
    replacedertThat(httpStatusMono).isEqualTo(HttpStatus.FOUND);
}

17 View Source File : SpringDocApp14Test.java
License : Apache License 2.0
Project Creator : springdoc

@Test
public void testIndexActuator() {
    HttpStatus httpStatusMono = webClient.get().uri("/application/swaggerui").exchangeToMono(clientResponse -> Mono.just(clientResponse.statusCode())).block();
    replacedertThat(httpStatusMono).isEqualTo(HttpStatus.FOUND);
}

17 View Source File : RedirectViewTests.java
License : Apache License 2.0
Project Creator : SourceHot

@Test
public void customStatusCode() {
    String url = "https://url.somewhere.com";
    RedirectView view = new RedirectView(url, HttpStatus.FOUND);
    view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange).block();
    replacedertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND);
    replacedertThat(this.exchange.getResponse().getHeaders().getLocation()).isEqualTo(URI.create(url));
}

17 View Source File : InternalAuthenticationIntegrationTest.java
License : MIT License
Project Creator : ls1intum

@Test
public void launchLtiRequest_authViaEmail_success() throws Exception {
    ltiLaunchRequest.setCustom_lookup_user_by_email(true);
    request.postForm("/api/lti/launch/" + programmingExercise.getId(), ltiLaunchRequest, HttpStatus.FOUND);
    final var user = userRepository.findAll().get(0);
    final var ltiUser = ltiUserIdRepository.findAll().get(0);
    final var ltiOutcome = ltiOutcomeUrlRepository.findAll().get(0);
    replacedertThat(ltiUser.getUser()).isEqualTo(user);
    replacedertThat(ltiUser.getLtiUserId()).isEqualTo(ltiLaunchRequest.getUser_id());
    replacedertThat(ltiOutcome.getUser()).isEqualTo(user);
    replacedertThat(ltiOutcome.getExercise()).isEqualTo(programmingExercise);
    replacedertThat(ltiOutcome.getUrl()).isEqualTo(ltiLaunchRequest.getLis_outcome_service_url());
    replacedertThat(ltiOutcome.getSourcedId()).isEqualTo(ltiLaunchRequest.getLis_result_sourcedid());
    final var updatedStudent = userRepository.findOneWithGroupsAndAuthoritiesByLogin(USERNAME).get();
    replacedertThat(student).isEqualTo(updatedStudent);
}

17 View Source File : GrantByImplicitProviderTest.java
License : MIT License
Project Creator : leftso

@Test
public void getJwtTokenByImplicitGrant() throws JsonParseException, JsonMappingException, IOException {
    String redirectUrl = "http://localhost:" + port + "/resources/user";
    ResponseEnreplacedy<String> response = new TestRestTemplate("user", "preplacedword").postForEnreplacedy("http://localhost:" + port + "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}", null, String.clreplaced, redirectUrl);
    replacedertEquals(HttpStatus.OK, response.getStatusCode());
    List<String> setCookie = response.getHeaders().get("Set-Cookie");
    String jSessionIdCookie = setCookie.get(0);
    String cookieValue = jSessionIdCookie.split(";")[0];
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cookie", cookieValue);
    response = new TestRestTemplate("user", "preplacedword").postForEnreplacedy("http://localhost:" + port + "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}&user_oauth_approval=true&authorize=Authorize", new HttpEnreplacedy<>(headers), String.clreplaced, redirectUrl);
    replacedertEquals(HttpStatus.FOUND, response.getStatusCode());
    replacedertNull(response.getBody());
    String location = response.getHeaders().get("Location").get(0);
    // FIXME: Is this a bug with redirect URL?
    location = location.replace("#", "?");
    response = new TestRestTemplate().getForEnreplacedy(location, String.clreplaced);
    replacedertEquals(HttpStatus.OK, response.getStatusCode());
}

17 View Source File : GameController.java
License : MIT License
Project Creator : FAForever

@GetMapping("/{id}/replay")
public void downloadReplay(HttpServletResponse httpServletResponse, @PathVariable("id") int replayId) {
    httpServletResponse.setHeader(HttpHeaders.LOCATION, gameService.getReplayDownloadUrl(replayId));
    httpServletResponse.setStatus(HttpStatus.FOUND.value());
}

16 View Source File : ClientLogoutSuccessHandler.java
License : MIT License
Project Creator : xkcoding

@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
    response.setStatus(HttpStatus.FOUND.value());
    // 跳转到客户端的回调地址
    response.sendRedirect(request.getParameter("redirectUrl"));
}

16 View Source File : SwaggerWelcomeCommon.java
License : Apache License 2.0
Project Creator : springdoc

/**
 * Redirect to ui mono.
 *
 * @param request the request
 * @param response the response
 * @return the mono
 */
protected Mono<Void> redirectToUi(ServerHttpRequest request, ServerHttpResponse response) {
    String contextPath = this.fromCurrentContextPath(request);
    String sbUrl = this.buildUrl(contextPath, swaggerUiConfigParameters.getUiRootPath() + springDocConfigProperties.getWebjars().getPrefix() + SWAGGER_UI_URL);
    UriComponentsBuilder uriBuilder = getUriComponentsBuilder(sbUrl);
    response.setStatusCode(HttpStatus.FOUND);
    response.getHeaders().setLocation(URI.create(uriBuilder.build().encode().toString()));
    return response.setComplete();
}

15 View Source File : OAuthGatewayIT.java
License : MIT License
Project Creator : timtebeek

@Test
void redirectCallsWithoutValidCookie() {
    final ClientResponse initialResponse = WebClient.create("http://localhost:9080").get().uri("/api/service1/hello").exchange().block();
    replacedertNotNull(initialResponse);
    replacedertEquals(HttpStatus.FOUND, initialResponse.statusCode());
    replacedertNotNull(initialResponse.headers().asHttpHeaders().getLocation());
    replacedertFalse(initialResponse.cookies().containsKey(SESSION));
    replacedertEquals("/oauth2/authorization/dummy-idp", initialResponse.headers().asHttpHeaders().getLocation().toString());
}

@Test
public void doFilterWhenUserConsentRequestApprovedThenAuthorizationResponse() throws Exception {
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scope(OidcScopes.OPENID).build();
    when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))).thenReturn(registeredClient);
    OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).principalName(this.authentication.getName()).attributes(attrs -> attrs.remove(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME)).build();
    when(this.authorizationService.findByToken(eq("state"), eq(STATE_TOKEN_TYPE))).thenReturn(authorization);
    MockHttpServletRequest request = createUserConsentRequest(registeredClient);
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.clreplaced);
    this.filter.doFilter(request, response, filterChain);
    verifyNoInteractions(filterChain);
    replacedertThat(response.getStatus()).isEqualTo(HttpStatus.FOUND.value());
    replacedertThat(response.getRedirectedUrl()).matches("https://example.com\\?code=.{15,}&state=state");
    ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClreplaced(OAuth2Authorization.clreplaced);
    verify(this.authorizationService).save(authorizationCaptor.capture());
    OAuth2Authorization updatedAuthorization = authorizationCaptor.getValue();
    replacedertThat(updatedAuthorization.getRegisteredClientId()).isEqualTo(registeredClient.getId());
    replacedertThat(updatedAuthorization.getPrincipalName()).isEqualTo(this.authentication.getPrincipal().toString());
    replacedertThat(updatedAuthorization.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
    replacedertThat(updatedAuthorization.getToken(OAuth2AuthorizationCode.clreplaced)).isNotNull();
    replacedertThat(updatedAuthorization.<String>getAttribute(OAuth2ParameterNames.STATE)).isNull();
    replacedertThat(updatedAuthorization.<OAuth2AuthorizationRequest>getAttribute(OAuth2AuthorizationRequest.clreplaced.getName())).isEqualTo(authorization.<OAuth2AuthorizationRequest>getAttribute(OAuth2AuthorizationRequest.clreplaced.getName()));
    replacedertThat(updatedAuthorization.<Set<String>>getAttribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME)).isEqualTo(registeredClient.getScopes());
}

14 View Source File : OAuthGatewayIT.java
License : MIT License
Project Creator : timtebeek

@Test
void oauthEndpointRedirectsToIdP() {
    final ClientResponse initialResponse = WebClient.create("http://localhost:9080").get().uri("/oauth2/authorization/dummy-idp").exchange().block();
    replacedertNotNull(initialResponse);
    replacedertEquals(HttpStatus.FOUND, initialResponse.statusCode());
    replacedertNotNull(initialResponse.headers().asHttpHeaders().getLocation());
    replacedertTrue(initialResponse.cookies().containsKey(SESSION));
    final URI idpLocation = initialResponse.headers().asHttpHeaders().getLocation();
    replacedertNotNull(idpLocation);
    replacedertTrue(idpLocation.isAbsolute());
    replacedertEquals("/dummy-idp-auth", idpLocation.getPath());
    replacedertTrue(idpLocation.getQuery().contains("response_type=code&client_id=gateway&scope=profile&state="));
    // redirect to IdP for login, should also contain the redirect_uri param to redirect back to after successful login
    replacedertTrue(idpLocation.getQuery().contains("&redirect_uri=http://localhost:9080/login/oauth2/code/dummy-idp"));
}

14 View Source File : SwaggerWelcomeCommon.java
License : Apache License 2.0
Project Creator : springdoc

/**
 * Redirect to ui response enreplacedy.
 *
 * @param request the request
 * @return the response enreplacedy
 */
protected ResponseEnreplacedy<Void> redirectToUi(HttpServletRequest request) {
    buildConfigUrl(request.getContextPath(), ServletUriComponentsBuilder.fromCurrentContextPath());
    String sbUrl = request.getContextPath() + swaggerUiConfigParameters.getUiRootPath() + SWAGGER_UI_URL;
    UriComponentsBuilder uriBuilder = getUriComponentsBuilder(sbUrl);
    // forward all queryParams from original request
    request.getParameterMap().forEach(uriBuilder::queryParam);
    return ResponseEnreplacedy.status(HttpStatus.FOUND).location(uriBuilder.build().encode().toUri()).build();
}

private void doFilterWhenAuthorizationRequestThenAuthorizationResponse(RegisteredClient registeredClient, MockHttpServletRequest request) throws Exception {
    when(this.registeredClientRepository.findByClientId((eq(registeredClient.getClientId())))).thenReturn(registeredClient);
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.clreplaced);
    this.filter.doFilter(request, response, filterChain);
    verifyNoInteractions(filterChain);
    replacedertThat(response.getStatus()).isEqualTo(HttpStatus.FOUND.value());
    replacedertThat(response.getRedirectedUrl()).matches("https://example.com\\?code=.{15,}&state=state");
    ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClreplaced(OAuth2Authorization.clreplaced);
    verify(this.authorizationService).save(authorizationCaptor.capture());
    OAuth2Authorization authorization = authorizationCaptor.getValue();
    replacedertThat(authorization.getRegisteredClientId()).isEqualTo(registeredClient.getId());
    replacedertThat(authorization.getPrincipalName()).isEqualTo(this.authentication.getPrincipal().toString());
    replacedertThat(authorization.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
    replacedertThat(authorization.<Authentication>getAttribute(Principal.clreplaced.getName())).isEqualTo(this.authentication);
    OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization.getToken(OAuth2AuthorizationCode.clreplaced);
    replacedertThat(authorizationCode).isNotNull();
    OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(OAuth2AuthorizationRequest.clreplaced.getName());
    replacedertThat(authorizationRequest).isNotNull();
    Set<String> authorizedScopes = authorization.getAttribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME);
    replacedertThat(authorizedScopes).isEqualTo(authorizationRequest.getScopes());
    replacedertThat(authorizationRequest.getAuthorizationUri()).isEqualTo("http://localhost/oauth2/authorize");
    replacedertThat(authorizationRequest.getGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
    replacedertThat(authorizationRequest.getResponseType()).isEqualTo(OAuth2AuthorizationResponseType.CODE);
    replacedertThat(authorizationRequest.getClientId()).isEqualTo(registeredClient.getClientId());
    replacedertThat(authorizationRequest.getRedirectUri()).isEqualTo(registeredClient.getRedirectUris().iterator().next());
    replacedertThat(authorizationRequest.getScopes()).containsExactlyInAnyOrderElementsOf(registeredClient.getScopes());
    replacedertThat(authorizationRequest.getState()).isEqualTo("state");
    replacedertThat(authorizationRequest.getAdditionalParameters()).isEmpty();
}

@Test
public void doFilterWhenPkceRequiredAndAuthorizationRequestThenAuthorizationResponse() throws Exception {
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient().clientSettings(clientSettings -> clientSettings.requireProofKey(true)).build();
    when(this.registeredClientRepository.findByClientId((eq(registeredClient.getClientId())))).thenReturn(registeredClient);
    MockHttpServletRequest request = createAuthorizationRequest(registeredClient);
    addPkceParameters(request);
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.clreplaced);
    this.filter.doFilter(request, response, filterChain);
    verifyNoInteractions(filterChain);
    replacedertThat(response.getStatus()).isEqualTo(HttpStatus.FOUND.value());
    replacedertThat(response.getRedirectedUrl()).matches("https://example.com\\?code=.{15,}&state=state");
    ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClreplaced(OAuth2Authorization.clreplaced);
    verify(this.authorizationService).save(authorizationCaptor.capture());
    OAuth2Authorization authorization = authorizationCaptor.getValue();
    replacedertThat(authorization.getRegisteredClientId()).isEqualTo(registeredClient.getId());
    replacedertThat(authorization.getPrincipalName()).isEqualTo(this.authentication.getPrincipal().toString());
    replacedertThat(authorization.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
    replacedertThat(authorization.<Authentication>getAttribute(Principal.clreplaced.getName())).isEqualTo(this.authentication);
    OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization.getToken(OAuth2AuthorizationCode.clreplaced);
    replacedertThat(authorizationCode).isNotNull();
    OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(OAuth2AuthorizationRequest.clreplaced.getName());
    replacedertThat(authorizationRequest).isNotNull();
    Set<String> authorizedScopes = authorization.getAttribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME);
    replacedertThat(authorizedScopes).isEqualTo(authorizationRequest.getScopes());
    replacedertThat(authorizationRequest.getClientId()).isEqualTo(registeredClient.getClientId());
    replacedertThat(authorizationRequest.getAdditionalParameters()).size().isEqualTo(2).returnToMap().containsEntry(PkceParameterNames.CODE_CHALLENGE, "code-challenge").containsEntry(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256");
}

14 View Source File : JiraAuthenticationIntegationTest.java
License : MIT License
Project Creator : ls1intum

@Test
@WithAnonymousUser
public void launchLtiRequest_authViaEmail_success() throws Exception {
    final var username = "mrrobot";
    final var email = ltiLaunchRequest.getLis_person_contact_email_primary();
    final var firstName = "Elliot";
    final var groups = Set.of("allsec", "security", ADMIN_GROUP_NAME, course.getInstructorGroupName(), course.getTeachingreplacedistantGroupName());
    jiraRequestMockProvider.mockGetUsernameForEmail(email, username);
    jiraRequestMockProvider.mockGetOrCreateUserLti(JIRA_USER, JIRA_PreplacedWORD, username, email, firstName, groups);
    jiraRequestMockProvider.mockAddUserToGroupForMultipleGroups(Set.of(course.getStudentGroupName()));
    jiraRequestMockProvider.mockGetOrCreateUserLti(username, "", username, email, firstName, groups);
    ltiLaunchRequest.setCustom_lookup_user_by_email(true);
    request.postForm("/api/lti/launch/" + programmingExercise.getId(), ltiLaunchRequest, HttpStatus.FOUND);
    final var user = userRepository.findAll().get(0);
    final var ltiUser = ltiUserIdRepository.findAll().get(0);
    final var ltiOutcome = ltiOutcomeUrlRepository.findAll().get(0);
    replacedertThat(ltiUser.getUser()).isEqualTo(user);
    replacedertThat(ltiUser.getLtiUserId()).isEqualTo(ltiLaunchRequest.getUser_id());
    replacedertThat(ltiOutcome.getUser()).isEqualTo(user);
    replacedertThat(ltiOutcome.getExercise()).isEqualTo(programmingExercise);
    replacedertThat(ltiOutcome.getUrl()).isEqualTo(ltiLaunchRequest.getLis_outcome_service_url());
    replacedertThat(ltiOutcome.getSourcedId()).isEqualTo(ltiLaunchRequest.getLis_result_sourcedid());
    final var mrrobotUser = userRepository.findOneWithGroupsAndAuthoritiesByLogin(username).get();
    replacedertThat(mrrobotUser.getEmail()).isEqualTo(email);
    replacedertThat(mrrobotUser.getFirstName()).isEqualTo(firstName);
    replacedertThat(mrrobotUser.getGroups()).containsAll(groups);
    replacedertThat(mrrobotUser.getGroups()).contains(course.getStudentGroupName());
    replacedertThat(mrrobotUser.getAuthorities()).containsAll(authorityRepository.findAll());
    final var preplacedword = preplacedwordService.decryptPreplacedword(mrrobotUser.getPreplacedword());
    final var auth = new TestingAuthenticationToken(username, preplacedword);
    final var responseAuth = jiraAuthenticationProvider.authenticate(auth);
    replacedertThat(responseAuth.getPrincipal()).isEqualTo(username);
    replacedertThat(responseAuth.getCredentials()).isEqualTo(mrrobotUser.getPreplacedword());
}

14 View Source File : AuthLogoutSuccessHandler.java
License : MIT License
Project Creator : gzmuSoft

@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
    String redirectUrl = request.getParameter("redirectUrl");
    if (StringUtils.isBlank(redirectUrl)) {
        redirectUrl = "/oauth/login";
    }
    String clientId = request.getParameter("clientId");
    if (StringUtils.isNoneBlank(clientId)) {
        oauth2Helper.safeLogout(clientId, authentication);
    }
    response.setStatus(HttpStatus.FOUND.value());
    response.sendRedirect(redirectUrl);
}

14 View Source File : ReviewControllerTests.java
License : Apache License 2.0
Project Creator : BBVA

@Test
public void createFeedbackReviewRedirectTest() throws Exception {
    final Review review = createFeedbackReview();
    when(reviewService.saveApplicationReview(eq(review.getAppname()), any())).thenReturn(map(review));
    final MockHttpServletRequestBuilder mockHSRB = post("/reviews/" + review.getAppname());
    this.mockMvc.perform(mockHSRB.contentType(MediaType.APPLICATION_FORM_URLENCODED).param("rate", String.valueOf(review.getStarrating())).param("comment", review.getComment()).param("url", "foobar")).andExpect(status().is(HttpStatus.FOUND.value()));
}

14 View Source File : ResponseUtilsTest.java
License : Apache License 2.0
Project Creator : adorsys

@Test
void redirect_relative_url() {
    // Given
    HttpServletResponse response = Mockito.mock(HttpServletResponse.clreplaced);
    when(cookieConfigProperties.getPath()).thenReturn("somePath");
    // When
    ResponseEnreplacedy<OnlineBankingResponse> responseResponseEnreplacedy = responseUtils.redirect("www.google.com", response);
    // Then
    replacedertTrue(responseResponseEnreplacedy.getStatusCode().is3xxRedirection());
    replacedertSame(HttpStatus.FOUND, responseResponseEnreplacedy.getStatusCode());
    replacedertEquals("http://www.google.com", responseResponseEnreplacedy.getHeaders().get("Location").get(0));
}

14 View Source File : ResponseUtilsTest.java
License : Apache License 2.0
Project Creator : adorsys

@Test
void redirect_absolute_url() {
    // Given
    HttpServletResponse response = Mockito.mock(HttpServletResponse.clreplaced);
    when(cookieConfigProperties.getPath()).thenReturn("somePath");
    // When
    ResponseEnreplacedy<OnlineBankingResponse> responseResponseEnreplacedy = responseUtils.redirect("http://www.google.com", response);
    // Then
    replacedertTrue(responseResponseEnreplacedy.getStatusCode().is3xxRedirection());
    replacedertSame(HttpStatus.FOUND, responseResponseEnreplacedy.getStatusCode());
    replacedertEquals("http://www.google.com", responseResponseEnreplacedy.getHeaders().get("Location").get(0));
}

14 View Source File : ResponseUtilsTest.java
License : Apache License 2.0
Project Creator : adorsys

@Test
void redirect() {
    // Given
    HttpServletResponse response = Mockito.mock(HttpServletResponse.clreplaced);
    when(cookieConfigProperties.getPath()).thenReturn("somePath");
    // When
    ResponseEnreplacedy<OnlineBankingResponse> responseResponseEnreplacedy = responseUtils.redirect("locationURI", response);
    // Then
    replacedertTrue(responseResponseEnreplacedy.getStatusCode().is3xxRedirection());
    replacedertSame(HttpStatus.FOUND, responseResponseEnreplacedy.getStatusCode());
}

13 View Source File : LtiIntegrationTest.java
License : MIT License
Project Creator : ls1intum

@Test
@WithMockUser(value = "student1", roles = "USER")
void launchAsNewStudent() throws Exception {
    Long exerciseId = programmingExercise.getId();
    Long courseId = programmingExercise.getCourseViaExerciseGroupOrCourseMember().getId();
    URI header = request.post("/api/lti/launch/" + exerciseId, requestBody, HttpStatus.FOUND, MediaType.APPLICATION_FORM_URLENCODED, false);
    replacedertTrue(header.toString().contains("?welcome&jwt="));
    replacedertTrue(header.toString().contains("/courses/" + courseId + "/exercises/" + exerciseId));
    this.checkExceptions();
}

13 View Source File : LtiIntegrationTest.java
License : MIT License
Project Creator : ls1intum

@Test
@WithAnonymousUser
void launchAsAnonymousUser() throws Exception {
    Long exerciseId = programmingExercise.getId();
    Long courseId = programmingExercise.getCourseViaExerciseGroupOrCourseMember().getId();
    URI header = request.post("/api/lti/launch/" + exerciseId, requestBody, HttpStatus.FOUND, MediaType.APPLICATION_FORM_URLENCODED, false);
    replacedertTrue(header.toString().contains("?login&jwt="));
    replacedertTrue(header.toString().contains("/courses/" + courseId + "/exercises/" + exerciseId));
    this.checkExceptions();
}

12 View Source File : SampleWebSecureJdbcApplicationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void testHome() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    ResponseEnreplacedy<String> enreplacedy = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEnreplacedy<Void>(headers), String.clreplaced);
    replacedertThat(enreplacedy.getStatusCode()).isEqualTo(HttpStatus.FOUND);
    replacedertThat(enreplacedy.getHeaders().getLocation().toString()).endsWith(this.port + "/login");
}

12 View Source File : OAuthGatewayIT.java
License : MIT License
Project Creator : timtebeek

@Test
void testCompleteLoginAndBackendCallFlow() throws JsonProcessingException, InterruptedException {
    // step 1: request authZ
    final ClientResponse initialResponse = WebClient.create("http://localhost:9080").get().uri("/oauth2/authorization/dummy-idp").exchange().block();
    // save cookie for use in later calls
    ResponseCookie sessionCookie = initialResponse.cookies().getFirst(SESSION);
    // pretend we logged in at the IdP
    final String query = initialResponse.headers().asHttpHeaders().getLocation().getQuery();
    final String state = query.substring(query.indexOf("state="), query.indexOf("&redirect"));
    String dummyRedirect = "http://localhost:9080/login/oauth2/code/dummy-idp?code=dummy-code&" + state;
    // play IdP and accept any authorization code check call and just give an access token back
    final HashMap<String, Object> tokenResponse = new HashMap<>();
    tokenResponse.put("access_token", "dummy-token");
    tokenResponse.put("token_type", "bearer");
    tokenResponse.put("expires_in", 300);
    idpMock.enqueue(new MockResponse().setResponseCode(200).setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(new ObjectMapper().writeValuereplacedtring(tokenResponse)));
    // play IdP and provide back user details which are requested directly after the token
    idpMock.enqueue(new MockResponse().setResponseCode(200).setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(new ObjectMapper().writeValuereplacedtring(Collections.singletonMap("username", "Dummy"))));
    // step 2: trigger the server-side code to token exchange call to our idpMock
    final ClientResponse authResponse = WebClient.create(dummyRedirect).get().cookie(SESSION, sessionCookie.getValue()).exchange().block();
    // check that client is now successfully logged in and are now redirected back to "/"
    replacedertEquals(HttpStatus.FOUND, authResponse.statusCode());
    replacedertEquals("/", authResponse.headers().asHttpHeaders().getLocation().toString());
    // update the cookie with the new value from the received Set-Cookie header
    sessionCookie = authResponse.cookies().getFirst(SESSION);
    // prepare service backend
    service1Mock.enqueue(new MockResponse().setResponseCode(200).setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(new ObjectMapper().writeValuereplacedtring(Collections.singletonMap("message", "hello mocked user"))));
    // step 3: call actual service with the session cookie
    final ClientResponse apiResponse = WebClient.create("http://localhost:9080").get().uri("/api/service1/hello").cookie(SESSION, sessionCookie.getValue()).exchange().block();
    replacedertEquals(HttpStatus.OK, apiResponse.statusCode());
    // final String result = apiResponse.bodyToMono(String.clreplaced).block();
    final Map jsonMap = apiResponse.bodyToMono(Map.clreplaced).block();
    replacedertNotNull(jsonMap);
    replacedertEquals("hello mocked user", jsonMap.get("message"));
    // check if the token was send to our backend service
    RecordedRequest recordedRequest = service1Mock.takeRequest();
    replacedertEquals("Bearer dummy-token", recordedRequest.getHeader("Authorization"));
}

11 View Source File : CallbackServiceTests.java
License : GNU General Public License v3.0
Project Creator : wehotel

@Test
void requestBackendsTest() throws InterruptedException {
    MockServerHttpRequest request = MockServerHttpRequest.get("http://127.0.0.1:8600/proxy/xservice/ybiz").build();
    MockServerWebExchange exchange = MockServerWebExchange.from(request);
    HttpHeaders headers = new HttpHeaders();
    headers.add("h1", "v1");
    DataBuffer body = null;
    CallbackConfig callbackConfig = new CallbackConfig();
    callbackConfig.receivers = new ArrayList<>();
    Receiver r1 = new Receiver();
    r1.service = "s1";
    r1.type = ApiConfig.Type.SERVICE_DISCOVERY;
    r1.path = "p1";
    callbackConfig.receivers.add(r1);
    Receiver r2 = new Receiver();
    r2.service = "s2";
    r2.type = ApiConfig.Type.SERVICE_DISCOVERY;
    r2.path = "p2";
    callbackConfig.receivers.add(r2);
    ServerHttpRequest req = exchange.getRequest();
    String reqId = req.getId();
    when(mockFizzWebClient.proxySend2service(reqId, HttpMethod.GET, "s1", "p1", headers, body)).thenReturn(Mono.just(ClientResponse.create(HttpStatus.GONE, ExchangeStrategies.withDefaults()).header("FIZZ-RSV", "s1-rsv-value").body("s1 resp").build()));
    when(mockFizzWebClient.proxySend2service(reqId, HttpMethod.GET, "s2", "p2", headers, body)).thenReturn(Mono.just(ClientResponse.create(HttpStatus.FOUND, ExchangeStrategies.withDefaults()).header("FIZZ-RSV", "s2-rsv-value").body("s2 resp").build()));
    Mono<Void> vm = callbackService.requestBackends(exchange, headers, body, callbackConfig, Collections.EMPTY_MAP);
    vm.subscribe();
    Thread.sleep(2000);
// if test preplaced, there will be a '{request id} response 410 GONE' log in console
}

10 View Source File : SampleMethodSecurityApplicationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void testLogin() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.set("username", "admin");
    form.set("preplacedword", "admin");
    getCsrf(form, headers);
    ResponseEnreplacedy<String> enreplacedy = this.restTemplate.exchange("/login", HttpMethod.POST, new HttpEnreplacedy<>(form, headers), String.clreplaced);
    replacedertThat(enreplacedy.getStatusCode()).isEqualTo(HttpStatus.FOUND);
    replacedertThat(enreplacedy.getHeaders().getLocation().toString()).isEqualTo("http://localhost:" + this.port + "/");
}

See More Examples