Package org.mitre.oauth2.model

Examples of org.mitre.oauth2.model.OAuth2AccessTokenEntity


    OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity();
    token.setClient(client);
    token.setScope(scope);

    AuthenticationHolderEntity authHolder = new AuthenticationHolderEntity();
    authHolder.setAuthentication(authentication);
    authHolder = authenticationHolderRepository.save(authHolder);
    token.setAuthenticationHolder(authHolder);

    JWTClaimsSet claims = new JWTClaimsSet();
View Full Code Here


   * @return
   */
  @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
  public String registerNewProtectedResource(@RequestBody String jsonString, Model m) {

    ClientDetailsEntity newClient = null;
    try {
      newClient = ClientDetailsEntityJsonProcessor.parse(jsonString);
    } catch (JsonSyntaxException e) {
      // bad parse
      // didn't parse, this is a bad request
      logger.error("registerNewProtectedResource failed; submitted JSON is malformed");
      m.addAttribute("code", HttpStatus.BAD_REQUEST); // http 400
      return HttpCodeView.VIEWNAME;
    }

    if (newClient != null) {
      // it parsed!

      //
      // Now do some post-processing consistency checks on it
      //

      // clear out any spurious id/secret (clients don't get to pick)
      newClient.setClientId(null);
      newClient.setClientSecret(null);

      // do validation on the fields
      try {
        newClient = validateScopes(newClient);
        newClient = validateAuth(newClient);
      } catch (ValidationException ve) {
        // validation failed, return an error
        m.addAttribute("error", ve.getError());
        m.addAttribute("errorMessage", ve.getErrorDescription());
        m.addAttribute("code", ve.getStatus());
        return JsonErrorView.VIEWNAME;
      }


      // no grant types are allowed
      newClient.setGrantTypes(new HashSet<String>());
      newClient.setResponseTypes(new HashSet<String>());
      newClient.setRedirectUris(new HashSet<String>());

      // don't issue tokens to this client
      newClient.setAccessTokenValiditySeconds(0);
      newClient.setIdTokenValiditySeconds(0);
      newClient.setRefreshTokenValiditySeconds(0);

      // clear out unused fields
      newClient.setDefaultACRvalues(new HashSet<String>());
      newClient.setDefaultMaxAge(null);
      newClient.setIdTokenEncryptedResponseAlg(null);
      newClient.setIdTokenEncryptedResponseEnc(null);
      newClient.setIdTokenSignedResponseAlg(null);
      newClient.setInitiateLoginUri(null);
      newClient.setPostLogoutRedirectUri(null);
      newClient.setRequestObjectSigningAlg(null);
      newClient.setRequireAuthTime(null);
      newClient.setReuseRefreshToken(false);
      newClient.setSectorIdentifierUri(null);
      newClient.setSubjectType(null);
      newClient.setUserInfoEncryptedResponseAlg(null);
      newClient.setUserInfoEncryptedResponseEnc(null);
      newClient.setUserInfoSignedResponseAlg(null);

      // this client has been dynamically registered (obviously)
      newClient.setDynamicallyRegistered(true);

      // this client has access to the introspection endpoint
      newClient.setAllowIntrospection(true);

      // now save it
      try {
        ClientDetailsEntity savedClient = clientService.saveNewClient(newClient);

        // generate the registration access token
        OAuth2AccessTokenEntity token = connectTokenService.createResourceAccessToken(savedClient);
        tokenService.saveAccessToken(token);

        // send it all out to the view

        RegisteredClient registered = new RegisteredClient(savedClient, token.getValue(), config.getIssuer() + "resource/" + UriUtils.encodePathSegment(savedClient.getClientId(), "UTF-8"));
        m.addAttribute("client", registered);
        m.addAttribute("code", HttpStatus.CREATED); // http 201

        return ClientInformationResponseView.VIEWNAME;
      } catch (UnsupportedEncodingException e) {
View Full Code Here

   */
  @PreAuthorize("hasRole('ROLE_CLIENT') and #oauth2.hasScope('" + SystemScopeService.RESOURCE_TOKEN_SCOPE + "')")
  @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json")
  public String readResourceConfiguration(@PathVariable("id") String clientId, Model m, OAuth2Authentication auth) {

    ClientDetailsEntity client = clientService.loadClientByClientId(clientId);

    if (client != null && client.getClientId().equals(auth.getOAuth2Request().getClientId())) {



      try {
        // possibly update the token
        OAuth2AccessTokenEntity token = fetchValidRegistrationToken(auth, client);

        RegisteredClient registered = new RegisteredClient(client, token.getValue(), config.getIssuer() + "resource/" +  UriUtils.encodePathSegment(client.getClientId(), "UTF-8"));

        // send it all out to the view
        m.addAttribute("client", registered);
        m.addAttribute("code", HttpStatus.OK); // http 200

View Full Code Here

  @PreAuthorize("hasRole('ROLE_CLIENT') and #oauth2.hasScope('" + SystemScopeService.RESOURCE_TOKEN_SCOPE + "')")
  @RequestMapping(value = "/{id}", method = RequestMethod.PUT, produces = "application/json", consumes = "application/json")
  public String updateProtectedResource(@PathVariable("id") String clientId, @RequestBody String jsonString, Model m, OAuth2Authentication auth) {


    ClientDetailsEntity newClient = null;
    try {
      newClient = ClientDetailsEntityJsonProcessor.parse(jsonString);
    } catch (JsonSyntaxException e) {
      // bad parse
      // didn't parse, this is a bad request
      logger.error("updateProtectedResource failed; submitted JSON is malformed");
      m.addAttribute("code", HttpStatus.BAD_REQUEST); // http 400
      return HttpCodeView.VIEWNAME;
    }

    ClientDetailsEntity oldClient = clientService.loadClientByClientId(clientId);

    if (newClient != null && oldClient != null  // we have an existing client and the new one parsed
        && oldClient.getClientId().equals(auth.getOAuth2Request().getClientId()) // the client passed in the URI matches the one in the auth
        && oldClient.getClientId().equals(newClient.getClientId()) // the client passed in the body matches the one in the URI
        ) {

      // a client can't ask to update its own client secret to any particular value
      newClient.setClientSecret(oldClient.getClientSecret());

      newClient.setCreatedAt(oldClient.getCreatedAt());

      // no grant types are allowed
      newClient.setGrantTypes(new HashSet<String>());
      newClient.setResponseTypes(new HashSet<String>());
      newClient.setRedirectUris(new HashSet<String>());

      // don't issue tokens to this client
      newClient.setAccessTokenValiditySeconds(0);
      newClient.setIdTokenValiditySeconds(0);
      newClient.setRefreshTokenValiditySeconds(0);

      // clear out unused fields
      newClient.setDefaultACRvalues(new HashSet<String>());
      newClient.setDefaultMaxAge(null);
      newClient.setIdTokenEncryptedResponseAlg(null);
      newClient.setIdTokenEncryptedResponseEnc(null);
      newClient.setIdTokenSignedResponseAlg(null);
      newClient.setInitiateLoginUri(null);
      newClient.setPostLogoutRedirectUri(null);
      newClient.setRequestObjectSigningAlg(null);
      newClient.setRequireAuthTime(null);
      newClient.setReuseRefreshToken(false);
      newClient.setSectorIdentifierUri(null);
      newClient.setSubjectType(null);
      newClient.setUserInfoEncryptedResponseAlg(null);
      newClient.setUserInfoEncryptedResponseEnc(null);
      newClient.setUserInfoSignedResponseAlg(null);

      // this client has been dynamically registered (obviously)
      newClient.setDynamicallyRegistered(true);

      // this client has access to the introspection endpoint
      newClient.setAllowIntrospection(true);

      // do validation on the fields
      try {
        newClient = validateScopes(newClient);
        newClient = validateAuth(newClient);
      } catch (ValidationException ve) {
        // validation failed, return an error
        m.addAttribute("error", ve.getError());
        m.addAttribute("errorMessage", ve.getErrorDescription());
        m.addAttribute("code", ve.getStatus());
        return JsonErrorView.VIEWNAME;
      }


      try {
        // save the client
        ClientDetailsEntity savedClient = clientService.updateClient(oldClient, newClient);

        // possibly update the token
        OAuth2AccessTokenEntity token = fetchValidRegistrationToken(auth, savedClient);

        RegisteredClient registered = new RegisteredClient(savedClient, token.getValue(), config.getIssuer() + "resource/" + UriUtils.encodePathSegment(savedClient.getClientId(), "UTF-8"));

        // send it all out to the view
        m.addAttribute("client", registered);
        m.addAttribute("code", HttpStatus.OK); // http 200
View Full Code Here

   */
  @PreAuthorize("hasRole('ROLE_CLIENT') and #oauth2.hasScope('" + SystemScopeService.RESOURCE_TOKEN_SCOPE + "')")
  @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "application/json")
  public String deleteResource(@PathVariable("id") String clientId, Model m, OAuth2Authentication auth) {

    ClientDetailsEntity client = clientService.loadClientByClientId(clientId);

    if (client != null && client.getClientId().equals(auth.getOAuth2Request().getClientId())) {

      clientService.deleteClient(client);

      m.addAttribute("code", HttpStatus.NO_CONTENT); // http 204

View Full Code Here

    model.addAttribute("userInfo", userInfo);

    // content negotiation

    // start off by seeing if the client has registered for a signed/encrypted JWT from here
    ClientDetailsEntity client = clientService.loadClientByClientId(auth.getOAuth2Request().getClientId());
    model.addAttribute("client", client);
   
    List<MediaType> mediaTypes = MediaType.parseMediaTypes(acceptHeader);
    MediaType.sortBySpecificityAndQuality(mediaTypes);
   
    if (client.getUserInfoSignedResponseAlg() != null
        || client.getUserInfoEncryptedResponseAlg() != null
        || client.getUserInfoEncryptedResponseEnc() != null) {
      // client has a preference, see if they ask for plain JSON specifically on this request
      for (MediaType m : mediaTypes) {
        if (!m.isWildcardType() && m.isCompatibleWith(JOSE_MEDIA_TYPE)) {
          return UserInfoJwtView.VIEWNAME;
        } else if (!m.isWildcardType() && m.isCompatibleWith(MediaType.APPLICATION_JSON)) {
View Full Code Here

      clientIds.add(approvedSite.getClientId());
    }

    Map<Long, Integer> counts = getEmptyClientCountMap();
    for (String clientId : clientIds) {
      ClientDetailsEntity client = clientService.loadClientByClientId(clientId);
      counts.put(client.getId(), clientIds.count(clientId));
    }

    return counts;
  }
View Full Code Here

      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);
      }
    }
View Full Code Here

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

        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

      return JsonEntityView.VIEWNAME;
    }

        OAuth2AccessTokenEntity accessToken = null;
        OAuth2RefreshTokenEntity refreshToken = null;
    ClientDetailsEntity tokenClient;
    Set<String> scopes;
    UserInfo user;

    try {

      // check access tokens first (includes ID tokens)
      accessToken = tokenServices.readAccessToken(tokenValue);

      tokenClient = accessToken.getClient();
      scopes = accessToken.getScope();

            user = userInfoService.getByUsernameAndClientId(accessToken.getAuthenticationHolder().getAuthentication().getName(), tokenClient.getClientId());

    } catch (InvalidTokenException e) {
      logger.info("Verify failed; Invalid access token. Checking refresh token.");
      try {

        // check refresh tokens next
        refreshToken = tokenServices.getRefreshToken(tokenValue);

        tokenClient = refreshToken.getClient();
        scopes = refreshToken.getAuthenticationHolder().getAuthentication().getOAuth2Request().getScope();

        user = userInfoService.getByUsernameAndClientId(refreshToken.getAuthenticationHolder().getAuthentication().getName(), tokenClient.getClientId());

      } catch (InvalidTokenException e2) {
        logger.error("Verify failed; Invalid access/refresh token", e2);
        Map<String,Boolean> entity = ImmutableMap.of("active", Boolean.FALSE);
        model.addAttribute("entity", entity);
        return JsonEntityView.VIEWNAME;
      }
    }

        // clientID is the principal name in the authentication
        String clientId = p.getName();
        ClientDetailsEntity authClient = clientService.loadClientByClientId(clientId);

        if (authClient.isAllowIntrospection()) {
            if (introspectionAuthorizer.isIntrospectionPermitted(authClient, tokenClient, scopes)) {
                // if it's a valid token, we'll print out information on it
                Map<String, Object> entity = accessToken != null
                        ? introspectionResultAssembler.assembleFrom(accessToken, user)
                        : introspectionResultAssembler.assembleFrom(refreshToken, user);
View Full Code Here

TOP

Related Classes of org.mitre.oauth2.model.OAuth2AccessTokenEntity

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.