Example usage for org.springframework.security.oauth2.common.exceptions InvalidTokenException getMessage

List of usage examples for org.springframework.security.oauth2.common.exceptions InvalidTokenException getMessage

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common.exceptions InvalidTokenException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.osiam.security.controller.TokenController.java

@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)/*from   ww w . ja v a 2s  .  co  m*/
@ResponseBody
public AuthenticationError handleClientAuthenticationException(InvalidTokenException ex,
        HttpServletRequest request) {
    return new AuthenticationError("invalid_token", ex.getMessage());
}

From source file:com.ge.predix.uaa.token.lib.FastTokenServiceTest.java

/**
 * Tests that an expired token issues an InvalidTokenException.
 *///  w  ww .  java2 s. co  m
@Test
public void testLoadAuthenticationWithExpiredToken() throws Exception {
    String accessToken = this.testTokenUtil.mockAccessToken(System.currentTimeMillis() - 240000, 60);
    try {
        this.services.loadAuthentication(accessToken);
        Assert.fail("Expected InvalidTokenException for expired token.");
    } catch (InvalidTokenException e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.ge.predix.uaa.token.lib.FastTokenServiceTest.java

/**
 * Tests that an token that is valid for future use issues an InvalidTokenException.
 *//*  ww w.java 2 s . co  m*/
@Test
public void testLoadAuthenticationWithFutureToken() throws Exception {
    String accessToken = this.testTokenUtil.mockAccessToken(System.currentTimeMillis() + 240000, 60);
    try {
        this.services.loadAuthentication(accessToken);
        Assert.fail("Expected InvalidTokenException for token issued in the future.");
    } catch (InvalidTokenException e) {
        System.out.println(e.getMessage());
    }
}

From source file:org.springframework.security.oauth2.common.exception.OAuth2ExceptionJackson2DeserializerTests.java

@Test
public void readValueInvalidToken() throws Exception {
    String accessToken = createResponse(OAuth2Exception.INVALID_TOKEN);
    InvalidTokenException result = (InvalidTokenException) mapper.readValue(accessToken, OAuth2Exception.class);
    assertEquals(DETAILS, result.getMessage());
    assertEquals(null, result.getAdditionalInformation());
}

From source file:it.smartcommunitylab.aac.controller.ResourceAccessController.java

@ApiOperation(value = "Get token info")
@RequestMapping(method = RequestMethod.GET, value = "/resources/token")
@Deprecated//from  w  w w.  java 2 s  .co m
public @ResponseBody AACTokenValidation getTokenInfo(HttpServletRequest request, HttpServletResponse response) {
    AACTokenValidation result = new AACTokenValidation();

    try {
        String parsedToken = it.smartcommunitylab.aac.common.Utils.parseHeaderToken(request);

        OAuth2Authentication auth = resourceServerTokenServices.loadAuthentication(parsedToken);

        OAuth2AccessToken storedToken = tokenStore.getAccessToken(auth);
        long expiresIn = storedToken.getExpiresIn();

        String clientId = auth.getOAuth2Request().getClientId();

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.ANY)
                .withSetterVisibility(JsonAutoDetect.Visibility.ANY)
                .withCreatorVisibility(JsonAutoDetect.Visibility.ANY));

        String userName = null;
        String userId = null;
        boolean applicationToken = false;

        //         System.err.println(auth.getPrincipal());

        if (auth.getPrincipal() instanceof User) {
            User principal = (User) auth.getPrincipal();
            userId = principal.getUsername();
            //         } if (auth.getPrincipal() instanceof it.smartcommunitylab.aac.model.User) { 
            //            it.smartcommunitylab.aac.model.User principal = (it.smartcommunitylab.aac.model.User)auth.getPrincipal();
            //            userId = principal.getId().toString();
            //            userName = getWSO2Name(user);
        } else {
            ClientDetailsEntity client = clientDetailsRepository.findByClientId(clientId);
            applicationToken = true;
            userId = "" + client.getDeveloperId();
            //            if (client.getParameters() != null) {
            //               Map<String,?> parameters = mapper.readValue(client.getParameters(), Map.class);
            //               userName = (String)parameters.get("username");
            //            } else {
            ////               it.smartcommunitylab.aac.model.User user = userRepository.findOne(Long.parseLong(userId));
            //               userName = "admin";
            //               userName = (String)auth.getPrincipal();
            //            }
        }
        userName = userManager.getUserInternalName(Long.parseLong(userId));

        result.setUsername(userName);
        result.setUserId(userId);
        result.setClientId(clientId);
        result.setScope(Iterables.toArray(auth.getOAuth2Request().getScope(), String.class));
        result.setGrantType(auth.getOAuth2Request().getGrantType());

        long now = System.currentTimeMillis();
        result.setIssuedTime(now);
        result.setValidityPeriod(expiresIn);

        logger.info("Requested token " + parsedToken + " expires in " + result.getValidityPeriod());

        result.setValid(true);

        result.setApplicationToken(applicationToken);

        //         System.err.println(mapper.writeValueAsString(response));         
    } catch (InvalidTokenException e) {
        logger.error("Invalid token: " + e.getMessage());
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return null;
    } catch (Exception e) {
        logger.error("Error getting info for token: " + e.getMessage());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }

    return result;
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void validateOldTokenAfterDeleteClientSecret() throws Exception {
    String clientId = "testclient" + generator.generate();
    String scopes = "space.*.developer,space.*.admin,org.*.reader,org.123*.admin,*.*,*";
    setUpClients(clientId, scopes, scopes, GRANT_TYPES, true);

    String body = getMockMvc()/* w w  w.  j  a  v  a2s.  c  om*/
            .perform(post("/oauth/token").accept(MediaType.APPLICATION_JSON_VALUE)
                    .header("Authorization",
                            "Basic " + new String(Base64.encode((clientId + ":" + SECRET).getBytes())))
                    .param("grant_type", "client_credentials").param("client_id", clientId)
                    .param("client_secret", SECRET))
            .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();

    Map<String, Object> bodyMap = JsonUtils.readValue(body, new TypeReference<Map<String, Object>>() {
    });
    String access_token = (String) bodyMap.get("access_token");
    assertNotNull(access_token);

    clientDetailsService.addClientSecret(clientId, "newSecret");
    clientDetailsService.deleteClientSecret(clientId);

    MockHttpServletResponse response = getMockMvc().perform(post("/check_token")
            .header("Authorization", "Basic " + new String(Base64.encode("app:appclientsecret".getBytes())))
            .param("token", access_token)).andExpect(status().isBadRequest()).andReturn().getResponse();

    InvalidTokenException tokenRevokedException = JsonUtils.readValue(response.getContentAsString(),
            TokenRevokedException.class);
    assertEquals("invalid_token", tokenRevokedException.getOAuth2ErrorCode());
    assertEquals("revocable signature mismatch", tokenRevokedException.getMessage());
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java

@Test
public void testClientSecret_Added_Token_Validation_Still_Works() {

    defaultClient.setClientSecret(SECRET);

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, PASSWORD);
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = defaultUserAuthentication;

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            userAuthentication);/*w w w. j  a v a2s .co  m*/
    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);
    //normal token validation
    tokenServices.loadAuthentication(accessToken.getValue());

    //add a 2nd secret
    defaultClient.setClientSecret(defaultClient.getClientSecret() + " newsecret");
    tokenServices.loadAuthentication(accessToken.getValue());

    //generate a token when we have two secrets
    OAuth2AccessToken accessToken2 = tokenServices.createAccessToken(authentication);

    //remove the 1st secret
    defaultClient.setClientSecret("newsecret");
    try {
        tokenServices.loadAuthentication(accessToken.getValue());
        fail("Token should fail to validate on the revocation signature");
    } catch (InvalidTokenException e) {
        assertTrue(e.getMessage().contains("revocable signature mismatch"));
    }
    tokenServices.loadAuthentication(accessToken2.getValue());

    OAuth2AccessToken accessToken3 = tokenServices.createAccessToken(authentication);
    tokenServices.loadAuthentication(accessToken3.getValue());
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java

public void readAccessToken(Set<String> excludedClaims) {
    tokenServices.setExcludedClaims(excludedClaims);
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE);
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = defaultUserAuthentication;

    Calendar expiresAt = Calendar.getInstance();
    expiresAt.add(Calendar.MILLISECOND, 3000);
    Calendar updatedAt = Calendar.getInstance();
    updatedAt.add(Calendar.MILLISECOND, -1000);

    approvalStore.addApproval(new Approval().setUserId(userId).setClientId(CLIENT_ID).setScope(readScope.get(0))
            .setExpiresAt(expiresAt.getTime()).setStatus(ApprovalStatus.APPROVED)
            .setLastUpdatedAt(updatedAt.getTime()));
    approvalStore.addApproval(new Approval().setUserId(userId).setClientId(CLIENT_ID)
            .setScope(writeScope.get(0)).setExpiresAt(expiresAt.getTime()).setStatus(ApprovalStatus.APPROVED)
            .setLastUpdatedAt(updatedAt.getTime()));
    Approval approval = new Approval().setUserId(userId).setClientId(CLIENT_ID).setScope(OPENID)
            .setExpiresAt(expiresAt.getTime()).setStatus(ApprovalStatus.APPROVED)
            .setLastUpdatedAt(updatedAt.getTime());
    approvalStore.addApproval(approval);

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            userAuthentication);/*ww  w .j  a  va  2  s  .  c  o m*/
    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);
    assertEquals(accessToken, tokenServices.readAccessToken(accessToken.getValue()));

    approvalStore.revokeApproval(approval);
    try {
        tokenServices.readAccessToken(accessToken.getValue());
        fail("Approval has been revoked");
    } catch (InvalidTokenException x) {
        assertThat("Exception should be about approvals",
                x.getMessage().contains("some requested scopes are not approved"));
    }
}