Example usage for org.springframework.http HttpStatus FORBIDDEN

List of usage examples for org.springframework.http HttpStatus FORBIDDEN

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus FORBIDDEN.

Prototype

HttpStatus FORBIDDEN

To view the source code for org.springframework.http HttpStatus FORBIDDEN.

Click Source Link

Document

403 Forbidden .

Usage

From source file:net.maritimecloud.identityregistry.controllers.UserController.java

/**
 * Sync user from keycloak, diff from create/update user is that this should only be done by
 * the keycloak sync-mechanism. //from   www.j av a  2  s. c o m
 * 
 * @return a reply...
 * @throws McBasicRestException 
 */
@ApiOperation(hidden = true, value = "Sync user from keycloak")
@RequestMapping(value = "/api/org/{orgMrn}/user-sync/", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public ResponseEntity<?> syncUser(HttpServletRequest request, @PathVariable String orgMrn,
        @RequestBody User input, @RequestParam(value = "org-name", required = false) String orgName,
        @RequestParam(value = "org-address", required = false) String orgAddress) throws McBasicRestException {
    if (!AccessControlUtil.isUserSync(this.userSyncMRN, this.userSyncO, this.userSyncOU, this.userSyncC)) {
        throw new McBasicRestException(HttpStatus.FORBIDDEN, MCIdRegConstants.MISSING_RIGHTS,
                request.getServletPath());
    }
    Organization org = this.organizationService.getOrganizationByMrnNoFilter(orgMrn);
    // The organization does not exists - check if this a an organization hosted by an external "validator".
    if (org == null && orgAddress != null && orgName != null) {
        // Check that the org shortname is the same for the orgMrn and originalErrorMessage
        String orgShortname = MrnUtil.getOrgShortNameFromOrgMrn(orgMrn);
        if (!orgShortname.equals(MrnUtil.getOrgShortNameFromEntityMrn(input.getMrn()))) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.URL_DATA_MISMATCH,
                    request.getServletPath());
        }
        // Since the permissions of this user will be used as a template for administrator permissions, it must be
        // verified that the user actually has some permissions.
        if (input.getPermissions() == null || input.getPermissions().isEmpty()) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.ROLE_NOT_FOUND,
                    request.getServletPath());
        }
        // Check validators?
        String orgValidator = MrnUtil.getOrgValidatorFromOrgShortname(orgShortname);
        // Create the new org based on given info
        org = new Organization();
        org.setName(orgName);
        org.setMrn(orgMrn);
        org.setApproved(true);
        org.setEmail(input.getEmail());
        // Extract domain-name from the user email and use that for org url.
        int at = input.getEmail().indexOf("@");
        String url = "http://" + input.getEmail().substring(at + 1);
        org.setUrl(url);
        // Extract country from address
        String country;
        String address;
        int lastComma = orgAddress.lastIndexOf(",");
        if (lastComma > 0) {
            country = orgAddress.substring(lastComma + 1).trim();
            address = orgAddress.substring(0, lastComma).trim();
        } else {
            country = "The Seven Seas";
            address = orgAddress;
        }
        org.setAddress(address);
        org.setCountry(country);
        org.setFederationType("external-idp");
        // save the new organization
        org = this.organizationService.save(org);
        // Create the initial roles for the organization. The permissions of the first user is used to define the ORG_ADMIN
        // Come on! That's a great idea!!
        if (input.getPermissions() != null) {
            for (String permission : input.getPermissions().split(",")) {
                Role newRole = new Role();
                newRole.setRoleName("ROLE_ORG_ADMIN");
                newRole.setPermission(permission.trim());
                newRole.setIdOrganization(org.getId());
                this.roleService.save(newRole);
            }
        }
    }

    if (org != null) {
        String userMrn = input.getMrn();
        if (userMrn == null || userMrn.isEmpty()) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.USER_NOT_FOUND,
                    request.getServletPath());
        }
        User oldUser = this.entityService.getByMrn(userMrn);
        // If user does not exists, we create him
        if (oldUser == null) {
            input.setIdOrganization(org.getId());
            this.entityService.save(input);
        } else {
            // Update the existing user and save
            oldUser = input.selectiveCopyTo(oldUser);
            this.entityService.save(oldUser);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:net.maritimecloud.identityregistry.controllers.OrganizationController.java

/**
 * Revokes certificate for the user identified by the given ID
 *
 * @return a reply.../*from   w  w w.  j a  va  2 s.com*/
 * @throws McBasicRestException
 */
@RequestMapping(value = "/api/org/{orgMrn}/certificate/{certId}/revoke", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@PreAuthorize("hasRole('ORG_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)")
public ResponseEntity<?> revokeOrgCert(HttpServletRequest request, @PathVariable String orgMrn,
        @PathVariable Long certId, @Valid @RequestBody CertificateRevocation input)
        throws McBasicRestException {
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        Certificate cert = this.certificateService.getCertificateById(certId);
        Organization certOrg = cert.getOrganization();
        if (certOrg != null && certOrg.getId().compareTo(org.getId()) == 0) {
            this.revokeCertificate(certId, input, request);
            return new ResponseEntity<>(HttpStatus.OK);
        }
        throw new McBasicRestException(HttpStatus.FORBIDDEN, MCIdRegConstants.MISSING_RIGHTS,
                request.getServletPath());
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:org.mitreid.multiparty.web.ResourceController.java

@RequestMapping(value = "/api/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody/* w  w  w. j  av  a 2  s . c  o m*/
public Resource getResource(@PathVariable("id") String rsId,
        @RequestHeader(value = "Authorization", required = false) String authorization,
        HttpServletResponse response) throws JsonIOException, IOException {
    // load the resource from the ID
    Resource res = resourceService.getById(rsId);

    if (res == null) {
        // no resource with that ID, return a 404
        response.setStatus(HttpStatus.NOT_FOUND.value());
        return null;
    }

    // get the resource set associated with the resource
    SharedResourceSet resourceSet = resourceService.getSharedResourceSetForResource(res);

    if (resourceSet == null) {
        // not shared yet, return a 404
        response.setStatus(HttpStatus.NOT_FOUND.value());
        return null;
    }

    // load the server configuration based on the issuer from the resource set
    MultipartyServerConfiguration server = serverConfig.getServerConfiguration(resourceSet.getIssuer());
    // load client configuration (register if needed)
    RegisteredClient client = clientConfig.getClientConfiguration(server);
    // get an access token
    String protectionAccessTokenValue = acccessTokenService.getAccessToken(server, client);

    // get a permission ticket for this resource set
    String ticket = getTicket(resourceSet, server, client, protectionAccessTokenValue);

    if (Strings.isNullOrEmpty(ticket)) {
        // couldn't get a ticket for some reason
        response.addHeader(HttpHeaders.WARNING, "199 - UMA Authorization Server Unreachable");
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        return null;
    }

    // add the issuer and ticket to the response header
    response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "UMA realm=\"multiparty-resource\", as_uri=\""
            + resourceSet.getIssuer() + "\", ticket=\"" + ticket + "\"");

    // check the request to get the incoming token
    if (Strings.isNullOrEmpty(authorization) || !authorization.toLowerCase().startsWith("bearer ")) {
        // no token, return a 401
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return null;
    }
    String incomingAccessToken = authorization.substring("bearer ".length());
    // introspect/load the token
    JsonObject introspected = introspectToken(incomingAccessToken, server, client, protectionAccessTokenValue);

    if (!introspected.get("active").getAsBoolean()) {
        // token wasn't active, forbidden
        response.setStatus(HttpStatus.FORBIDDEN.value());
        return null;
    }

    JsonArray permissions = introspected.get("permissions").getAsJsonArray();
    for (JsonElement permission : permissions) {
        // check to see that the token is for the right resource set
        String permissionRsid = permission.getAsJsonObject().get("resource_set_id").getAsString();
        if (permissionRsid.equals(resourceSet.getRsid())) {
            // check to see if the token has the right scopes
            Set<String> scopes = JsonUtils.getAsStringSet(permission.getAsJsonObject(), "permission_scopes");

            if (scopes.contains("read")) {
                // if the token is good enough, return the resource
                return res;
            }
        }
    }

    // if we fall down here then we didn't find a workable permission
    response.setStatus(HttpStatus.FORBIDDEN.value());
    return null;

}

From source file:org.mitre.openid.connect.web.ProtectedResourceRegistrationEndpoint.java

/**
 * Update the metainformation for a given client.
 * @param clientId//from  w ww .j  av  a  2  s  . c  om
 * @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;
    }
}

From source file:org.mitre.openid.connect.web.DynamicClientRegistrationEndpoint.java

/**
 * Update the metainformation for a given client.
 * @param clientId//w  ww  .  j a v  a2 s .co m
 * @param jsonString
 * @param m
 * @param auth
 * @return
 */
@PreAuthorize("hasRole('ROLE_CLIENT') and #oauth2.hasScope('" + SystemScopeService.REGISTRATION_TOKEN_SCOPE
        + "')")
@RequestMapping(value = "/{id}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
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(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());

        // 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(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);

            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(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("updateClient failed, client ID mismatch: " + clientId + " and "
                + auth.getOAuth2Request().getClientId() + " do not match.");
        m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); // http 403

        return HttpCodeView.VIEWNAME;
    }
}

From source file:com.erudika.scoold.ScooldServer.java

/**
 * @return Error page registry bean/*ww w .  ja v  a 2 s .  c  o m*/
 */
@Bean
public ErrorPageRegistrar errorPageRegistrar() {
    return new ErrorPageRegistrar() {
        @Override
        public void registerErrorPages(ErrorPageRegistry epr) {
            epr.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/not-found"));
            epr.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/error/403"));
            epr.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401"));
            epr.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500"));
            epr.addErrorPages(new ErrorPage(HttpStatus.SERVICE_UNAVAILABLE, "/error/503"));
            epr.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400"));
            epr.addErrorPages(new ErrorPage(HttpStatus.METHOD_NOT_ALLOWED, "/error/405"));
            epr.addErrorPages(new ErrorPage(Exception.class, "/error/500"));
        }
    };
}

From source file:org.mitre.openid.connect.web.ProtectedResourceRegistrationEndpoint.java

/**
 * Delete the indicated client from the system.
 * @param clientId/*from   www  .  j a  va 2 s.  co  m*/
 * @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;
    }
}

From source file:org.mitre.openid.connect.web.DynamicClientRegistrationEndpoint.java

/**
 * Delete the indicated client from the system.
 * @param clientId//w  w w  .ja v a2  s.c o  m
 * @param m
 * @param auth
 * @return
 */
@PreAuthorize("hasRole('ROLE_CLIENT') and #oauth2.hasScope('" + SystemScopeService.REGISTRATION_TOKEN_SCOPE
        + "')")
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
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(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;
    }
}

From source file:net.maritimecloud.identityregistry.controllers.ServiceController.java

/**
 * Returns keycloak.json the service identified by the given ID
 *
 * @return a reply...//from   w  w  w.  j a  v a 2s.  co  m
 * @throws McBasicRestException
 */
@RequestMapping(value = "/api/org/{orgMrn}/service/{serviceMrn}/keycloakjson", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
@ResponseBody
@PreAuthorize("hasRole('SERVICE_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)")
public ResponseEntity<String> getServiceKeycloakJson(HttpServletRequest request, @PathVariable String orgMrn,
        @PathVariable String serviceMrn) throws McBasicRestException {
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        // Check that the entity being queried belongs to the organization
        if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn)
                .equals(MrnUtil.getOrgShortNameFromEntityMrn(serviceMrn))) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS,
                    request.getServletPath());
        }
        Service service = this.entityService.getByMrn(serviceMrn);
        if (service == null) {
            throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ENTITY_NOT_FOUND,
                    request.getServletPath());
        }
        if (service.getIdOrganization().compareTo(org.getId()) == 0) {
            // Get the keycloak json for the client the service represents if it exists
            if (service.getOidcAccessType() != null && !service.getOidcAccessType().trim().isEmpty()) {
                keycloakAU.init(KeycloakAdminUtil.BROKER_INSTANCE);
                String keycloakJson = keycloakAU.getClientKeycloakJson(service.getMrn());
                return new ResponseEntity<>(keycloakJson, HttpStatus.OK);
            }
            throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.OIDC_CONF_FILE_NOT_AVAILABLE,
                    request.getServletPath());
        }
        throw new McBasicRestException(HttpStatus.FORBIDDEN, MCIdRegConstants.MISSING_RIGHTS,
                request.getServletPath());
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:de.hska.ld.content.controller.DocumentControllerIntegrationTest.java

@Test
public void testShareDocumentWithUserWithUnsufficientRights() throws Exception {
    // create userA
    User userA = CoreUtil.newUser();/*w  w  w  .j ava  2s .co  m*/
    HttpResponse responseA = UserSession.admin().post(RESOURCE_USER, userA);
    Assert.assertEquals(HttpStatus.CREATED, ResponseHelper.getStatusCode(responseA));
    UserSession userASession = new UserSession();
    userASession = userASession.login(userA.getUsername(), DEFAULT_PASSWORD);

    // create userB
    User userB = CoreUtil.newUser();
    HttpResponse responseB = UserSession.admin().post(RESOURCE_USER, userB);
    Assert.assertEquals(HttpStatus.CREATED, ResponseHelper.getStatusCode(responseB));
    userB = ResponseHelper.getBody(responseB, User.class);
    UserSession userBSession = new UserSession();
    Assert.assertNotNull(userB);
    userBSession = userBSession.login(userB.getUsername(), DEFAULT_PASSWORD);

    // userA adds document
    HttpResponse addDocument = userASession.post(RESOURCE_DOCUMENT, document);
    Assert.assertEquals(HttpStatus.CREATED, ResponseHelper.getStatusCode(addDocument));
    Document respondedDocument = ResponseHelper.getBody(addDocument, Document.class);
    Assert.assertNotNull(respondedDocument);
    Assert.assertNotNull(respondedDocument.getId());

    // userA shares document to read
    HttpResponse shareDocument = userASession.post(RESOURCE_DOCUMENT + "/" + respondedDocument.getId()
            + "/share?userIds=" + userB.getId() + "&permissions=READ", null);
    Assert.assertEquals(HttpStatus.OK, ResponseHelper.getStatusCode(shareDocument));

    // userB should be able to READ
    HttpResponse readDocument = userBSession.get(RESOURCE_DOCUMENT + "/" + respondedDocument.getId());
    Assert.assertEquals(HttpStatus.OK, ResponseHelper.getStatusCode(readDocument));

    // userB should not be able to WRITE
    HttpResponse updateDocument = userBSession.put(RESOURCE_DOCUMENT + "/" + respondedDocument.getId(),
            respondedDocument);
    Assert.assertEquals(HttpStatus.FORBIDDEN, ResponseHelper.getStatusCode(updateDocument));
}