Example usage for org.springframework.security.jwt JwtHelper decode

List of usage examples for org.springframework.security.jwt JwtHelper decode

Introduction

In this page you can find the example usage for org.springframework.security.jwt JwtHelper decode.

Prototype

public static Jwt decode(String token) 

Source Link

Document

Creates a token from an encoded token string.

Usage

From source file:org.cloudfoundry.identity.uaa.login.feature.OpenIdTokenGrantsIT.java

private void doOpenIdHybridFlowIdTokenAndCode(Set<String> responseTypes, String responseTypeMatcher)
        throws Exception {

    HttpHeaders headers = new HttpHeaders();
    // TODO: should be able to handle just TEXT_HTML
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL));

    StringBuilder responseType = new StringBuilder();
    Iterator<String> rTypes = responseTypes.iterator();
    while (rTypes.hasNext()) {
        String type = rTypes.next();
        responseType.append(type);/*from w ww.  j av a  2 s .  co m*/
        if (rTypes.hasNext()) {
            responseType.append(" ");
        }
    }
    String state = new RandomValueStringGenerator().generate();
    String clientId = "app";
    String clientSecret = "appclientsecret";
    String redirectUri = "http://anywhere.com";
    String uri = loginUrl + "/oauth/authorize?response_type={response_type}&"
            + "state={state}&client_id={client_id}&redirect_uri={redirect_uri}";

    ResponseEntity<Void> result = restOperations.exchange(uri, HttpMethod.GET, new HttpEntity<>(null, headers),
            Void.class, responseType, state, clientId, redirectUri);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());
    String location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");

    if (result.getHeaders().containsKey("Set-Cookie")) {
        String cookie = result.getHeaders().getFirst("Set-Cookie");
        headers.set("Cookie", cookie);
    }

    ResponseEntity<String> response = restOperations.exchange(location, HttpMethod.GET,
            new HttpEntity<>(null, headers), String.class);
    // should be directed to the login screen...
    assertTrue(response.getBody().contains("/login.do"));
    assertTrue(response.getBody().contains("username"));
    assertTrue(response.getBody().contains("password"));

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("username", user.getUserName());
    formData.add("password", "secret");

    // Should be redirected to the original URL, but now authenticated
    result = restOperations.exchange(loginUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(formData, headers), Void.class);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());

    if (result.getHeaders().containsKey("Set-Cookie")) {
        String cookie = result.getHeaders().getFirst("Set-Cookie");
        headers.set("Cookie", cookie);
    }

    location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");
    response = restOperations.exchange(location, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    if (response.getStatusCode() == HttpStatus.OK) {
        // The grant access page should be returned
        assertTrue(response.getBody().contains("You can change your approval of permissions"));

        formData.clear();
        formData.add("user_oauth_approval", "true");
        result = restOperations.exchange(loginUrl + "/oauth/authorize", HttpMethod.POST,
                new HttpEntity<>(formData, headers), Void.class);
        assertEquals(HttpStatus.FOUND, result.getStatusCode());
        location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");
    } else {
        // Token cached so no need for second approval
        assertEquals(HttpStatus.FOUND, response.getStatusCode());
        location = UriUtils.decode(response.getHeaders().getLocation().toString(), "UTF-8");
    }
    assertTrue("Wrong location: " + location, location.matches(redirectUri + responseTypeMatcher.toString()));

    formData.clear();
    formData.add("client_id", clientId);
    formData.add("redirect_uri", redirectUri);
    formData.add("grant_type", "authorization_code");
    formData.add("code", location.split("code=")[1].split("&")[0]);
    HttpHeaders tokenHeaders = new HttpHeaders();
    String basicDigestHeaderValue = "Basic "
            + new String(Base64.encodeBase64((clientId + ":" + clientSecret).getBytes()));
    tokenHeaders.set("Authorization", basicDigestHeaderValue);

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> tokenResponse = restOperations.exchange(loginUrl + "/oauth/token", HttpMethod.POST,
            new HttpEntity<>(formData, tokenHeaders), Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, String> body = tokenResponse.getBody();
    Jwt token = JwtHelper.decode(body.get("access_token"));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"aud\""));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"user_id\""));
}