@PreAuthorize("hasRole('ROLE_ADMIN')")
  @RequestMapping(
      value = "/registration/{clientId}",
      method = RequestMethod.PUT,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public String rotateRegistrationTokenByClientId(
      @PathVariable("clientId") String clientId, ModelMap m, Principal p) {
    ClientDetailsEntity client = clientService.loadClientByClientId(clientId);

    if (client != null) {
      OAuth2AccessTokenEntity token =
          oidcTokenService.rotateRegistrationAccessTokenForClient(client);
      token = tokenService.saveAccessToken(token);

      if (token != null) {
        m.put(JsonEntityView.ENTITY, token);
        return TokenApiView.VIEWNAME;
      } else {
        m.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        m.put(JsonErrorView.ERROR_MESSAGE, "No registration token could be found.");
        return JsonErrorView.VIEWNAME;
      }
    } else {
      // client not found
      m.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
      m.put(
          JsonErrorView.ERROR_MESSAGE,
          "The requested client with id " + clientId + " could not be found.");
      return JsonErrorView.VIEWNAME;
    }
  }
  /**
   * Delete the indicated client from the system.
   *
   * @param clientId
   * @param m
   * @param auth
   * @return
   */
  @PreAuthorize(
      "hasRole('ROLE_CLIENT') and #oauth2.hasScope('"
          + OAuth2AccessTokenEntity.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

      return "httpCodeView";
    } else {
      // client mismatch
      logger.error(
          "readClientConfiguration failed, client ID mismatch: "
              + clientId
              + " and "
              + auth.getOAuth2Request().getClientId()
              + " do not match.");
      m.addAttribute("code", HttpStatus.FORBIDDEN); // http 403

      return "httpCodeView";
    }
  }
  /**
   * Delete the indicated client from the system.
   *
   * @param clientId
   * @param m
   * @param auth
   * @return
   */
  @PreAuthorize(
      "hasRole('ROLE_CLIENT') and #oauth2.hasScope('"
          + SystemScopeService.RESOURCE_TOKEN_SCOPE
          + "')")
  @RequestMapping(
      value = "/{id}",
      method = RequestMethod.DELETE,
      produces = MediaType.APPLICATION_JSON_VALUE)
  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(HttpCodeView.CODE, HttpStatus.NO_CONTENT); // http 204

      return HttpCodeView.VIEWNAME;
    } else {
      // client mismatch
      logger.error(
          "readClientConfiguration failed, client ID mismatch: "
              + clientId
              + " and "
              + auth.getOAuth2Request().getClientId()
              + " do not match.");
      m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); // http 403

      return HttpCodeView.VIEWNAME;
    }
  }
  /**
   * Get the meta information for a client.
   *
   * @param clientId
   * @param m
   * @param auth
   * @return
   */
  @PreAuthorize(
      "hasRole('ROLE_CLIENT') and #oauth2.hasScope('"
          + SystemScopeService.RESOURCE_TOKEN_SCOPE
          + "')")
  @RequestMapping(
      value = "/{id}",
      method = RequestMethod.GET,
      produces = MediaType.APPLICATION_JSON_VALUE)
  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(HttpCodeView.CODE, HttpStatus.OK); // http 200

        return ClientInformationResponseView.VIEWNAME;
      } catch (UnsupportedEncodingException e) {
        logger.error("Unsupported encoding", e);
        m.addAttribute(HttpCodeView.CODE, HttpStatus.INTERNAL_SERVER_ERROR);
        return HttpCodeView.VIEWNAME;
      }
    } else {
      // client mismatch
      logger.error(
          "readResourceConfiguration failed, client ID mismatch: "
              + clientId
              + " and "
              + auth.getOAuth2Request().getClientId()
              + " do not match.");
      m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); // http 403

      return HttpCodeView.VIEWNAME;
    }
  }
  /**
   * Prepares a collection of ApprovedSite mocks to be returned from the approvedSiteService and a
   * collection of ClientDetailEntity mocks to be returned from the clientService.
   */
  @Before
  public void prepare() {

    Mockito.reset(approvedSiteService, clientService);

    Mockito.when(ap1.getUserId()).thenReturn(userId1);
    Mockito.when(ap1.getClientId()).thenReturn(clientId1);

    Mockito.when(ap2.getUserId()).thenReturn(userId1);
    Mockito.when(ap2.getClientId()).thenReturn(clientId1);

    Mockito.when(ap3.getUserId()).thenReturn(userId2);
    Mockito.when(ap3.getClientId()).thenReturn(clientId2);

    Mockito.when(ap4.getUserId()).thenReturn(userId2);
    Mockito.when(ap4.getClientId()).thenReturn(clientId3);

    Mockito.when(ap5.getUserId()).thenReturn(userId2);
    Mockito.when(ap5.getClientId()).thenReturn(clientId1);

    Mockito.when(ap6.getUserId()).thenReturn(userId1);
    Mockito.when(ap6.getClientId()).thenReturn(clientId4);

    Mockito.when(approvedSiteService.getAll()).thenReturn(Sets.newHashSet(ap1, ap2, ap3, ap4));

    Mockito.when(client1.getId()).thenReturn(1L);
    Mockito.when(client2.getId()).thenReturn(2L);
    Mockito.when(client3.getId()).thenReturn(3L);
    Mockito.when(client4.getId()).thenReturn(4L);

    Mockito.when(clientService.getAllClients())
        .thenReturn(Sets.newHashSet(client1, client2, client3, client4));
    Mockito.when(clientService.loadClientByClientId(clientId1)).thenReturn(client1);
    Mockito.when(clientService.loadClientByClientId(clientId2)).thenReturn(client2);
    Mockito.when(clientService.loadClientByClientId(clientId3)).thenReturn(client3);
    Mockito.when(clientService.loadClientByClientId(clientId4)).thenReturn(client4);
  }
  /**
   * Get the meta information for a client.
   *
   * @param clientId
   * @param m
   * @param auth
   * @return
   */
  @PreAuthorize(
      "hasRole('ROLE_CLIENT') and #oauth2.hasScope('"
          + OAuth2AccessTokenEntity.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())) {

      // we return the token that we got in
      OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails();
      OAuth2AccessTokenEntity token = tokenService.readAccessToken(details.getTokenValue());

      // TODO: urlencode the client id for safety?
      RegisteredClient registered =
          new RegisteredClient(
              client, token.getValue(), config.getIssuer() + "register/" + client.getClientId());

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

      return "clientInformationResponseView";
    } else {
      // client mismatch
      logger.error(
          "readClientConfiguration failed, client ID mismatch: "
              + clientId
              + " and "
              + auth.getOAuth2Request().getClientId()
              + " do not match.");
      m.addAttribute("code", HttpStatus.FORBIDDEN); // http 403

      return "httpCodeView";
    }
  }
  @PreAuthorize("hasRole('ROLE_ADMIN')")
  @RequestMapping(
      value = "/client/{clientId}",
      method = RequestMethod.GET,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public String getAccessTokensByClientId(
      @PathVariable("clientId") String clientId, ModelMap m, Principal p) {

    ClientDetailsEntity client = clientService.loadClientByClientId(clientId);

    if (client != null) {
      List<OAuth2AccessTokenEntity> tokens = tokenService.getAccessTokensForClient(client);
      m.put(JsonEntityView.ENTITY, tokens);
      return TokenApiView.VIEWNAME;
    } else {
      // client not found
      m.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
      m.put(
          JsonErrorView.ERROR_MESSAGE,
          "The requested client with id " + clientId + " could not be found.");
      return JsonErrorView.VIEWNAME;
    }
  }
  /**
   * Update the metainformation for a given client.
   *
   * @param clientId
   * @param jsonString
   * @param m
   * @param auth
   * @return
   */
  @PreAuthorize(
      "hasRole('ROLE_CLIENT') and #oauth2.hasScope('"
          + OAuth2AccessTokenEntity.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 = ClientDetailsEntityJsonProcessor.parse(jsonString);
    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(oldClient.isAllowIntrospection());
      newClient.setAuthorities(oldClient.getAuthorities());
      newClient.setClientDescription(oldClient.getClientDescription());
      newClient.setCreatedAt(oldClient.getCreatedAt());
      newClient.setReuseRefreshToken(oldClient.isReuseRefreshToken());

      // set of scopes that are OK for clients to dynamically register for
      Set<SystemScope> dynScopes = scopeService.getDynReg();

      // scopes that the client is asking for
      Set<SystemScope> requestedScopes = scopeService.fromStrings(newClient.getScope());

      // the scopes that the client can have must be a subset of the dynamically allowed scopes
      Set<SystemScope> allowedScopes = Sets.intersection(dynScopes, requestedScopes);

      // make sure that the client doesn't ask for scopes it can't have
      newClient.setScope(scopeService.toStrings(allowedScopes));

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

        // we return the token that we got in
        // TODO: rotate this after some set amount of time
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails();
        OAuth2AccessTokenEntity token = tokenService.readAccessToken(details.getTokenValue());

        // TODO: urlencode the client id for safety?
        RegisteredClient registered =
            new RegisteredClient(
                savedClient,
                token.getValue(),
                config.getIssuer() + "register/" + savedClient.getClientId());

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

        return "clientInformationResponseView";
      } catch (IllegalArgumentException e) {
        logger.error("Couldn't save client", e);
        m.addAttribute("code", HttpStatus.BAD_REQUEST);

        return "httpCodeView";
      }
    } else {
      // client mismatch
      logger.error(
          "readClientConfiguration failed, client ID mismatch: "
              + clientId
              + " and "
              + auth.getOAuth2Request().getClientId()
              + " do not match.");
      m.addAttribute("code", HttpStatus.FORBIDDEN); // http 403

      return "httpCodeView";
    }
  }
  /**
   * Update the metainformation for a given client.
   *
   * @param clientId
   * @param jsonString
   * @param m
   * @param auth
   * @return
   */
  @PreAuthorize(
      "hasRole('ROLE_CLIENT') and #oauth2.hasScope('"
          + SystemScopeService.RESOURCE_TOKEN_SCOPE
          + "')")
  @RequestMapping(
      value = "/{id}",
      method = RequestMethod.PUT,
      produces = MediaType.APPLICATION_JSON_VALUE,
      consumes = MediaType.APPLICATION_JSON_VALUE)
  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(HttpCodeView.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.setPostLogoutRedirectUris(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(JsonErrorView.ERROR, ve.getError());
        m.addAttribute(JsonErrorView.ERROR_MESSAGE, ve.getErrorDescription());
        m.addAttribute(HttpCodeView.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(HttpCodeView.CODE, HttpStatus.OK); // http 200

        return ClientInformationResponseView.VIEWNAME;
      } catch (UnsupportedEncodingException e) {
        logger.error("Unsupported encoding", e);
        m.addAttribute(HttpCodeView.CODE, HttpStatus.INTERNAL_SERVER_ERROR);
        return HttpCodeView.VIEWNAME;
      } catch (IllegalArgumentException e) {
        logger.error("Couldn't save client", e);

        m.addAttribute(JsonErrorView.ERROR, "invalid_client_metadata");
        m.addAttribute(
            JsonErrorView.ERROR_MESSAGE,
            "Unable to save client due to invalid or inconsistent metadata.");
        m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400

        return JsonErrorView.VIEWNAME;
      }
    } else {
      // client mismatch
      logger.error(
          "updateProtectedResource"
              + " failed, client ID mismatch: "
              + clientId
              + " and "
              + auth.getOAuth2Request().getClientId()
              + " do not match.");
      m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); // http 403

      return HttpCodeView.VIEWNAME;
    }
  }