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:jetbrains.buildServer.projectPush.PostProjectToSandboxController.java

@Nullable
@Override//from ww w .ja v a  2 s.  com
protected ModelAndView doHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response)
        throws Exception {
    if (!isPost(request)) {
        response.sendError(HttpStatus.METHOD_NOT_ALLOWED.value());
        return null;
    }

    final StringBuilder stringBuffer = new StringBuilder();
    try {
        String line;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
            stringBuffer.append(line);
    } catch (Exception e) {
        response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
        return null;
    }

    final String projectName = stringBuffer.toString();
    if (projectName.isEmpty()) {
        response.sendError(HttpStatus.BAD_REQUEST.value(), "Project name is empty.");
        return null;
    }

    if (mySettings.isDisabled()) {
        response.sendError(HttpStatus.FORBIDDEN.value(), "Sandbox disabled.");
        return null;
    }

    SUser user;
    user = SessionUser.getUser(request);
    if (user == null) {
        user = myAuthHelper.getAuthenticatedUser(request, response);
    }
    if (user == null)
        return null;

    final Role projectAdminRole = myRolesHelper.findProjectAdminRole();
    if (projectAdminRole == null) {
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "Failed to locate Project Admin role on the server.");
        return null;
    }

    final SProject project;
    try {
        final String sandboxProjectId = mySettings.getSandboxProjectId();
        final SProject sandboxProject = myProjectManager.findProjectByExternalId(sandboxProjectId);
        if (sandboxProject == null) {
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(),
                    "Failed to locate sandbox project by ID " + sandboxProjectId);
            return null;
        }

        if (sandboxProject.findProjectByName(projectName) != null) {
            response.sendError(HttpStatus.CONFLICT.value(),
                    "Project with name " + projectName + " already exists.");
            return null;
        }

        project = sandboxProject.createProject(
                myProjectIdentifiersManager.generateNewExternalId(null, projectName, null), projectName);
        project.persist();
    } catch (Exception e) {
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        return null;
    }

    try {
        myRolesHelper.addRole(user, RoleScope.projectScope(project.getProjectId()), projectAdminRole);
    } catch (Throwable throwable) {
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), throwable.getMessage());
        return null;
    }

    response.setStatus(HttpStatus.CREATED.value());
    response.setHeader(HttpHeaders.LOCATION, RESTApiHelper.getProjectURI(project));

    return null;
}

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

@Secured({ "ROLE_USER", "ROLE_ADMIN" })
@RequestMapping(value = "{id}/password", method = RequestMethod.PUT)
HttpEntity<User> updatePassword(@PathVariable("id") Long id, @Valid @RequestBody String password) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    RecipeManagerAuthenticationToken token = (RecipeManagerAuthenticationToken) authentication;
    if (ROLE_ADMIN.name().equals(token.getRole())
            || (ROLE_USER.name().equals(token.getRole()) && token.getPrincipal().equals(id))) {
        User u = repository.updatePassword(id, password);
        return new ResponseEntity<>(u, HttpStatus.OK);
    } else {/*w ww  . j  av  a  2  s  .  c  o m*/
        return new ResponseEntity<>(HttpStatus.FORBIDDEN);
    }
}

From source file:org.craftercms.profile.controllers.rest.ExceptionHandlers.java

@ExceptionHandler(ExpiredAccessTokenException.class)
public ResponseEntity<Object> handleExpiredAccessTokenException(ExpiredAccessTokenException e,
        WebRequest request) {/*from   ww  w . ja  v  a2 s.c om*/
    return handleExceptionInternal(e, HttpStatus.FORBIDDEN, ErrorCode.EXPIRED_ACCESS_TOKEN, request);
}

From source file:com.fbr.services.SecurityService.java

@Transactional
public HttpStatus checkAuthenticationAndAuthorization(HttpServletRequest httpRequest) {

    logger.debug("Request uri is {}" + httpRequest.getRequestURI());
    if (!LOGIN_EXCEPTION_URIS.contains(httpRequest.getRequestURI())) {

        String sessionId = httpRequest.getHeader("sessionId");
        Enumeration<String> headers = httpRequest.getHeaderNames();
        if (headers != null) {
            logger.debug("Headers are");
            while (headers.hasMoreElements()) {
                logger.debug(headers.nextElement());
            }//from  w  w w  .j  a v  a 2 s  .  c  om
        }
        if (sessionId != null) {
            Date idleExpirationDate = DateUtils.addMinutes(new Date(), -idle_session_timeout);
            SessionDbType sessionDbType = sessionDao.validateSessionId(sessionId, idleExpirationDate);
            if (sessionDbType == null) {
                logger.debug("Session " + sessionId + " was not found in the database");
                return HttpStatus.UNAUTHORIZED;
            }
            logger.debug("Session " + sessionId + " is validated");
            sessionDbType.setLastAccessTime(new Date());
            sessionDao.update(sessionDbType);
            if (!isAuthorizedForApi(httpRequest.getMethod(), httpRequest.getRequestURI(),
                    httpRequest.getQueryString(), sessionDbType)) {
                logger.debug(httpRequest.getMethod() + " on " + httpRequest.getRequestURI()
                        + " for this user is not authorized");
                return HttpStatus.FORBIDDEN;
            }

            logger.debug("Session " + sessionId + "is Authorized");

        } else {
            logger.debug("sessionId was not found in the header");
            return HttpStatus.UNAUTHORIZED;
        }

    }
    return HttpStatus.OK;
}

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

/**
 * Get the indicated resource set/*from w  w  w.  ja v a  2 s  . c o  m*/
 * @param rsid
 * @param m
 * @param auth
 * @return
 */
@RequestMapping(value = "/{rsid}", method = RequestMethod.GET, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String getResourceSet(@PathVariable(value = "rsid") Long rsid, 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;
    }

    m.addAttribute(JsonEntityView.ENTITY, rs);

    return JsonEntityView.VIEWNAME;
}

From source file:com.javiermoreno.springboot.rest.App.java

@Bean
public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
    //factory.setPort(7777); (est definido en el application.properties
    factory.setSessionTimeout(10, TimeUnit.MINUTES);
    factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/errores/error404.html"),
            new ErrorPage(HttpStatus.UNAUTHORIZED, "/errores/error401.html"),
            new ErrorPage(HttpStatus.FORBIDDEN, "/errores/error403.html"));
    // Activacin gzip sobre http (*NO* activar sobre ssl, induce ataques.)
    // http://stackoverflow.com/questions/21410317/using-gzip-compression-with-spring-boot-mvc-javaconfig-with-restful
    factory.addConnectorCustomizers((TomcatConnectorCustomizer) (Connector connector) -> {
        AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler();
        httpProtocol.setCompression("on");
        httpProtocol.setCompressionMinSize(256);
        String mimeTypes = httpProtocol.getCompressableMimeTypes();
        String mimeTypesWithJson = mimeTypes + "," + MediaType.APPLICATION_JSON_VALUE;
        httpProtocol.setCompressableMimeTypes(mimeTypesWithJson);
    });//from w  w  w  . j ava  2 s  .  c  om

    factory.addAdditionalTomcatConnectors(createSslConnector());
    /* En el caso de que se desee sustitur http por https: ************************
     // keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
     final String keystoreFilePath = "keystore.p12";
     final String keystoreType = "PKCS12";
     final String keystoreProvider = "SunJSSE";
     final String keystoreAlias = "tomcat"; 
     factory.addConnectorCustomizers((TomcatConnectorCustomizer) (Connector con) -> {
     con.setScheme("https");
     con.setSecure(true);
     Http11NioProtocol proto = (Http11NioProtocol) con.getProtocolHandler();
     proto.setSSLEnabled(true);
     // @todo: Descarga el fichero con el certificado actual 
     File keystoreFile = new File(keystoreFilePath);
     proto.setKeystoreFile(keystoreFile.getAbsolutePath());
     proto.setKeystorePass(remoteProps.getKeystorePass());
     proto.setKeystoreType(keystoreType);
     proto.setProperty("keystoreProvider", keystoreProvider);
     proto.setKeyAlias(keystoreAlias);
     });
     ***************************************************************************** */
    return factory;
}

From source file:com.blogspot.sgdev.blog.GrantByAuthorizationCodeProviderTest.java

@Test
public void getJwtTokenByAuthorizationCode()
        throws JsonParseException, JsonMappingException, IOException, URISyntaxException {
    String redirectUrl = "http://localhost:" + port + "/resources/user";
    ResponseEntity<String> response = new TestRestTemplate("user", "password").postForEntity(
            "http://localhost:" + port
                    + "/oauth/authorize?response_type=code&client_id=normal-app&redirect_uri={redirectUrl}",
            null, String.class, redirectUrl);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    List<String> setCookie = response.getHeaders().get("Set-Cookie");
    String jSessionIdCookie = setCookie.get(0);
    String cookieValue = jSessionIdCookie.split(";")[0];

    HttpHeaders headers = new HttpHeaders();
    headers.add("Cookie", cookieValue);
    response = new TestRestTemplate("user", "password").postForEntity("http://localhost:" + port
            + "oauth/authorize?response_type=code&client_id=normal-app&redirect_uri={redirectUrl}&user_oauth_approval=true&authorize=Authorize",
            new HttpEntity<Void>(headers), String.class, redirectUrl);
    assertEquals(HttpStatus.FOUND, response.getStatusCode());
    assertNull(response.getBody());//from w w  w. ja v  a2 s.  c  om
    String location = response.getHeaders().get("Location").get(0);
    URI locationURI = new URI(location);
    String query = locationURI.getQuery();

    location = "http://localhost:" + port + "/oauth/token?" + query
            + "&grant_type=authorization_code&client_id=normal-app&redirect_uri={redirectUrl}";

    response = new TestRestTemplate("normal-app", "").postForEntity(location,
            new HttpEntity<Void>(new HttpHeaders()), String.class, redirectUrl);
    assertEquals(HttpStatus.OK, response.getStatusCode());

    HashMap jwtMap = new ObjectMapper().readValue(response.getBody(), HashMap.class);
    String accessToken = (String) jwtMap.get("access_token");

    headers = new HttpHeaders();
    headers.set("Authorization", "Bearer " + accessToken);

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/client", HttpMethod.GET,
            new HttpEntity<String>(null, headers), String.class);
    assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/user", HttpMethod.GET,
            new HttpEntity<String>(null, headers), String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal",
            HttpMethod.GET, new HttpEntity<String>(null, headers), String.class);
    assertEquals("user", response.getBody());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET,
            new HttpEntity<String>(null, headers), String.class);
    assertEquals("[{\"authority\":\"ROLE_USER\"}]", response.getBody());
}

From source file:plbtw.klmpk.barang.hilang.controller.UserController.java

@RequestMapping(value = "/find/{id}", method = RequestMethod.GET, produces = "application/json")
public CustomResponseMessage getUser(@RequestHeader String apiKey, @PathVariable("id") long id) {
    try {/*  w  w  w. j a v a  2 s.  c o m*/

        if (!authApiKey(apiKey)) {
            return new CustomResponseMessage(HttpStatus.FORBIDDEN, "Please use your api key to authentication");
        }

        if (checkRateLimit(RATE_LIMIT, apiKey)) {
            return new CustomResponseMessage(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED,
                    "Please wait a while, you have reached your rate limit");
        }

        LogRequest temp = DependencyFactory.createLog(apiKey, "Get");

        Log log = new Log();
        log.setApiKey(temp.getApiKey());
        log.setStatus(temp.getStatus());
        log.setTimeRequest(temp.getTime_request());
        logService.addLog(log);

        User user = userService.getUser(id);
        Link selfLink = linkTo(UserController.class).withSelfRel();
        user.add(selfLink);
        List<User> listUser = new ArrayList<User>();
        listUser.add(user);
        CustomResponseMessage result = new CustomResponseMessage();
        result.add(linkTo(UserController.class).withSelfRel());
        result.setHttpStatus(HttpStatus.ACCEPTED);
        result.setMessage("Success");
        result.setResult(listUser);
        return result;
    } catch (Exception ex) {
        return new CustomResponseMessage(HttpStatus.FORBIDDEN, "Please use your api key to authentication");
    }
}

From source file:com.hypersocket.auth.json.AuthenticatedController.java

@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(value = HttpStatus.FORBIDDEN)
public void unauthorizedAccess(HttpServletRequest request, HttpServletResponse response,
        AccessDeniedException redirect) {

}

From source file:com.redblackit.war.AppSecurityRestControllerTest.java

/**
 * Test OPTIONS method for human page about (should get 403)
 * {@link com.redblackit.web.controller.AdminRestController#getVersion()}
 * with https.//from   w ww.  j  av a  2 s  . c  o  m
 */
@Test
public void testOptionsAbout() {
    helper.doOptionsForHttpStatusCodeException(inaccessibleUrl, null, "inaccessible URL for REST",
            HttpStatus.FORBIDDEN);
}