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:com.ge.predix.web.cors.CORSFilter.java

@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) throws ServletException, IOException {

    if (!isCrossOriginRequest(request)) {
        filterChain.doFilter(request, response);
        return;/*ww w  .j  ava  2  s  .c  o  m*/
    }

    if (isXhrRequest(request)) {
        String method = request.getMethod();
        if (!isCorsXhrAllowedMethod(method)) {
            response.setStatus(HttpStatus.METHOD_NOT_ALLOWED.value());
            return;
        }
        String origin = request.getHeader(HttpHeaders.ORIGIN);
        // Validate the origin so we don't reflect back any potentially dangerous content.
        URI originURI;
        try {
            originURI = new URI(origin);
        } catch (URISyntaxException e) {
            response.setStatus(HttpStatus.FORBIDDEN.value());
            return;
        }

        String requestUri = request.getRequestURI();
        if (!isCorsXhrAllowedRequestUri(requestUri) || !isCorsXhrAllowedOrigin(origin)) {
            response.setStatus(HttpStatus.FORBIDDEN.value());
            return;
        }
        response.addHeader("Access-Control-Allow-Origin", originURI.toString());
        if ("OPTIONS".equals(request.getMethod())) {
            buildCorsXhrPreFlightResponse(request, response);
        } else {
            filterChain.doFilter(request, response);
        }
        return;
    }

    response.addHeader("Access-Control-Allow-Origin", "*");
    if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
        // CORS "pre-flight" request
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Authorization");
        response.addHeader("Access-Control-Max-Age", "1728000");
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:com.chevres.rss.restapi.controller.UserController.java

@CrossOrigin
@RequestMapping(path = "/user/{username}", method = RequestMethod.PUT)
@ResponseBody/*from  w  w w. ja v a  2 s.  c  o  m*/
public ResponseEntity<String> updateUser(@RequestHeader(value = "User-token") String userToken,
        @PathVariable String username, @RequestBody User userRequest, BindingResult bindingResult) {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    UserDAO userDAO = context.getBean(UserDAO.class);
    UserAuthDAO userAuthDAO = context.getBean(UserAuthDAO.class);

    userUpdateValidator.validate(userRequest, bindingResult);
    if (bindingResult.hasErrors()) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("bad_params"), HttpStatus.BAD_REQUEST);
    }

    UserAuth userAuth = userAuthDAO.findByToken(userToken);
    if (userAuth == null) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("invalid_token"), HttpStatus.BAD_REQUEST);
    }

    User user = userDAO.findByUsername(username);
    if (user == null) {
        context.close();
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }

    boolean isAdmin = userDAO.isAdmin(userAuth.getIdUser());
    if ((!isAdmin && (userAuth.getIdUser() != user.getId())) || (userRequest.getType() != null && !isAdmin)) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("admin_required"), HttpStatus.FORBIDDEN);
    }

    if (userDAO.doesExist(userRequest.getUsername())
            && !user.getUsername().equalsIgnoreCase(userRequest.getUsername())) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("already_exist"), HttpStatus.BAD_REQUEST);
    }

    userDAO.updateUser(user, userRequest, isAdmin);
    context.close();

    return new ResponseEntity(new SuccessMessageResponse("success"), HttpStatus.OK);
}

From source file:org.mitre.uma.web.PermissionRegistrationEndpoint.java

@RequestMapping(method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String getPermissionTicket(@RequestBody String jsonString, Model m, Authentication auth) {

    ensureOAuthScope(auth, SystemScopeService.UMA_PROTECTION_SCOPE);

    try {/*from  ww  w .j  av a 2 s.  c o m*/

        // parse the permission request

        JsonElement el = parser.parse(jsonString);
        if (el.isJsonObject()) {
            JsonObject o = el.getAsJsonObject();

            Long rsid = getAsLong(o, "resource_set_id");
            Set<String> scopes = getAsStringSet(o, "scopes");

            if (rsid == null || scopes == null || scopes.isEmpty()) {
                // missing information
                m.addAttribute("code", HttpStatus.BAD_REQUEST);
                m.addAttribute("errorMessage",
                        "Missing required component of permission registration request.");
                return JsonErrorView.VIEWNAME;
            }

            // trim any restricted scopes
            Set<SystemScope> scopesRequested = scopeService.fromStrings(scopes);
            scopesRequested = scopeService.removeRestrictedAndReservedScopes(scopesRequested);
            scopes = scopeService.toStrings(scopesRequested);

            ResourceSet resourceSet = resourceSetService.getById(rsid);

            // requested resource set doesn't exist
            if (resourceSet == null) {
                m.addAttribute("code", HttpStatus.NOT_FOUND);
                m.addAttribute("errorMessage", "Requested resource set not found: " + rsid);
                return JsonErrorView.VIEWNAME;
            }

            // authorized user of the token doesn't match owner of the resource set
            if (!resourceSet.getOwner().equals(auth.getName())) {
                m.addAttribute("code", HttpStatus.FORBIDDEN);
                m.addAttribute("errorMessage",
                        "Party requesting permission is not owner of resource set, expected "
                                + resourceSet.getOwner() + " got " + auth.getName());
                return JsonErrorView.VIEWNAME;
            }

            // create the permission
            PermissionTicket permission = permissionService.createTicket(resourceSet, scopes);

            if (permission != null) {
                // we've created the permission, return the ticket
                JsonObject out = new JsonObject();
                out.addProperty("ticket", permission.getTicket());
                m.addAttribute("entity", out);

                m.addAttribute("code", HttpStatus.CREATED);

                return JsonEntityView.VIEWNAME;
            } else {
                // there was a failure creating the permission object

                m.addAttribute("code", HttpStatus.INTERNAL_SERVER_ERROR);
                m.addAttribute("errorMessage", "Unable to save permission and generate ticket.");

                return JsonErrorView.VIEWNAME;
            }

        } else {
            // malformed request
            m.addAttribute("code", HttpStatus.BAD_REQUEST);
            m.addAttribute("errorMessage", "Malformed JSON request.");
            return JsonErrorView.VIEWNAME;
        }
    } catch (JsonParseException e) {
        // malformed request
        m.addAttribute("code", HttpStatus.BAD_REQUEST);
        m.addAttribute("errorMessage", "Malformed JSON request.");
        return JsonErrorView.VIEWNAME;
    }

}

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

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

    GNDMSResponseHeader headers = getSubspaceHeaders(subspace, dn);

    if (subspaceProvider.exists(subspace)) {
        logger.info("Subspace " + subspace + " cannot be created because it already exists.");
        return new ResponseEntity<Facets>(null, headers, HttpStatus.FORBIDDEN);
    }//from   ww  w . j  ava2 s  .  c o  m

    // TODO: catch creation errors and return appropriate HttpStatus
    logger.info("Creating supspace " + subspace + ".");
    subspaceProvider.create("subspace: " + subspace + "; " + config);

    List<Facet> facets = listFacetsOfSubspace(subspace);
    return new ResponseEntity<Facets>(new Facets(facets), headers, HttpStatus.CREATED);
}

From source file:de.sainth.recipe.backend.rest.controller.CookbookController.java

@Secured({ "ROLE_USER", "ROLE_ADMIN" })
@RequestMapping(method = RequestMethod.POST)
HttpEntity<Cookbook> add(@Valid @RequestBody Cookbook cookbook) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication instanceof RecipeManagerAuthenticationToken) {
        RecipeManagerAuthenticationToken token = (RecipeManagerAuthenticationToken) authentication;
        if (ROLE_ADMIN.name().equals(token.getRole())
                || token.getPrincipal().equals(cookbook.getAuthor().getId())) {
            Cookbook c = repository.save(cookbook);
            return new ResponseEntity<>(c, HttpStatus.CREATED);
        } else {//from w w w .j av  a2  s . c  om
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }
    return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}

From source file:de.steilerdev.myVerein.server.controller.ContentController.java

/**
 * This function deletes the currently stored club logo. This action can only be performed by the super admin. The function is invoked by DELETEing the URI /content/clubLogo.
 * @param currentUser The currently logged in user.
 * @return An HTTP response with a status code. If an error occurred an error message is bundled into the response, otherwise a success message is available.
 *//*from w  w  w.j  a v a  2s  .  com*/
@RequestMapping(value = "clubLogo", method = RequestMethod.DELETE)
public @ResponseBody ResponseEntity<String> deleteClubLogo(@CurrentUser User currentUser) {
    if (currentUser == null) {
        logger.warn("An unauthenticated user tries to delete the club logo");
        return new ResponseEntity<>("You are not allowed to perform this action, please log in first",
                HttpStatus.FORBIDDEN);
    } else if (!currentUser.isSuperAdmin()) {
        logger.warn("A non-super admin tries to delete the club logo: " + currentUser.getEmail());
        return new ResponseEntity<>("You are not allowed to perform this action", HttpStatus.FORBIDDEN);
    } else if (gridFSRepository.findClubLogo() == null) {
        logger.warn("Unable to delete club logo, because it is not available");
        return new ResponseEntity<>("No club logo there to delete", HttpStatus.BAD_REQUEST);
    } else {
        gridFSRepository.deleteCurrentClubLogo();
        logger.info("Successfully delete the club logo");
        return new ResponseEntity<>("Successfully delete the club logo", HttpStatus.OK);
    }
}

From source file:org.avidj.zuul.rs.Zuul.java

/**
 * Obtain, upgrade, or downgrade a lock for the given {@code session}. Upgrades and downgrades are
 * possible along two dimensions: type and scope. Lock types are read ({@literal aka.} shared) and
 * write ({@literal aka.} exclusive). Lock scopes are shallow and deep. A shallow lock is only 
 * with respect to the specified lock path, a deep lock also locks the whole subtree below that 
 * path./*w  w  w .  ja v a  2s  .  c om*/
 * 
 * @param session the session to obtain a lock for 
 * @param type the type of lock to obtain, possible values are ({@code r})ead and 
 *     ({@code w})rite, default is ({@code w})write  
 * @param scope the scope of lock to obtain, possible values are ({@code s})shallow and 
 *     ({@code d})eep, default is ({@code d})eep  
 * @param request the HTTP request, provided by the REST framework
 * @param uriBuilder builder for the result location URI
 * @return {@code true}, iff the operation was successful
 */
@RequestMapping(value = "/s/{id}/**", method = { RequestMethod.POST, RequestMethod.PUT })
public ResponseEntity<String> lock(@PathVariable("id") String session,
        @RequestParam(value = "t", defaultValue = "w") String type,
        @RequestParam(value = "s", defaultValue = "s") String scope, HttpServletRequest request,
        UriComponentsBuilder uriBuilder) {
    // TODO: POST: lock (create resource)
    // TODO: PUT: upscope, downscope, lock reentry (return 226 IM used, return 404 as appropriate)
    final List<String> path = getLockPath(request, session);
    final LockType lockType = getLockType(type);
    final LockScope lockScope = getLockScope(scope);

    final boolean created = lm.lock(session, path, lockType, lockScope);
    HttpStatus httpStatus = created ? HttpStatus.CREATED : HttpStatus.FORBIDDEN;

    UriComponents uriComponents = uriBuilder.path("/s/{id}/{lockPath}").buildAndExpand(session,
            Strings.join("/", path));
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(uriComponents.toUri());
    return new ResponseEntity<String>(headers, httpStatus);
}

From source file:org.mitre.uma.web.AuthorizationRequestEndpoint.java

@RequestMapping(method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String authorizationRequest(@RequestBody String jsonString, Model m, Authentication auth) {

    AuthenticationUtilities.ensureOAuthScope(auth, SystemScopeService.UMA_AUTHORIZATION_SCOPE);

    JsonParser parser = new JsonParser();
    JsonElement e = parser.parse(jsonString);

    if (e.isJsonObject()) {
        JsonObject o = e.getAsJsonObject();

        if (o.has(TICKET)) {

            OAuth2AccessTokenEntity incomingRpt = null;
            if (o.has(RPT)) {
                String rptValue = o.get(RPT).getAsString();
                incomingRpt = tokenService.readAccessToken(rptValue);
            }//from  www  .ja va  2 s .  c o  m

            String ticketValue = o.get(TICKET).getAsString();

            PermissionTicket ticket = permissionService.getByTicket(ticketValue);

            if (ticket != null) {
                // found the ticket, see if it's any good

                ResourceSet rs = ticket.getPermission().getResourceSet();

                if (rs.getPolicies() == null || rs.getPolicies().isEmpty()) {
                    // the required claims are empty, this resource has no way to be authorized

                    m.addAttribute(JsonErrorView.ERROR, "not_authorized");
                    m.addAttribute(JsonErrorView.ERROR_MESSAGE, "This resource set can not be accessed.");
                    m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
                    return JsonErrorView.VIEWNAME;
                } else {
                    // claims weren't empty or missing, we need to check against what we have

                    ClaimProcessingResult result = claimsProcessingService.claimsAreSatisfied(rs, ticket);

                    if (result.isSatisfied()) {
                        // the service found what it was looking for, issue a token

                        // we need to downscope this based on the required set that was matched if it was matched
                        OAuth2Authentication o2auth = (OAuth2Authentication) auth;

                        OAuth2AccessTokenEntity token = umaTokenService.createRequestingPartyToken(o2auth,
                                ticket, result.getMatched());

                        // if we have an inbound RPT, throw it out because we're replacing it
                        if (incomingRpt != null) {
                            tokenService.revokeAccessToken(incomingRpt);
                        }

                        Map<String, String> entity = ImmutableMap.of("rpt", token.getValue());

                        m.addAttribute(JsonEntityView.ENTITY, entity);

                        return JsonEntityView.VIEWNAME;

                    } else {

                        // if we got here, the claim didn't match, forward the user to the claim gathering endpoint
                        JsonObject entity = new JsonObject();

                        entity.addProperty(JsonErrorView.ERROR, "need_info");
                        JsonObject details = new JsonObject();

                        JsonObject rpClaims = new JsonObject();
                        rpClaims.addProperty("redirect_user", true);
                        rpClaims.addProperty("ticket", ticketValue);
                        JsonArray req = new JsonArray();
                        for (Claim claim : result.getUnmatched()) {
                            JsonObject c = new JsonObject();
                            c.addProperty("name", claim.getName());
                            c.addProperty("friendly_name", claim.getFriendlyName());
                            c.addProperty("claim_type", claim.getClaimType());
                            JsonArray f = new JsonArray();
                            for (String format : claim.getClaimTokenFormat()) {
                                f.add(new JsonPrimitive(format));
                            }
                            c.add("claim_token_format", f);
                            JsonArray i = new JsonArray();
                            for (String issuer : claim.getIssuer()) {
                                i.add(new JsonPrimitive(issuer));
                            }
                            c.add("issuer", i);
                            req.add(c);
                        }
                        rpClaims.add("required_claims", req);
                        details.add("requesting_party_claims", rpClaims);
                        entity.add("error_details", details);

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

                }
            } else {
                // ticket wasn't found, return an error
                m.addAttribute(HttpStatus.BAD_REQUEST);
                m.addAttribute(JsonErrorView.ERROR, "invalid_ticket");
                return JsonErrorView.VIEWNAME;
            }

        } else {
            m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
            m.addAttribute(JsonErrorView.ERROR_MESSAGE, "Missing JSON elements.");
            return JsonErrorView.VIEWNAME;
        }

    } else {
        m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
        m.addAttribute(JsonErrorView.ERROR_MESSAGE, "Malformed JSON request.");
        return JsonErrorView.VIEWNAME;
    }

}