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:org.mitre.uma.web.PolicyAPI.java

/**
 * Update a specific policy/*from w w w  .jav a 2  s . c  o  m*/
 * @param rsid
 * @param pid
 * @param jsonString
 * @param m
 * @param auth
 * @return
 */
@RequestMapping(value = "/{rsid}" + POLICYURL
        + "/{pid}", method = RequestMethod.PUT, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String setClaimsForResourceSet(@PathVariable(value = "rsid") Long rsid,
        @PathVariable(value = "pid") Long pid, @RequestBody String jsonString, Model m, Authentication auth) {

    ResourceSet rs = resourceSetService.getById(rsid);

    if (rs == null) {
        m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        return HttpCodeView.VIEWNAME;
    }

    if (!rs.getOwner().equals(auth.getName())) {
        logger.warn("Unauthorized resource set request from bad user; expected " + rs.getOwner() + " got "
                + auth.getName());

        // authenticated user didn't match the owner of the resource set
        m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        return HttpCodeView.VIEWNAME;
    }

    Policy p = gson.fromJson(jsonString, Policy.class);

    if (!pid.equals(p.getId())) {
        logger.warn("Policy ID mismatch, expected " + pid + " got " + p.getId());

        m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
        return HttpCodeView.VIEWNAME;
    }

    for (Policy policy : rs.getPolicies()) {
        if (policy.getId().equals(pid)) {
            // found it!

            // find the existing claim IDs, make sure we're not overwriting anything from another policy
            Set<Long> claimIds = new HashSet<>();
            for (Claim claim : policy.getClaimsRequired()) {
                claimIds.add(claim.getId());
            }

            for (Claim claim : p.getClaimsRequired()) {
                if (claim.getId() != null && !claimIds.contains(claim.getId())) {
                    logger.warn("Tried to add a policy with a an unmatched claim ID: got " + claim.getId()
                            + " expected " + claimIds);
                    m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
                    return HttpCodeView.VIEWNAME;
                }
            }

            // update the existing object with the new values
            policy.setClaimsRequired(p.getClaimsRequired());
            policy.setName(p.getName());
            policy.setScopes(p.getScopes());

            resourceSetService.update(rs, rs);

            m.addAttribute(JsonEntityView.ENTITY, policy);
            return JsonEntityView.VIEWNAME;
        }
    }

    // if we made it this far, we haven't found it
    m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
    return HttpCodeView.VIEWNAME;
}

From source file:de.zib.gndms.dspace.service.SubspaceServiceImpl.java

@Override
@RequestMapping(value = "/_{subspace}/config", method = RequestMethod.PUT)
@Secured("ROLE_ADMIN")
public ResponseEntity<Void> setSubspaceConfiguration(@PathVariable final String subspace,
        @RequestBody final Configuration config, @RequestHeader("DN") final String dn) {

    GNDMSResponseHeader headers = getSubspaceHeaders(subspace, dn);

    try {//from ww  w .j a  v a2s .  c o  m
        SubspaceConfiguration subspaceConfig = SubspaceConfiguration.checkSubspaceConfig(config);

        if (!subspaceProvider.exists(subspace) || subspaceConfig.getMode() != SetupMode.UPDATE) {
            logger.warn("Subspace " + subspace + " cannot be updated");
            return new ResponseEntity<Void>(null, headers, HttpStatus.FORBIDDEN);
        }
        final EntityManager em = emf.createEntityManager();
        TxFrame tx = new TxFrame(em);

        try {

            SetupSubspaceAction action = new SetupSubspaceAction(subspaceConfig);
            action.setOwnEntityManager(em);
            logger.info("Calling action for updating the supspace " + subspace + ".");

            action.call();
        } finally {
            tx.finish();
            if (em != null && em.isOpen()) {
                em.close();
            }
        }
        return new ResponseEntity<Void>(null, headers, HttpStatus.OK);
    } catch (WrongConfigurationException e) {
        logger.warn(e.getMessage());
        return new ResponseEntity<Void>(null, headers, HttpStatus.BAD_REQUEST);
    }
}

From source file:com.redblackit.web.test.RestTemplateTestHelperTest.java

/**
 * Find a status code (not 2xx) which does not equal supplied code
 * /*from  w  ww  .  j  a v  a2  s . co  m*/
 * @param expectedStatusCode
 * @return different statusCode
 */
private HttpStatus getNonMatchingErrorStatusCode(HttpStatus expectedStatusCode) {
    return (expectedStatusCode.equals(HttpStatus.FORBIDDEN) ? HttpStatus.INTERNAL_SERVER_ERROR
            : HttpStatus.FORBIDDEN);
}

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

/**
 * Get the meta information for a client.
 * @param clientId//w  ww  .ja va2 s  . c o m
 * @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;
    }
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java

@Test
public void simpleAuthenticationRemoteLogServiceEnabledWithoutCsrfTokenTest() throws Exception {
    RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO();
    logRequestVO.setMessage("Test mesage!");
    logRequestVO.setLogLevel("DEBUG");

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization",
            "Basic " + new String(Base64.encode((getUsername() + ":" + getPassword()).getBytes("UTF-8"))));
    HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);

    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + baseApiPath + remoteLogEndpointPath);
    ResponseEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, entity, String.class);
    assertEquals(HttpStatus.FORBIDDEN, responseEntity.getStatusCode());
}

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

/**
 * Updates a Service/*from  ww w.  j a v a  2s.  co m*/
 * 
 * @return a reply...
 * @throws McBasicRestException 
 */
@RequestMapping(value = "/api/org/{orgMrn}/service/{serviceMrn}", method = RequestMethod.PUT)
@ResponseBody
@PreAuthorize("hasRole('SERVICE_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)")
public ResponseEntity<?> updateService(HttpServletRequest request, @PathVariable String orgMrn,
        @PathVariable String serviceMrn, @Valid @RequestBody Service input, BindingResult bindingResult)
        throws McBasicRestException {
    ValidateUtil.hasErrors(bindingResult, request);
    if (!serviceMrn.equals(input.getMrn())) {
        throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.URL_DATA_MISMATCH,
                request.getServletPath());
    }
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        // Check that the entity being updated belongs to the organization
        if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn)
                .equals(MrnUtil.getOrgShortNameFromEntityMrn(input.getMrn()))) {
            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) {
            // Update the keycloak client for the service if needed
            if (input.getOidcAccessType() != null && !input.getOidcAccessType().trim().isEmpty()) {
                // Check if the redirect uri is set if access type is "bearer-only"
                if (!"bearer-only".equals(input.getOidcAccessType()) && (input.getOidcRedirectUri() == null
                        || input.getOidcRedirectUri().trim().isEmpty())) {
                    throw new McBasicRestException(HttpStatus.BAD_REQUEST,
                            MCIdRegConstants.OIDC_MISSING_REDIRECT_URL, request.getServletPath());
                }
                keycloakAU.init(KeycloakAdminUtil.BROKER_INSTANCE);
                String clientSecret;
                try {
                    if (service.getOidcClientId() != null && !service.getOidcClientId().isEmpty()) {
                        clientSecret = keycloakAU.updateClient(service.getMrn(), service.getOidcAccessType(),
                                service.getOidcRedirectUri());
                    } else {
                        service.setOidcClientId(service.getMrn());
                        clientSecret = keycloakAU.createClient(service.getMrn(), service.getOidcAccessType(),
                                service.getOidcRedirectUri());
                    }
                } catch (IOException e) {
                    log.error("Error while updating/creation client in keycloak.", e);
                    throw new McBasicRestException(HttpStatus.INTERNAL_SERVER_ERROR,
                            MCIdRegConstants.ERROR_CREATING_KC_CLIENT, request.getServletPath());
                } catch (DuplicatedKeycloakEntry dke) {
                    throw new McBasicRestException(HttpStatus.CONFLICT, dke.getErrorMessage(),
                            request.getServletPath());
                }
                if ("confidential".equals(service.getOidcAccessType())) {
                    service.setOidcClientSecret(clientSecret);
                } else {
                    service.setOidcClientSecret(null);
                }
            }
            input.selectiveCopyTo(service);
            try {
                this.entityService.save(service);
                return new ResponseEntity<>(HttpStatus.OK);
            } catch (DataIntegrityViolationException e) {
                throw new McBasicRestException(HttpStatus.CONFLICT, e.getRootCause().getMessage(),
                        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:org.apigw.authserver.AuthorizationCodeProviderIntegrationtest.java

@Test
public void testInvalidScopeInResourceRequest() throws Exception {
    log.debug("testInvalidScopeInResourceRequest");
    String code = helper.getAuthorizationCode(CLIENT_ID, REDIRECT_URL, "CRM_SCHEDULING_WRITE");
    TokenResponseDTO accessToken = helper.getAccessToken(CLIENT_ID, REDIRECT_URL, code, "CRM_SCHEDULING_WRITE",
            HttpStatus.OK);//from  w  ww . j  a va2s  .  c  o  m
    assertNotNull(accessToken);

    // now make sure an unauthorized request fails the right way.
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization",
            String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, accessToken.getAccessToken()));
    ResponseEntity<String> response = serverRunning.getForString("/crm-scheduling-api/crm/scheduling/booking",
            headers);

    assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());

    String authenticate = response.getHeaders().getFirst("WWW-Authenticate");
    assertNotNull(authenticate);
    assertTrue(authenticate.startsWith("Bearer"));
    assertTrue(authenticate.contains("scope=\""));

}

From source file:de.zib.gndms.dspace.service.SliceServiceImpl.java

@Override
@RequestMapping(value = "/_{subspaceId}/_{sliceKindId}/_{sliceId}/files", method = RequestMethod.GET)
@Secured("ROLE_USER")
public ResponseEntity<List<FileStats>> listFiles(@PathVariable final String subspaceId,
        @PathVariable final String sliceKindId, @PathVariable final String sliceId,
        @RequestHeader("DN") final String dn) {
    final GNDMSResponseHeader headers = setHeaders(subspaceId, sliceKindId, sliceId, dn);

    try {/*  w  w  w . j a  va  2s .  c om*/
        final Subspace space = subspaceProvider.get(subspaceId);
        final Slice slice = findSliceOfKind(subspaceId, sliceKindId, sliceId);
        final String path = space.getPathForSlice(slice);

        File dir = new File(path);
        if (dir.exists() && dir.canRead() && dir.isDirectory()) {
            List<FileStats> files = new LinkedList<FileStats>();
            recursiveListFiles(path, "", files);

            headers.add("DiskUsage", String.valueOf(sliceProvider.getDiskUsage(subspaceId, sliceId)));

            return new ResponseEntity<List<FileStats>>(files, headers, HttpStatus.OK);
        } else {
            return new ResponseEntity<List<FileStats>>(null, headers, HttpStatus.FORBIDDEN);
        }
    } catch (NoSuchElementException ne) {
        logger.warn(ne.getMessage());
        return new ResponseEntity<List<FileStats>>(null, headers, HttpStatus.NOT_FOUND);
    }
}

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

/**
 * Get the meta information for a client.
 * @param clientId//  www .  ja v  a 2s  .  c o  m
 * @param m
 * @param auth
 * @return
 */
@PreAuthorize("hasRole('ROLE_CLIENT') and #oauth2.hasScope('" + SystemScopeService.REGISTRATION_TOKEN_SCOPE
        + "')")
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
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(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("readClientConfiguration failed, client ID mismatch: " + clientId + " and "
                + auth.getOAuth2Request().getClientId() + " do not match.");
        m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); // http 403

        return HttpCodeView.VIEWNAME;
    }
}