Example usage for org.springframework.security.oauth2.common OAuth2AccessToken getExpiration

List of usage examples for org.springframework.security.oauth2.common OAuth2AccessToken getExpiration

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common OAuth2AccessToken getExpiration.

Prototype

Date getExpiration();

Source Link

Usage

From source file:org.springframework.security.oauth2.common.OAuth2AccessTokenJackson2DeserializerTests.java

private static void assertTokenEquals(OAuth2AccessToken expected, OAuth2AccessToken actual) {
    assertEquals(expected.getTokenType(), actual.getTokenType());
    assertEquals(expected.getValue(), actual.getValue());

    OAuth2RefreshToken expectedRefreshToken = expected.getRefreshToken();
    if (expectedRefreshToken == null) {
        assertNull(actual.getRefreshToken());
    } else {/*from  www .  j av  a 2s .  c  o  m*/
        assertEquals(expectedRefreshToken.getValue(), actual.getRefreshToken().getValue());
    }
    assertEquals(expected.getScope(), actual.getScope());
    Date expectedExpiration = expected.getExpiration();
    if (expectedExpiration == null) {
        assertNull(actual.getExpiration());
    } else {
        assertEquals(expectedExpiration.getTime(), actual.getExpiration().getTime());
    }
    assertEquals(expected.getAdditionalInformation(), actual.getAdditionalInformation());
}

From source file:com.onedrive.api.internal.InternalTokenServices.java

public void saveAccessToken(OAuth2ProtectedResourceDetails resource, Authentication authentication,
        OAuth2AccessToken accessToken) {
    if (reference.getAccessTokenListener() != null) {
        AccessToken internalAccessToken = new AccessToken();
        internalAccessToken.setAccessToken(accessToken.getValue());
        internalAccessToken.setExpiration(accessToken.getExpiration());
        internalAccessToken.setRefreshToken(accessToken.getRefreshToken().getValue());
        internalAccessToken.setScope(accessToken.getScope());
        internalAccessToken.setTokenType(accessToken.getTokenType());
        reference.getAccessTokenListener().onAccessTokenReceived(reference, internalAccessToken);
    }//w  ww . j  ava 2  s .  co m
}

From source file:eu.trentorise.smartcampus.permissionprovider.oauth.NonRemovingTokenServices.java

private OAuth2AccessToken refreshWithRepeat(String refreshTokenValue, AuthorizationRequest request,
        boolean repeat) {
    OAuth2AccessToken accessToken = localtokenStore.readAccessTokenForRefreshToken(refreshTokenValue);
    if (accessToken == null) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }/*  ww  w  .j  ava 2  s  . co m*/

    if (accessToken.getExpiration().getTime() - System.currentTimeMillis() > tokenThreshold * 1000L) {
        return accessToken;
    }

    try {
        OAuth2AccessToken res = super.refreshAccessToken(refreshTokenValue, request);
        OAuth2Authentication auth = localtokenStore.readAuthentication(res);
        traceUserLogger.info(
                String.format("'type':'refresh','user':'%s','token':'%s'", auth.getName(), res.getValue()));
        return res;
    } catch (RuntimeException e) {
        // do retry: it may be the case of race condition so retry the operation but only once
        if (!repeat)
            return refreshWithRepeat(refreshTokenValue, request, true);
        throw e;
    }
}

From source file:org.apigw.authserver.web.controller.CertifiedClientsController.java

private CertifiedClientDetails retrieveUserDetailsForCertifiedClient(String clientID,
        Map<String, Collection<OAuth2AccessToken>> accessTokens) {
    SimpleDateFormat formatter = getTimestampFormatter();
    Date now = new Date();

    CertifiedClientDetails certifiedClientDetails = new CertifiedClientDetails();
    for (Map.Entry<String, Collection<OAuth2AccessToken>> entry : accessTokens.entrySet()) {
        //Find all users that match this client
        for (OAuth2AccessToken token : entry.getValue()) {
            if (token.getExpiration() == null || token.getExpiration().before(now)) {
                continue;
            }//from w w w.  j a  va2  s .  c  o  m
            String tokenValue = token.getValue();
            String userClientID = consumerTokenServices.getClientId(tokenValue);
            if (userClientID.equalsIgnoreCase(clientID)) {
                UserDetail userDetails = new UserDetail();
                userDetails.setResidentId(entry.getKey());

                if (token.getExpiration() != null) {
                    userDetails.setExpires(formatter.format(token.getExpiration()));
                }
                String scopes = getScopesString(token.getScope());
                userDetails.setScopes(scopes);

                Map<String, Object> addInfo = token.getAdditionalInformation();
                userDetails.setGrantId(addInfo.get("authorization_grant_id").toString());

                if (addInfo != null && addInfo.get("issue_date") != null
                        && addInfo.get("issue_date") instanceof Date) {
                    userDetails.setIssued(formatter.format(addInfo.get("issue_date")));
                }

                if (certifiedClientDetails.getClientId() != null) {
                    certifiedClientDetails.getUserDetails().add(userDetails);
                } else {
                    CertifiedClient client = (CertifiedClient) clientDetailsService
                            .loadClientByClientId(userClientID);
                    certifiedClientDetails.setClientId(clientID);
                    certifiedClientDetails.setClientName(client.getName());
                    certifiedClientDetails.setOrganization(client.getOrganization());
                    certifiedClientDetails.setDescription(client.getDescription());
                    certifiedClientDetails.getUserDetails().add(userDetails);
                }
            }
        }
    }

    return certifiedClientDetails;
}

From source file:it.smartcommunitylab.aac.oauth.NonRemovingTokenServices.java

private OAuth2AccessToken refreshWithRepeat(String refreshTokenValue, TokenRequest request, boolean repeat) {
    OAuth2AccessToken accessToken = localtokenStore.readAccessTokenForRefreshToken(refreshTokenValue);
    if (accessToken == null) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }/* ww  w. j a  v  a2 s.c o  m*/

    if (accessToken.getExpiration().getTime() - System.currentTimeMillis() > tokenThreshold * 1000L) {
        return accessToken;
    }

    try {
        OAuth2AccessToken res = super.refreshAccessToken(refreshTokenValue, request);
        OAuth2Authentication auth = localtokenStore.readAuthentication(res);
        traceUserLogger.info(
                String.format("'type':'refresh','user':'%s','token':'%s'", auth.getName(), res.getValue()));
        return res;
    } catch (RuntimeException e) {
        // do retry: it may be the case of race condition so retry the operation but only once
        if (!repeat)
            return refreshWithRepeat(refreshTokenValue, request, true);
        throw e;
    }
}

From source file:org.mitre.oauth2.introspectingfilter.IntrospectingTokenService.java

/**
 * Validate a token string against the introspection endpoint,
 * then parse it and store it in the local cache if caching is enabled.
 *
 * @param accessToken Token to pass to the introspection endpoint
 * @return TokenCacheObject containing authentication and token if the token was valid, otherwise null
 *//*from   w  w  w . j  a  v a2  s .co  m*/
private TokenCacheObject parseToken(String accessToken) {

    // find out which URL to ask
    String introspectionUrl;
    RegisteredClient client;
    try {
        introspectionUrl = introspectionConfigurationService.getIntrospectionUrl(accessToken);
        client = introspectionConfigurationService.getClientConfiguration(accessToken);
    } catch (IllegalArgumentException e) {
        logger.error("Unable to load introspection URL or client configuration", e);
        return null;
    }
    // Use the SpringFramework RestTemplate to send the request to the
    // endpoint
    String validatedToken = null;

    RestTemplate restTemplate;
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();

    final String clientId = client.getClientId();
    final String clientSecret = client.getClientSecret();

    if (SECRET_BASIC.equals(client.getTokenEndpointAuthMethod())) {
        // use BASIC auth if configured to do so
        restTemplate = new RestTemplate(factory) {

            @Override
            protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
                ClientHttpRequest httpRequest = super.createRequest(url, method);
                httpRequest.getHeaders().add("Authorization", String.format("Basic %s",
                        Base64.encode(String.format("%s:%s", clientId, clientSecret))));
                return httpRequest;
            }
        };
    } else { //Alternatively use form based auth
        restTemplate = new RestTemplate(factory);

        form.add("client_id", clientId);
        form.add("client_secret", clientSecret);
    }

    form.add("token", accessToken);

    try {
        validatedToken = restTemplate.postForObject(introspectionUrl, form, String.class);
    } catch (RestClientException rce) {
        logger.error("validateToken", rce);
        return null;
    }
    if (validatedToken != null) {
        // parse the json
        JsonElement jsonRoot = new JsonParser().parse(validatedToken);
        if (!jsonRoot.isJsonObject()) {
            return null; // didn't get a proper JSON object
        }

        JsonObject tokenResponse = jsonRoot.getAsJsonObject();

        if (tokenResponse.get("error") != null) {
            // report an error?
            logger.error("Got an error back: " + tokenResponse.get("error") + ", "
                    + tokenResponse.get("error_description"));
            return null;
        }

        if (!tokenResponse.get("active").getAsBoolean()) {
            // non-valid token
            logger.info("Server returned non-active token");
            return null;
        }
        // create an OAuth2Authentication
        OAuth2Authentication auth = new OAuth2Authentication(createStoredRequest(tokenResponse),
                createAuthentication(tokenResponse));
        // create an OAuth2AccessToken
        OAuth2AccessToken token = createAccessToken(tokenResponse, accessToken);

        if (token.getExpiration() == null || token.getExpiration().after(new Date())) {
            // Store them in the cache
            TokenCacheObject tco = new TokenCacheObject(token, auth);
            if (cacheTokens && (cacheNonExpiringTokens || token.getExpiration() != null)) {
                authCache.put(accessToken, tco);
            }
            return tco;
        }
    }

    // when the token is invalid for whatever reason
    return null;
}

From source file:org.osiam.auth.token.TokenService.java

public AccessToken validateToken(final String token) {
    OAuth2Authentication auth = tokenStore.readAuthentication(token);
    OAuth2AccessToken accessToken = tokenStore.getAccessToken(auth);
    OAuth2Request authReq = auth.getOAuth2Request();

    AccessToken.Builder tokenBuilder = new AccessToken.Builder(token).setClientId(authReq.getClientId());

    if (auth.getUserAuthentication() != null && auth.getPrincipal() instanceof User) {
        User user = (User) auth.getPrincipal();
        tokenBuilder.setUserName(user.getUserName());
        tokenBuilder.setUserId(user.getId());
    }//from  w ww. ja v  a2 s.com

    tokenBuilder.setExpiresAt(accessToken.getExpiration());
    for (String scopeString : authReq.getScope()) {
        tokenBuilder.addScope(new Scope(scopeString));
    }

    return tokenBuilder.build();
}

From source file:org.springframework.security.oauth2.common.OAuth2AccessTokenJackson2Serializer.java

@Override
public void serialize(OAuth2AccessToken token, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException {
    jgen.writeStartObject();/*from   w  w  w  . ja  v a  2  s  .  co m*/
    jgen.writeStringField(OAuth2AccessToken.ACCESS_TOKEN, token.getValue());
    jgen.writeStringField(OAuth2AccessToken.TOKEN_TYPE, token.getTokenType());
    OAuth2RefreshToken refreshToken = token.getRefreshToken();
    if (refreshToken != null) {
        jgen.writeStringField(OAuth2AccessToken.REFRESH_TOKEN, refreshToken.getValue());
    }
    Date expiration = token.getExpiration();
    if (expiration != null) {
        long now = System.currentTimeMillis();
        jgen.writeNumberField(OAuth2AccessToken.EXPIRES_IN, (expiration.getTime() - now) / 1000);
    }
    Set<String> scope = token.getScope();
    if (scope != null && !scope.isEmpty()) {
        StringBuffer scopes = new StringBuffer();
        for (String s : scope) {
            Assert.hasLength(s, "Scopes cannot be null or empty. Got " + scope + "");
            scopes.append(s);
            scopes.append(" ");
        }
        jgen.writeStringField(OAuth2AccessToken.SCOPE, scopes.substring(0, scopes.length() - 1));
    }
    Map<String, Object> additionalInformation = token.getAdditionalInformation();
    for (String key : additionalInformation.keySet()) {
        jgen.writeObjectField(key, additionalInformation.get(key));
    }
    jgen.writeEndObject();
}

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

@RequestMapping(value = "/validation", method = RequestMethod.POST)
@ResponseBody//from w w w .  jav a2  s. com
public AccessToken tokenValidation(@RequestHeader("Authorization") final String authorization) {
    String token = getToken(authorization);
    OAuth2Authentication auth = tokenServices.loadAuthentication(token);
    OAuth2AccessToken accessToken = tokenServices.getAccessToken(auth);

    AuthorizationRequest authReq = auth.getAuthorizationRequest();
    AccessToken.Builder tokenBuilder = new AccessToken.Builder(token).setClientId(authReq.getClientId());

    if (auth.getUserAuthentication() != null && auth.getPrincipal() instanceof User) {
        User user = (User) auth.getPrincipal();
        tokenBuilder.setUserName(user.getUserName());
        tokenBuilder.setUserId(user.getId());
    }

    tokenBuilder.setExpiresAt(accessToken.getExpiration());

    for (String scopeString : authReq.getScope()) {
        tokenBuilder.addScope(new Scope(scopeString));
    }

    return tokenBuilder.build();
}

From source file:am.ik.categolj2.app.authentication.AuthenticationHelper.java

void saveAccessTokenInCookie(OAuth2AccessToken accessToken, HttpServletResponse response)
        throws UnsupportedEncodingException {
    Cookie accessTokenValueCookie = new Cookie(Categolj2Cookies.ACCESS_TOKEN_VALUE_COOKIE,
            URLEncoder.encode(accessToken.getValue(), "UTF-8"));
    accessTokenValueCookie.setMaxAge(accessToken.getExpiresIn());
    Cookie accessTokenExpireCookie = new Cookie(Categolj2Cookies.ACCESS_TOKEN_EXPIRATION_COOKIE,
            URLEncoder.encode(String.valueOf(accessToken.getExpiration().getTime()), "UTF-8"));
    accessTokenExpireCookie.setMaxAge(accessToken.getExpiresIn());

    response.addCookie(accessTokenValueCookie);
    response.addCookie(accessTokenExpireCookie);

    OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
    if (refreshToken != null) {
        Cookie refreshTokenCookie = new Cookie(Categolj2Cookies.REFRESH_TOKEN_VALUE_COOKIE,
                URLEncoder.encode(refreshToken.getValue(), "UTF-8"));
        refreshTokenCookie.setMaxAge(getRefreshTokenMaxAge(accessToken));
        response.addCookie(refreshTokenCookie);
    }/*from  w  ww  .j av a  2s  . c  om*/
}