Search in sources :

Example 81 with HttpHeaders

use of org.springframework.http.HttpHeaders in project spring-security-oauth by spring-projects.

the class PhotoController method getJsonPhotos.

@RequestMapping(value = "/photos", params = "format=json")
public ResponseEntity<String> getJsonPhotos(Principal principal) {
    Collection<PhotoInfo> photos = getPhotoService().getPhotosForCurrentUser(principal.getName());
    StringBuilder out = new StringBuilder();
    out.append("{ \"photos\" : [ ");
    Iterator<PhotoInfo> photosIt = photos.iterator();
    while (photosIt.hasNext()) {
        PhotoInfo photo = photosIt.next();
        out.append(String.format("{ \"id\" : \"%s\" , \"name\" : \"%s\" }", photo.getId(), photo.getName()));
        if (photosIt.hasNext()) {
            out.append(" , ");
        }
    }
    out.append("] }");
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Type", "application/javascript");
    return new ResponseEntity<String>(out.toString(), headers, HttpStatus.OK);
}
Also used : PhotoInfo(org.springframework.security.oauth.examples.sparklr.PhotoInfo) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 82 with HttpHeaders

use of org.springframework.http.HttpHeaders in project spring-security-oauth by spring-projects.

the class AdminEndpointsTests method testRevokeTokenByUser.

@Test
@OAuth2ContextConfiguration(ResourceOwnerWriteOnly.class)
public void testRevokeTokenByUser() throws Exception {
    OAuth2AccessToken token = context.getAccessToken();
    String tokenValueBeforeDeletion = token.getValue();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<?> request = new HttpEntity<Void>(headers);
    assertEquals(HttpStatus.NO_CONTENT, serverRunning.getRestTemplate().exchange(serverRunning.getUrl("/sparklr2/oauth/users/{user}/tokens/{token}"), HttpMethod.DELETE, request, Void.class, "marissa", token.getValue()).getStatusCode());
    try {
        // The request above will delete the oauth token so that the next request will initially fail. However,
        // the failure will be detected and a new access token will be obtained.  The new access token
        // only has "write" scope and the requested resource needs "read" scope.  So, an insufficient_scope
        // exception should be thrown.
        ResponseEntity<String> result = serverRunning.getForString("/sparklr2/oauth/clients/my-client-with-registered-redirect/users/marissa/tokens", headers);
        fail("Should have thrown an exception");
        assertNotNull(result);
    } catch (InsufficientScopeException ex) {
        assertEquals(HttpStatus.FORBIDDEN.value(), ex.getHttpErrorCode());
        assertEquals("insufficient_scope", ex.getOAuth2ErrorCode());
        String secondTokenWithWriteOnlyScope = context.getOAuth2ClientContext().getAccessToken().getValue();
        assertNotNull(secondTokenWithWriteOnlyScope);
        assertFalse(secondTokenWithWriteOnlyScope.equals(tokenValueBeforeDeletion));
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) InsufficientScopeException(org.springframework.security.oauth2.common.exceptions.InsufficientScopeException) HttpEntity(org.springframework.http.HttpEntity) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2ContextConfiguration(org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration) Test(org.junit.Test)

Example 83 with HttpHeaders

use of org.springframework.http.HttpHeaders in project spring-security-oauth by spring-projects.

the class AuthorizationCodeProviderTests method testInvalidAccessToken.

@Test
public void testInvalidAccessToken() throws Exception {
    // now make sure an unauthorized request fails the right way.
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, "FOO"));
    ResponseEntity<String> response = serverRunning.getForString("/sparklr2/photos?format=json", headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
    String authenticate = response.getHeaders().getFirst("WWW-Authenticate");
    assertNotNull(authenticate);
    assertTrue(authenticate.startsWith("Bearer"));
    // Resource Server doesn't know what scopes are required until the token can be validated
    assertFalse(authenticate.contains("scope=\""));
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Test(org.junit.Test)

Example 84 with HttpHeaders

use of org.springframework.http.HttpHeaders in project spring-security-oauth by spring-projects.

the class AuthorizationCodeProviderTests method testInvalidScopeInAuthorizationRequest.

@Test
public void testInvalidScopeInAuthorizationRequest() throws Exception {
    // Need to use the client with a redirect because "my-less-trusted-client" has no registered scopes
    String cookie = loginAndGrabCookie();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    headers.set("Cookie", cookie);
    String scope = "bogus";
    String redirectUri = "http://anywhere?key=value";
    String clientId = "my-client-with-registered-redirect";
    UriBuilder uri = serverRunning.buildUri("/sparklr2/oauth/authorize").queryParam("response_type", "code").queryParam("state", "mystateid").queryParam("scope", scope);
    if (clientId != null) {
        uri.queryParam("client_id", clientId);
    }
    if (redirectUri != null) {
        uri.queryParam("redirect_uri", redirectUri);
    }
    ResponseEntity<String> response = serverRunning.getForString(uri.pattern(), headers, uri.params());
    assertEquals(HttpStatus.FOUND, response.getStatusCode());
    String location = response.getHeaders().getLocation().toString();
    assertTrue(location.startsWith("http://anywhere"));
    assertTrue(location.contains("error=invalid_scope"));
    assertFalse(location.contains("redirect_uri="));
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) UriBuilder(org.springframework.security.oauth2.provider.ServerRunning.UriBuilder) Test(org.junit.Test)

Example 85 with HttpHeaders

use of org.springframework.http.HttpHeaders in project spring-security-oauth by spring-projects.

the class SparklrController method photo.

@RequestMapping("/sparklr/photos/{id}")
public ResponseEntity<BufferedImage> photo(@PathVariable String id, HttpServletRequest request) throws Exception {
    InputStream photo = sparklrService.loadSparklrPhoto(id);
    if (photo == null) {
        throw new UnavailableException("The requested photo does not exist");
    }
    BufferedImage body;
    MediaType contentType = MediaType.IMAGE_JPEG;
    Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString());
    if (imageReaders.hasNext()) {
        ImageReader imageReader = imageReaders.next();
        ImageReadParam irp = imageReader.getDefaultReadParam();
        imageReader.setInput(new MemoryCacheImageInputStream(photo), true);
        body = imageReader.read(0, irp);
    } else {
        throw new HttpMessageNotReadableException("Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    request.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(MediaType.IMAGE_JPEG));
    return new ResponseEntity<BufferedImage>(body, headers, HttpStatus.OK);
}
Also used : ImageReadParam(javax.imageio.ImageReadParam) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) InputStream(java.io.InputStream) UnavailableException(javax.servlet.UnavailableException) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) MediaType(org.springframework.http.MediaType) ImageReader(javax.imageio.ImageReader) BufferedImage(java.awt.image.BufferedImage) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

HttpHeaders (org.springframework.http.HttpHeaders)1676 Test (org.junit.Test)426 ResponseEntity (org.springframework.http.ResponseEntity)383 HttpEntity (org.springframework.http.HttpEntity)345 Test (org.junit.jupiter.api.Test)273 HashMap (java.util.HashMap)184 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)154 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)127 MediaType (org.springframework.http.MediaType)121 URI (java.net.URI)111 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)102 Map (java.util.Map)97 IOException (java.io.IOException)83 RestTemplate (org.springframework.web.client.RestTemplate)78 ArrayList (java.util.ArrayList)75 MessageHeaders (org.springframework.messaging.MessageHeaders)74 MultiValueMap (org.springframework.util.MultiValueMap)74 HttpStatus (org.springframework.http.HttpStatus)71 List (java.util.List)65 Timed (com.codahale.metrics.annotation.Timed)54