Package org.mitre.oauth2.model

Examples of org.mitre.oauth2.model.ClientDetailsEntity


    OAuth2AccessTokenEntity token = (OAuth2AccessTokenEntity) accessToken;
    OAuth2Request originalAuthRequest = authentication.getOAuth2Request();

    String clientId = originalAuthRequest.getClientId();
    ClientDetailsEntity client = clientService.loadClientByClientId(clientId);

    JWTClaimsSet claims = new JWTClaimsSet();

    claims.setAudience(Lists.newArrayList(clientId));
View Full Code Here


   * @return
   */
  @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
  public String registerNewClient(@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("registerNewClient 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 = validateResponseTypes(newClient);
        newClient = validateGrantTypes(newClient);
        newClient = validateRedirectUris(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;
      }
     
      if (newClient.getTokenEndpointAuthMethod() == null) {
        newClient.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC);
      }

      if (newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_BASIC ||
          newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_JWT ||
          newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_POST) {

        // we need to generate a secret
        newClient = clientService.generateClientSecret(newClient);
      }

      // set some defaults for token timeouts
      newClient.setAccessTokenValiditySeconds((int)TimeUnit.HOURS.toSeconds(1)); // access tokens good for 1hr
      newClient.setIdTokenValiditySeconds((int)TimeUnit.MINUTES.toSeconds(10)); // id tokens good for 10min
      newClient.setRefreshTokenValiditySeconds(null); // refresh tokens good until revoked

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

      // this client can't do token introspection
      newClient.setAllowIntrospection(false);

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

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

        // send it all out to the view

        RegisteredClient registered = new RegisteredClient(savedClient, token.getValue(), config.getIssuer() + "register/" + 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

    JwtBearerAssertionAuthenticationToken jwtAuth = (JwtBearerAssertionAuthenticationToken)authentication;


    try {
      ClientDetailsEntity client = clientService.loadClientByClientId(jwtAuth.getClientId());

      JWT jwt = jwtAuth.getJwt();
      ReadOnlyJWTClaimsSet jwtClaims = jwt.getJWTClaimsSet();

      // check the signature with nimbus
      if (jwt instanceof SignedJWT) {
        SignedJWT jws = (SignedJWT)jwt;

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

        if (client.getTokenEndpointAuthSigningAlg() != null &&
            !client.getTokenEndpointAuthSigningAlg().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 (client.getTokenEndpointAuthMethod() == null ||
            client.getTokenEndpointAuthMethod().equals(AuthMethod.NONE) ||
            client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_BASIC) ||
            client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_POST)) {
         
          // this client doesn't support this type of authentication
          throw new AuthenticationServiceException("Client does not support this authentication method.");
         
        } else if (client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY) &&
            (alg.equals(JWSAlgorithm.RS256)
                || alg.equals(JWSAlgorithm.RS384)
                || alg.equals(JWSAlgorithm.RS512))) {

          JwtSigningAndValidationService validator = validators.getValidator(client.getJwksUri());

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

          if (!validator.validateSignature(jws)) {
            throw new AuthenticationServiceException("Signature did not validate for presented JWT authentication.");
          }
        } else if (client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT) &&
            (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 AuthenticationServiceException("Unable to create signature validator for client's secret: " + client.getClientSecret());
          }

          if (!validator.validateSignature(jws)) {
            throw new AuthenticationServiceException("Signature did not validate for presented JWT authentication.");
          }

        }
      }

      // check the issuer
      if (jwtClaims.getIssuer() == null) {
        throw new AuthenticationServiceException("Assertion Token Issuer is null");
      } else if (!jwtClaims.getIssuer().equals(client.getClientId())){
        throw new AuthenticationServiceException("Issuers do not match, expected " + client.getClientId() + " got " + jwtClaims.getIssuer());
      }

      // check expiration
      if (jwtClaims.getExpirationTime() == null) {
        throw new AuthenticationServiceException("Assertion Token does not have required expiration claim");
      } else {
        // it's not null, see if it's expired
        Date now = new Date(System.currentTimeMillis() - (timeSkewAllowance * 1000));
        if (now.after(jwtClaims.getExpirationTime())) {
          throw new AuthenticationServiceException("Assertion Token is expired: " + jwtClaims.getExpirationTime());
        }
      }

      // check not before
      if (jwtClaims.getNotBeforeTime() != null) {
        Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000));
        if (now.before(jwtClaims.getNotBeforeTime())){
          throw new AuthenticationServiceException("Assertion Token not valid untill: " + jwtClaims.getNotBeforeTime());
        }
      }

      // check issued at
      if (jwtClaims.getIssueTime() != null) {
        // since it's not null, see if it was issued in the future
        Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000));
        if (now.before(jwtClaims.getIssueTime())) {
          throw new AuthenticationServiceException("Assertion Token was issued in the future: " + jwtClaims.getIssueTime());
        }
      }

      // check audience
      if (jwtClaims.getAudience() == null) {
        throw new AuthenticationServiceException("Assertion token audience is null");
      } else if (!(jwtClaims.getAudience().contains(config.getIssuer()) || jwtClaims.getAudience().contains(config.getIssuer() + "token"))) {
        throw new AuthenticationServiceException("Audience does not match, expected " + config.getIssuer() + " or " + (config.getIssuer() + "token") + " got " + jwtClaims.getAudience());
      }

      // IFF we managed to get all the way down here, the token is valid
      return new JwtBearerAssertionAuthenticationToken(client.getClientId(), jwt, client.getAuthorities());

    } catch (InvalidClientException e) {
      throw new UsernameNotFoundException("Could not find client: " + jwtAuth.getClientId());
    } catch (ParseException e) {

View Full Code Here

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

    ClientDetailsEntity client = clientService.loadClientByClientId(clientId);

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

      try {
        OAuth2AccessTokenEntity token = fetchValidRegistrationToken(auth, client);
        RegisteredClient registered = new RegisteredClient(client, token.getValue(), config.getIssuer() + "register/" +  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.REGISTRATION_TOKEN_SCOPE + "')")
  @RequestMapping(value = "/{id}", method = RequestMethod.PUT, produces = "application/json", consumes = "application/json")
  public String updateClient(@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("updateClient 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());

      // we need to copy over all of the local and SECOAUTH fields
      newClient.setAccessTokenValiditySeconds(oldClient.getAccessTokenValiditySeconds());
      newClient.setIdTokenValiditySeconds(oldClient.getIdTokenValiditySeconds());
      newClient.setRefreshTokenValiditySeconds(oldClient.getRefreshTokenValiditySeconds());
      newClient.setDynamicallyRegistered(true); // it's still dynamically registered
      newClient.setAllowIntrospection(false); // dynamically registered clients can't do introspection -- use the resource registration instead
      newClient.setAuthorities(oldClient.getAuthorities());
      newClient.setClientDescription(oldClient.getClientDescription());
      newClient.setCreatedAt(oldClient.getCreatedAt());
      newClient.setReuseRefreshToken(oldClient.isReuseRefreshToken());

      // do validation on the fields
      try {
        newClient = validateScopes(newClient);
        newClient = validateResponseTypes(newClient);
        newClient = validateGrantTypes(newClient);
        newClient = validateRedirectUris(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);

        OAuth2AccessTokenEntity token = fetchValidRegistrationToken(auth, savedClient);

        RegisteredClient registered = new RegisteredClient(savedClient, token.getValue(), config.getIssuer() + "register/" + 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

  /* (non-Javadoc)
   * @see org.mitre.oauth2.repository.OAuth2ClientRepository#deleteClient(org.mitre.oauth2.model.ClientDetailsEntity)
   */
  @Override
  public void deleteClient(ClientDetailsEntity client) {
    ClientDetailsEntity found = getById(client.getId());
    if (found != null) {
      manager.remove(found);
    } else {
      throw new IllegalArgumentException("Client not found: " + client);
    }
View Full Code Here

   */
  @PreAuthorize("hasRole('ROLE_CLIENT') and #oauth2.hasScope('" + SystemScopeService.REGISTRATION_TOKEN_SCOPE + "')")
  @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "application/json")
  public String deleteClient(@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

    }

    private void fixObjectReferences() {
        for (Long oldRefreshTokenId : refreshTokenToClientRefs.keySet()) {
            String clientRef = refreshTokenToClientRefs.get(oldRefreshTokenId);
            ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef);
            Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId);
            OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId);
            refreshToken.setClient(client);
            tokenRepository.saveRefreshToken(refreshToken);
        }
        refreshTokenToClientRefs.clear();
        for (Long oldRefreshTokenId : refreshTokenToAuthHolderRefs.keySet()) {
            Long oldAuthHolderId = refreshTokenToAuthHolderRefs.get(oldRefreshTokenId);
            Long newAuthHolderId = authHolderOldToNewIdMap.get(oldAuthHolderId);
            AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId);
            Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId);
            OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId);
            refreshToken.setAuthenticationHolder(authHolder);
            tokenRepository.saveRefreshToken(refreshToken);
        }
        refreshTokenToAuthHolderRefs.clear();
        for (Long oldAccessTokenId : accessTokenToClientRefs.keySet()) {
            String clientRef = accessTokenToClientRefs.get(oldAccessTokenId);
            ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef);
            Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId);
            OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId);
            accessToken.setClient(client);
            tokenRepository.saveAccessToken(accessToken);
        }
View Full Code Here

   * several ApprovedSite objects for use in unit tests.
   */
  @Before
  public void prepare() {

    client = new ClientDetailsEntity();
    client.setClientId(clientId);

    site1 = new ApprovedSite();
    site1.setId(1L);
    site1.setUserId("user1");
View Full Code Here

    userInfoRegular = new DefaultUserInfo();
    userInfoRegular.setPreferredUsername(regularUsername);
    userInfoRegular.setSub(regularSub);

    publicClient1 = new ClientDetailsEntity();
    publicClient1.setClientId(publicClientId1);

    publicClient2 = new ClientDetailsEntity();
    publicClient2.setClientId(publicClientId2);
    publicClient2.setSubjectType(SubjectType.PUBLIC);

    // pairwise set 1
    pairwiseClient1 = new ClientDetailsEntity();
    pairwiseClient1.setClientId(pairwiseClientId1);
    pairwiseClient1.setSubjectType(SubjectType.PAIRWISE);
    pairwiseClient1.setSectorIdentifierUri(sectorIdentifier1);

    pairwiseClient2 = new ClientDetailsEntity();
    pairwiseClient2.setClientId(pairwiseClientId2);
    pairwiseClient2.setSubjectType(SubjectType.PAIRWISE);
    pairwiseClient2.setSectorIdentifierUri(sectorIdentifier2);

    // pairwise set 2
    pairwiseClient3 = new ClientDetailsEntity();
    pairwiseClient3.setClientId(pairwiseClientId3);
    pairwiseClient3.setSubjectType(SubjectType.PAIRWISE);
    pairwiseClient3.setSectorIdentifierUri(sectorIdentifier3);

    // pairwise with null sector
    pairwiseClient4 = new ClientDetailsEntity();
    pairwiseClient4.setClientId(pairwiseClientId4);
    pairwiseClient4.setSubjectType(SubjectType.PAIRWISE);


View Full Code Here

TOP

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

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.