Package org.mitre.oauth2.model

Examples of org.mitre.oauth2.model.ClientDetailsEntityTest


    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


     * @throws IOException
     */
    private void readAuthenticationHolders(JsonReader reader) throws IOException {
        reader.beginArray();
        while (reader.hasNext()) {
            AuthenticationHolderEntity ahe = new AuthenticationHolderEntity();
            reader.beginObject();
            Long currentId = null;
            while (reader.hasNext()) {
                switch (reader.peek()) {
                    case END_OBJECT:
                        continue;
                    case NAME:
                        String name = reader.nextName();
                        if (reader.peek() == JsonToken.NULL) {
                            reader.skipValue();
                        } else if (name.equals("id")) {
                            currentId = reader.nextLong();
                        } else if (name.equals("ownerId")) {
                            //not needed
                            reader.skipValue();
                        } else if (name.equals("authentication")) {
                            OAuth2Request clientAuthorization = null;
                            Authentication userAuthentication = null;
                            reader.beginObject();
                            while (reader.hasNext()) {
                                switch (reader.peek()) {
                                    case END_OBJECT:
                                        continue;
                                    case NAME:
                                        String subName = reader.nextName();
                                        if (subName.equals("clientAuthorization")) {
                                            clientAuthorization = readAuthorizationRequest(reader);
                                        } else if (subName.equals("userAuthentication")) {
                                          if (reader.peek() == JsonToken.NULL) {
                                            reader.skipValue();
                                          } else {
                                              String authString = reader.nextString();
                                              userAuthentication = base64UrlDecodeObject(authString, Authentication.class);
                                          }
                                        } else {
                                            logger.debug("Found unexpected entry");
                                            reader.skipValue();
                                        }
                                        break;
                                    default:
                                        logger.debug("Found unexpected entry");
                                        reader.skipValue();
                                        continue;
                                }
                            }
                            reader.endObject();
                            OAuth2Authentication auth = new OAuth2Authentication(clientAuthorization, userAuthentication);
                            ahe.setAuthentication(auth);
                        } else {
                            logger.debug("Found unexpected entry");
                            reader.skipValue();
                        }
                        break;
View Full Code Here

        }
        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);
        }
        accessTokenToClientRefs.clear();
        for (Long oldAccessTokenId : accessTokenToAuthHolderRefs.keySet()) {
            Long oldAuthHolderId = accessTokenToAuthHolderRefs.get(oldAccessTokenId);
            Long newAuthHolderId = authHolderOldToNewIdMap.get(oldAuthHolderId);
            AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId);
            Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId);
            OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId);
            accessToken.setAuthenticationHolder(authHolder);
            tokenRepository.saveAccessToken(accessToken);
        }
View Full Code Here

  }

  @Test
  public void createAccessToken_checkAttachedAuthentication() {

    AuthenticationHolderEntity authHolder = Mockito.mock(AuthenticationHolderEntity.class);
    Mockito.when(authHolder.getAuthentication()).thenReturn(authentication);

    Mockito.when(authenticationHolderRepository.save(Matchers.any(AuthenticationHolderEntity.class))).thenReturn(authHolder);

    OAuth2AccessTokenEntity token = service.createAccessToken(authentication);
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

TOP

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

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.