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.cfitzarl.cfjwed.controller.ApiExceptionHandler.java

@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public void handleAccessDeniedExceptions(AccessDeniedException e, HttpServletResponse response) {
    respond(e, "errors.forbidden", response);
}

From source file:comsat.sample.ui.method.SampleMethodSecurityApplicationTests.java

@Test
public void testDenied() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.set("username", "user");
    form.set("password", "user");
    getCsrf(form, headers);// w w  w.j ava  2  s.  co  m
    ResponseEntity<String> entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/login",
            HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class);
    assertEquals(HttpStatus.FOUND, entity.getStatusCode());
    String cookie = entity.getHeaders().getFirst("Set-Cookie");
    headers.set("Cookie", cookie);
    ResponseEntity<String> page = new TestRestTemplate().exchange(entity.getHeaders().getLocation(),
            HttpMethod.GET, new HttpEntity<Void>(headers), String.class);
    assertEquals(HttpStatus.FORBIDDEN, page.getStatusCode());
    assertTrue("Wrong body (message doesn't match):\n" + entity.getBody(),
            page.getBody().contains("Access denied"));
}

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

@ExceptionHandler(ActionDeniedException.class)
public ResponseEntity<Object> handleAccessDeniedException(ActionDeniedException e, WebRequest request) {
    return handleExceptionInternal(e, HttpStatus.FORBIDDEN, ErrorCode.ACTION_DENIED, request);
}

From source file:com.basicservice.controller.UserController.java

@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<String> login(HttpServletRequest request,
        @RequestParam(value = "email") EmailValidatedString email,
        @RequestParam(value = "password") String password) {
    if (email == null || email.getValue() == null || password == null) {
        return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
    }//from   www . j a  v a  2s  .  co m
    User user = userService.login(email.getValue(), password);
    LOG.debug("Got login request: email:" + email.getValue() + ", pass:" + password);

    if (user == null) {
        try {
            new AppSensorException("AF1", "Authentication Failure", "Authentication Failure detected");
        } catch (Exception e) {
            // AppSensor might throw an exception, but we want to catch it here and stop propagation
        }
        return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
    } else if (!user.isEmailConfirmed()) {
        // let the user know that she can't login until she confirms the email
        return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
    }

    user.setLastLogin(new Date());

    LOG.debug("Preparing to save user to db");
    userService.save(user);
    final HttpHeaders headers = new HttpHeaders();
    headers.add("Set-Cookie", Constants.AUTHENTICATED_USER_ID_COOKIE + "=" + user.getSessionId() + "; Path=/");
    return new ResponseEntity<String>(headers, HttpStatus.OK);
}

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

@RequestMapping(value = "/{rsid}", method = RequestMethod.PUT, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String setClaimsForResourceSet(@PathVariable(value = "rsid") Long rsid, @RequestBody String jsonString,
        Model m, Authentication auth) {/*from   w ww. ja v  a2 s . c om*/

    ResourceSet rs = resourceSetService.getById(rsid);

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

    if (!rs.getOwner().equals(auth.getName())) {
        // authenticated user didn't match the owner of the resource set
        m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        return HttpCodeView.VIEWNAME;
    }

    @SuppressWarnings("serial")
    Set<Claim> claims = (new Gson()).fromJson(jsonString, new TypeToken<Set<Claim>>() {
    }.getType());

    rs.setClaimsRequired(claims);

    resourceSetService.update(rs, rs);

    m.addAttribute(JsonEntityView.ENTITY, rs.getClaimsRequired());

    return JsonEntityView.VIEWNAME;
}

From source file:org.craftercms.profile.services.AuthenticationServiceIT.java

@Test
@DirtiesContext/*from w w w  . j  ava  2  s.  c o  m*/
public void testNoSuchAccessTokenIdError() throws Exception {
    accessTokenIdResolver.setAccessTokenId(INVALID_ACCESS_TOKEN_ID);

    try {
        authenticationService.authenticate(DEFAULT_TENANT_NAME, ADMIN_USERNAME, ADMIN_PASSWORD);
        fail("Exception " + ProfileRestServiceException.class.getName() + " expected");
    } catch (ProfileRestServiceException e) {
        assertEquals(HttpStatus.FORBIDDEN, e.getStatus());
        assertEquals(ErrorCode.NO_SUCH_ACCESS_TOKEN_ID, e.getErrorCode());
    }
}

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

@RequestMapping(value = "/find/{id}", method = RequestMethod.GET, produces = "application/json")
public CustomResponseMessage findBarang(@RequestHeader String apiKey, @PathVariable("id") long id) {
    try {/*from ww  w. j a va2s .  c o  m*/
        if (!authApiKey(apiKey)) {
            return new CustomResponseMessage(HttpStatus.FORBIDDEN, "Please use your api key to authentication");
        }
        LogRequest temp = DependencyFactory.createLog(apiKey, "Get");

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

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

        List<Barang> rsBarang = new ArrayList<>();
        Barang barang = barangService.getBarang(id);
        Link selfLink = linkTo(UserController.class).withSelfRel();
        barang.add(selfLink);
        rsBarang.add(barang);
        CustomResponseMessage result = new CustomResponseMessage();
        result.add(linkTo(BarangController.class).withSelfRel());
        result.setHttpStatus(HttpStatus.FOUND);
        result.setMessage("Success");
        result.setResult(rsBarang);
        return result;
    } catch (NullPointerException ex) {
        return new CustomResponseMessage(HttpStatus.NOT_FOUND, "Data not found");
    } catch (Exception ex) {
        return new CustomResponseMessage(HttpStatus.BAD_REQUEST, ex.getMessage());
    }
}

From source file:net.cpollet.shoppist.web.controller.TokenController.java

@ExceptionHandler({ InvalidCredentialsException.class })
@ResponseStatus(value = HttpStatus.FORBIDDEN)
@ResponseBody//from  w  w  w . j  a  va 2s  .  c om
public RestResponse credentialsError(HttpServletRequest request, Exception exception) {
    logger.error("InvalidCredentials", exception);
    return RestResponseBuilder.aRestResponse() //
            .withHttpStatus(HttpStatus.FORBIDDEN.value()) //
            .withErrorStatus(MESSAGE_INVALID_CREDENTIALS) //
            .withErrorDescription(exception.getMessage()) //
            .build();
}

From source file:cn.edu.zjnu.acm.judge.controller.MailController.java

@GetMapping({ "/sendpage", "/send" })
@SuppressWarnings("AssignmentToMethodParameter")
public String sendpage(Model model, @RequestParam(value = "reply", defaultValue = "-1") long reply,
        @RequestParam(value = "to", defaultValue = "") String userId, Authentication authentication) {
    String title = "";
    String content = "";

    if (reply != -1) {
        Mail parent = mailMapper.findOne(reply);
        if (parent == null) {
            throw new MessageException("No such mail", HttpStatus.NOT_FOUND);
        }//from  w ww .  j av  a 2s .c o  m
        String toUser = parent.getTo();
        if (!UserDetailService.isUser(authentication, toUser)) {
            throw new MessageException("invalid access", HttpStatus.FORBIDDEN);
        }
        userId = parent.getFrom();
        title = parent.getTitle();
        content = parent.getContent();
        if (!title.regionMatches(true, 0, "re:", 0, 3)) {
            title = "Re:" + title;
        }
        mailMapper.setReply(reply);
    }
    model.addAttribute("to", userId);
    model.addAttribute("title", title);
    model.addAttribute("content", JudgeUtils.getReplyString(content));
    return "mails/sendpage";
}

From source file:org.craftercms.profile.services.TenantServiceIT.java

@Test
@DirtiesContext/* ww w .  ja v  a2 s.  c  om*/
public void testNoSuchAccessTokenIdError() throws Exception {
    accessTokenIdResolver.setAccessTokenId(INVALID_ACCESS_TOKEN_ID);

    try {
        tenantService.createTenant(getCorporateTenant());
        fail("Exception " + ProfileRestServiceException.class.getName() + " expected");
    } catch (ProfileRestServiceException e) {
        assertEquals(HttpStatus.FORBIDDEN, e.getStatus());
        assertEquals(ErrorCode.NO_SUCH_ACCESS_TOKEN_ID, e.getErrorCode());
    }
}