Package org.springframework.security.oauth2.provider

Examples of org.springframework.security.oauth2.provider.OAuth2Request


  private Authentication createAuthentication(JsonObject token) {
    return new PreAuthenticatedAuthenticationToken(token.get("sub").getAsString(), token, introspectionAuthorityGranter.getAuthorities(token));
  }

  private OAuth2AccessToken createAccessToken(final JsonObject token, final String tokenString) {
    OAuth2AccessToken accessToken = new OAuth2AccessTokenImpl(token, tokenString);
    return accessToken;
  }
View Full Code Here


        return false;
      }
      // create an OAuth2Authentication
      OAuth2Authentication auth = new OAuth2Authentication(createStoredRequest(tokenResponse), createAuthentication(tokenResponse));
      // create an OAuth2AccessToken
      OAuth2AccessToken token = createAccessToken(tokenResponse, accessToken);

      if (token.getExpiration().after(new Date())) {
        // Store them in the cache
        authCache.put(accessToken, new TokenCacheObject(token, auth));

        return true;
      }
View Full Code Here

        }

        ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

        if (client == null) {
          throw new InvalidClientException("Client not found: " + request.getClientId());
        }


        JWSAlgorithm alg = signedJwt.getHeader().getAlgorithm();

        if (client.getRequestObjectSigningAlg() == null ||
            !client.getRequestObjectSigningAlg().equals(alg)) {
          throw new InvalidClientException("Client's registered request object signing algorithm (" + client.getRequestObjectSigningAlg() + ") does not match request object's actual algorithm (" + alg.getName() + ")");
        }

        if (alg.equals(JWSAlgorithm.RS256)
            || alg.equals(JWSAlgorithm.RS384)
            || alg.equals(JWSAlgorithm.RS512)) {

          // it's RSA, need to find the JWK URI and fetch the key

          if (client.getJwksUri() == null) {
            throw new InvalidClientException("Client must have a JWKS URI registered to use signed request objects.");
          }

          // check JWT signature
          JwtSigningAndValidationService validator = validators.getValidator(client.getJwksUri());

          if (validator == null) {
            throw new InvalidClientException("Unable to create signature validator for client's JWKS URI: " + client.getJwksUri());
          }

          if (!validator.validateSignature(signedJwt)) {
            throw new InvalidClientException("Signature did not validate for presented JWT request object.");
          }
        } else if (alg.equals(JWSAlgorithm.HS256)
            || alg.equals(JWSAlgorithm.HS384)
            || alg.equals(JWSAlgorithm.HS512)) {

          // it's HMAC, we need to make a validator based on the client secret

          JwtSigningAndValidationService validator = symmetricCacheService.getSymmetricValidtor(client);

          if (validator == null) {
            throw new InvalidClientException("Unable to create signature validator for client's secret: " + client.getClientSecret());
          }

          if (!validator.validateSignature(signedJwt)) {
            throw new InvalidClientException("Signature did not validate for presented JWT request object.");
          }


        }


      } else if (jwt instanceof PlainJWT) {
        PlainJWT plainJwt = (PlainJWT)jwt;

        // need to check clientId first so that we can load the client to check other fields
        if (request.getClientId() == null) {
          request.setClientId(plainJwt.getJWTClaimsSet().getStringClaim("client_id"));
        }

        ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

        if (client == null) {
          throw new InvalidClientException("Client not found: " + request.getClientId());
        }

        if (client.getRequestObjectSigningAlg() == null) {
          throw new InvalidClientException("Client is not registered for unsigned request objects (no request_object_signing_alg registered)");
        } else if (!client.getRequestObjectSigningAlg().equals(Algorithm.NONE)) {
          throw new InvalidClientException("Client is not registered for unsigned request objects (request_object_signing_alg is " + client.getRequestObjectSigningAlg() +")");
        }

        // if we got here, we're OK, keep processing

      } else if (jwt instanceof EncryptedJWT) {

        EncryptedJWT encryptedJWT = (EncryptedJWT)jwt;

        // decrypt the jwt if we can

        encryptionService.decryptJwt(encryptedJWT);

        // TODO: what if the content is a signed JWT? (#525)

        if (!encryptedJWT.getState().equals(State.DECRYPTED)) {
          throw new InvalidClientException("Unable to decrypt the request object");
        }

        // need to check clientId first so that we can load the client to check other fields
        if (request.getClientId() == null) {
          request.setClientId(encryptedJWT.getJWTClaimsSet().getStringClaim("client_id"));
        }

        ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

        if (client == null) {
          throw new InvalidClientException("Client not found: " + request.getClientId());
        }


      }
View Full Code Here

    OAuth2AccessTokenEntity incomingToken = tokenServices.readAccessToken(incomingTokenValue);

    if (incomingToken.getScope().contains(SystemScopeService.ID_TOKEN_SCOPE)) {

      if (!client.getClientId().equals(tokenRequest.getClientId())) {
        throw new InvalidClientException("Not the right client for this token");
      }

      // it's an ID token, process it accordingly

      try {
View Full Code Here

    query.setParameter("code", code);

    AuthorizationCodeEntity result = JpaUtil.getSingleResult(query.getResultList());

    if (result == null) {
      throw new InvalidGrantException("JpaAuthorizationCodeRepository: no authorization code found for value " + code);
    }

    OAuth2Authentication authRequest = result.getAuthentication();

    manager.remove(result);
View Full Code Here

      OAuth2Authentication authentication = new OAuth2Authentication(getRequestFactory().createOAuth2Request(client, tokenRequest), incomingToken.getAuthenticationHolder().getAuthentication().getUserAuthentication());

      return authentication;

    } else {
      throw new InvalidScopeException("Invalid scope requested in chained request", approvedScopes);
    }

  }
View Full Code Here

   */
  private void validateScope(Set<String> requestedScopes, Set<String> clientScopes) throws InvalidScopeException {
    if (requestedScopes != null && !requestedScopes.isEmpty()) {
      if (clientScopes != null && !clientScopes.isEmpty()) {
        if (!scopeService.scopesMatch(clientScopes, requestedScopes)) {
          throw new InvalidScopeException("Invalid scope", clientScopes);
        }
      }
    }
  }
View Full Code Here

  @Override
  public AuthorizationRequest createAuthorizationRequest(Map<String, String> inputParams) {


    AuthorizationRequest request = new AuthorizationRequest(inputParams, Collections.<String, String> emptyMap(),
        inputParams.get(OAuth2Utils.CLIENT_ID),
        OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.SCOPE)), null,
        null, false, inputParams.get(OAuth2Utils.STATE),
        inputParams.get(OAuth2Utils.REDIRECT_URI),
        OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.RESPONSE_TYPE)));

    //Add extension parameters to the 'extensions' map

    if (inputParams.containsKey("prompt")) {
      request.getExtensions().put("prompt", inputParams.get("prompt"));
    }
    if (inputParams.containsKey("nonce")) {
      request.getExtensions().put("nonce", inputParams.get("nonce"));
    }

    if (inputParams.containsKey("claims")) {
      JsonObject claimsRequest = parseClaimRequest(inputParams.get("claims"));
      if (claimsRequest != null) {
        request.getExtensions().put("claims", claimsRequest.toString());
      }
    }

    if (inputParams.containsKey("max_age")) {
      request.getExtensions().put("max_age", inputParams.get("max_age"));
    }

    if (inputParams.containsKey("request")) {
      request.getExtensions().put("request", inputParams.get("request"));
      processRequestObject(inputParams.get("request"), request);
    }

    if (request.getClientId() != null) {
      try {
        ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

        if ((request.getScope() == null || request.getScope().isEmpty())) {
          Set<String> clientScopes = client.getScope();
          request.setScope(clientScopes);
        }

        if (request.getExtensions().get("max_age") == null && client.getDefaultMaxAge() != null) {
          request.getExtensions().put("max_age", client.getDefaultMaxAge().toString());
        }
      } catch (OAuth2Exception e) {
        logger.error("Caught OAuth2 exception trying to test client scopes and max age:", e);
      }
    }


    // add CSRF protection to the request on first parse
    String csrf = UUID.randomUUID().toString();
    request.getExtensions().put("csrf", csrf);



    return request;
  }
View Full Code Here

      chain.doFilter(req, res);
      return;
    }

    // we have to create our own auth request in order to get at all the parmeters appropriately
    AuthorizationRequest authRequest = authRequestFactory.createAuthorizationRequest(createRequestMap(request.getParameterMap()));

    ClientDetailsEntity client = null;

    try {
      client = clientService.loadClientByClientId(authRequest.getClientId());
    } catch (InvalidClientException e) {
      // no need to worry about this here, it would be caught elsewhere
    } catch (IllegalArgumentException e) {
      // no need to worry about this here, it would be caught elsewhere
    }

    if (authRequest.getExtensions().get("prompt") != null) {
      // we have a "prompt" parameter
      String prompt = (String)authRequest.getExtensions().get("prompt");
      List<String> prompts = Splitter.on(" ").splitToList(Strings.nullToEmpty(prompt));

      if (prompts.contains("none")) {
        logger.info("Client requested no prompt");
        // see if the user's logged in
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (auth != null) {
          // user's been logged in already (by session management)
          // we're OK, continue without prompting
          chain.doFilter(req, res);
        } else {
          // user hasn't been logged in, we need to "return an error"
          logger.info("User not logged in, no prompt requested, returning 403 from filter");
          response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
          return;
        }
      } else if (prompts.contains("login")) {

        // first see if the user's already been prompted in this session
        HttpSession session = request.getSession();
        if (session.getAttribute(PROMPTED) == null) {
          // user hasn't been PROMPTED yet, we need to check

          session.setAttribute(PROMPT_REQUESTED, Boolean.TRUE);

          // see if the user's logged in
          Authentication auth = SecurityContextHolder.getContext().getAuthentication();
          if (auth != null) {
            // user's been logged in already (by session management)
            // log them out and continue
            SecurityContextHolder.getContext().setAuthentication(null);
            chain.doFilter(req, res);
          } else {
            // user hasn't been logged in yet, we can keep going since we'll get there
            chain.doFilter(req, res);
          }
        } else {
          // user has been PROMPTED, we're fine

          // but first, undo the prompt tag
          session.removeAttribute(PROMPTED);
          chain.doFilter(req, res);
        }
      } else {
        // prompt parameter is a value we don't care about, not our business
        chain.doFilter(req, res);
      }

    } else if (authRequest.getExtensions().get("max_age") != null ||
        (client != null && client.getDefaultMaxAge() != null)) {

      // default to the client's stored value, check the string parameter
      Integer max = (client != null ? client.getDefaultMaxAge() : null);
      String maxAge = (String) authRequest.getExtensions().get("max_age");
      if (maxAge != null) {
        max = Integer.parseInt(maxAge);
      }

      if (max != null) {
View Full Code Here

    // then
    assertThat(permitted, is(false));
  }

  private ClientDetails clientWithId(String clientId) {
    ClientDetails client = mock(ClientDetails.class);
    given(client.getClientId()).willReturn(clientId);
    return client;
  }
View Full Code Here

TOP

Related Classes of org.springframework.security.oauth2.provider.OAuth2Request

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.