protected Map<String, Object> decode(String token) {
   try {
     Jwt jwt = JwtHelper.decodeAndVerify(token, verifier);
     String content = jwt.getClaims();
     @SuppressWarnings("unchecked")
     Map<String, Object> map = objectMapper.readValue(content, Map.class);
     return map;
   } catch (Exception e) {
     throw new InvalidTokenException("Cannot convert access token to JSON", e);
   }
 }
  /** Extracts a value of the given claim from a token. */
  private Object extractValue(Claims claim, String encodedToken) throws InvalidSignatureException {
    // decode the token
    Jwt token = JwtHelper.decodeAndVerify(encodedToken, verifier);

    // parse claims which are encoded as stringified JSON
    Map<String, Object> map;
    try {
      map = jsonMapper.readValue(token.getClaims(), Map.class);
    } catch (IOException e) {
      logger.error("Failed to extract json values", e);
      return null;
    }
    return map.get(claim.toString());
  }
Example #3
0
  private void validateToken(String paramName, Map params, String[] scopes, String[] aud)
      throws java.io.IOException {
    Jwt access_token = JwtHelper.decode((String) params.get(paramName));

    Map<String, Object> claims =
        JsonUtils.readValue(access_token.getClaims(), new TypeReference<Map<String, Object>>() {});

    Assert.assertThat(claims.get("jti"), is(params.get("jti")));
    Assert.assertThat(claims.get("client_id"), is("cf"));
    Assert.assertThat(claims.get("cid"), is("cf"));
    Assert.assertThat(claims.get("user_name"), is(user.getUserName()));
    Assert.assertThat(((List<String>) claims.get(Claims.SCOPE)), containsInAnyOrder(scopes));
    Assert.assertThat(((List<String>) claims.get(Claims.AUD)), containsInAnyOrder(aud));
  }
  @Test
  public void testSuccessfulAuthorizationCodeFlow() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));

    AuthorizationCodeResourceDetails resource = testAccounts.getDefaultAuthorizationCodeResource();

    URI uri =
        serverRunning
            .buildUri("/oauth/authorize")
            .queryParam("response_type", "code")
            .queryParam("state", "mystateid")
            .queryParam("client_id", resource.getClientId())
            .queryParam("redirect_uri", resource.getPreEstablishedRedirectUri())
            .build();
    ResponseEntity<Void> result = serverRunning.getForResponse(uri.toString(), headers);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());
    String location = result.getHeaders().getLocation().toString();

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

    ResponseEntity<String> response = serverRunning.getForString(location, headers);
    // 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<String, String>();
    formData.add("username", testAccounts.getUserName());
    formData.add("password", testAccounts.getPassword());

    // Should be redirected to the original URL, but now authenticated
    result = serverRunning.postForResponse("/login.do", headers, formData);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());

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

    response = serverRunning.getForString(result.getHeaders().getLocation().toString(), headers);
    if (response.getStatusCode() == HttpStatus.OK) {
      // The grant access page should be returned
      assertTrue(response.getBody().contains("Do you authorize"));

      formData.clear();
      formData.add("user_oauth_approval", "true");
      result = serverRunning.postForResponse("/oauth/authorize", headers, formData);
      assertEquals(HttpStatus.FOUND, result.getStatusCode());
      location = result.getHeaders().getLocation().toString();
    } else {
      // Token cached so no need for second approval
      assertEquals(HttpStatus.FOUND, response.getStatusCode());
      location = response.getHeaders().getLocation().toString();
    }
    assertTrue(
        "Wrong location: " + location,
        location.matches(resource.getPreEstablishedRedirectUri() + ".*code=.+"));

    formData.clear();
    formData.add("client_id", resource.getClientId());
    formData.add("redirect_uri", resource.getPreEstablishedRedirectUri());
    formData.add("grant_type", "authorization_code");
    formData.add("code", location.split("code=")[1].split("&")[0]);
    HttpHeaders tokenHeaders = new HttpHeaders();
    tokenHeaders.set(
        "Authorization",
        testAccounts.getAuthorizationHeader(resource.getClientId(), resource.getClientSecret()));
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> tokenResponse =
        serverRunning.postForMap("/oauth/token", formData, tokenHeaders);
    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\""));
  }
Example #5
0
  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);
      if (rTypes.hasNext()) {
        responseType.append(" ");
      }
    }
    String state = new RandomValueStringGenerator().generate();
    String clientId = "app";
    String clientSecret = "appclientsecret";
    String redirectUri = "http://*****:*****@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\""));
  }