Search in sources :

Example 1 with OAuth2AccessToken

use of org.maxkey.authz.oauth2.common.OAuth2AccessToken in project developer-be by EdgeGallery.

the class AccessTokenFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    if (request.getRequestURI() == null || !(request.getRequestURI().equals("/health"))) {
        String accessTokenStr = request.getHeader(Consts.ACCESS_TOKEN_STR);
        if (StringUtils.isEmpty(accessTokenStr)) {
            LOGGER.error("Access token is empty");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Access token is empty");
            return;
        }
        OAuth2AccessToken accessToken = jwtTokenStore.readAccessToken(accessTokenStr);
        if (accessToken == null) {
            LOGGER.error("Invalid access token, token string is null");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Invalid access token, token string is null.");
            return;
        }
        if (accessToken.isExpired()) {
            LOGGER.error("Access token expired");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Access token expired");
            return;
        }
        Map<String, Object> additionalInfoMap = accessToken.getAdditionalInformation();
        if (additionalInfoMap == null) {
            LOGGER.error("Invalid access token, additional info map is null.");
            String msg = "Invalid access token, additional info map is null.";
            response.sendError(HttpStatus.UNAUTHORIZED.value(), msg);
            return;
        }
        String userIdFromToken = additionalInfoMap.get("userId").toString();
        String userNameFromToken = additionalInfoMap.get("userName").toString();
        String userAuthFromToken = additionalInfoMap.get("authorities").toString();
        AccessUserUtil.setUser(userIdFromToken, userNameFromToken, userAuthFromToken, accessTokenStr);
        String userIdFromRequest = request.getParameter("userId");
        if (!StringUtils.isEmpty(userIdFromRequest) && !userIdFromRequest.equals(userIdFromToken)) {
            LOGGER.error("Illegal userId");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Illegal userId");
            return;
        }
        String userNameFromRequest = request.getParameter("userName");
        if (!StringUtils.isEmpty(userNameFromRequest) && !userNameFromRequest.equals(userNameFromToken)) {
            LOGGER.error("Illegal userName");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Illegal userName");
            return;
        }
        OAuth2Authentication auth = jwtTokenStore.readAuthentication(accessToken);
        if (auth == null) {
            LOGGER.error("Invalid access token, authentication info is null.");
            String msg = "Invalid access token, authentication info is null.";
            response.sendError(HttpStatus.UNAUTHORIZED.value(), msg);
            return;
        }
        SecurityContextHolder.getContext().setAuthentication(auth);
    }
    try {
        filterChain.doFilter(request, response);
    } finally {
        AccessUserUtil.unload();
    }
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication)

Example 2 with OAuth2AccessToken

use of org.maxkey.authz.oauth2.common.OAuth2AccessToken in project alexa-oauth-sample by alexa-samples.

the class ReciprocalAuthorizationEndpoint method postReciprocalCode.

@RequestMapping(value = "/api/reciprocal/authorize", method = RequestMethod.POST)
public void postReciprocalCode(@RequestBody @RequestParam final Map<String, String> parameters) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String grantType = parameters.get("grant_type");
    // It is not the client_id we got from partner, but the client id we vend out to partner (partnerId).
    String partnerId = parameters.get("client_id");
    String authorizationCode = parameters.get("code");
    if (!StringUtils.equals(grantType, GRANT_TYPE)) {
        throw new UnsupportedGrantTypeException("Only reciprocal_authorization_code is supported in this endpoint");
    }
    OAuthPartner partner = partnerDetailsRepository.loadPartnerByPartnerId(partnerId);
    if (partner == null) {
        throw new NoSuchClientException("Invalid partner id: " + partnerId);
    }
    OAuth2ProtectedResourceDetails resourceDetails = partner.toProtectedResourceDetails();
    AuthorizationCodeAccessTokenProvider tokenProvider = new AuthorizationCodeAccessTokenProvider();
    tokenProvider.setStateMandatory(false);
    OAuth2AccessToken accessToken = tokenProvider.obtainAccessToken(resourceDetails, createAccessTokenRequest(authorizationCode));
    partnerTokenRepository.saveAccessToken(resourceDetails, auth, accessToken);
}
Also used : Authentication(org.springframework.security.core.Authentication) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuthPartner(com.oauth.server.dto.OAuthPartner) AuthorizationCodeAccessTokenProvider(org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider) OAuth2ProtectedResourceDetails(org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails) UnsupportedGrantTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException) NoSuchClientException(org.springframework.security.oauth2.provider.NoSuchClientException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 3 with OAuth2AccessToken

use of org.maxkey.authz.oauth2.common.OAuth2AccessToken in project OpenID-Connect-Java-Spring-Server by mitreid-connect.

the class IntrospectingTokenService method parseToken.

/**
 * 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
 */
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()) {
            // didn't get a proper JSON object
            return null;
        }
        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), createUserAuthentication(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;
}
Also used : LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) URI(java.net.URI) Date(java.util.Date) RegisteredClient(org.mitre.oauth2.model.RegisteredClient) JsonElement(com.google.gson.JsonElement) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) RestTemplate(org.springframework.web.client.RestTemplate) RestClientException(org.springframework.web.client.RestClientException) HttpMethod(org.springframework.http.HttpMethod) JsonParser(com.google.gson.JsonParser)

Example 4 with OAuth2AccessToken

use of org.maxkey.authz.oauth2.common.OAuth2AccessToken in project pig by pig-mesh.

the class PigRedisTokenStore method findTokensByClientId.

@Override
public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
    byte[] key = serializeKey(CLIENT_ID_TO_ACCESS + clientId);
    List<byte[]> byteList;
    try (RedisConnection conn = getConnection()) {
        byteList = getZByteLists(key, conn);
    }
    if (byteList.size() == 0) {
        return Collections.emptySet();
    }
    List<OAuth2AccessToken> accessTokens = new ArrayList<>(byteList.size());
    for (byte[] bytes : byteList) {
        OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
        accessTokens.add(accessToken);
    }
    return Collections.unmodifiableCollection(accessTokens);
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) RedisConnection(org.springframework.data.redis.connection.RedisConnection)

Example 5 with OAuth2AccessToken

use of org.maxkey.authz.oauth2.common.OAuth2AccessToken in project pig by pig-mesh.

the class PigRedisTokenStore method getAccessToken.

@Override
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
    String key = authenticationKeyGenerator.extractKey(authentication);
    byte[] serializedKey = serializeKey(AUTH_TO_ACCESS + key);
    byte[] bytes;
    try (RedisConnection conn = getConnection()) {
        bytes = conn.get(serializedKey);
    }
    OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
    if (accessToken != null) {
        OAuth2Authentication storedAuthentication = readAuthentication(accessToken.getValue());
        if ((storedAuthentication == null || !key.equals(authenticationKeyGenerator.extractKey(storedAuthentication)))) {
            // Keep the stores consistent (maybe the same user is
            // represented by this authentication but the details have
            // changed)
            storeAccessToken(accessToken, authentication);
        }
    }
    return accessToken;
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) RedisConnection(org.springframework.data.redis.connection.RedisConnection)

Aggregations

OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)516 Test (org.junit.Test)252 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)219 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)165 Authentication (org.springframework.security.core.Authentication)79 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)58 Date (java.util.Date)52 IsEmptyString.isEmptyString (org.hamcrest.text.IsEmptyString.isEmptyString)42 TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)42 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)42 HashMap (java.util.HashMap)35 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)32 Map (java.util.Map)30 HttpHeaders (org.springframework.http.HttpHeaders)30 OAuth2RefreshToken (org.springframework.security.oauth2.common.OAuth2RefreshToken)30 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)27 MultiValueMap (org.springframework.util.MultiValueMap)27 InvalidTokenException (org.springframework.security.oauth2.common.exceptions.InvalidTokenException)25 ArrayList (java.util.ArrayList)24 Claims (org.cloudfoundry.identity.uaa.oauth.token.Claims)22