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:de.hska.ld.core.controller.UserControllerIntegrationTest.java

@Test
public void testDeleteUserUsesHttpForbiddenOnAuthorizationFailure() throws Exception {
    User user = userService.save(newUser());

    HttpResponse response = UserSession.user().delete(RESOURCE_USER + "/" + user.getId());
    Assert.assertEquals(HttpStatus.FORBIDDEN, ResponseHelper.getStatusCode(response));
}

From source file:org.craftercms.security.authentication.impl.AuthenticationManagerImplTest.java

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    when(authenticationService.authenticate(TENANT1, USERNAME1, PASSWORD1)).thenReturn(getTicket1());
    when(authenticationService.authenticate(TENANT2, USERNAME2, PASSWORD2)).thenReturn(getTicket2());
    doThrow(new ProfileRestServiceException(HttpStatus.UNAUTHORIZED, ErrorCode.BAD_CREDENTIALS, ""))
            .when(authenticationService).authenticate(TENANT1, USERNAME2, PASSWORD2);
    doThrow(new ProfileRestServiceException(HttpStatus.FORBIDDEN, ErrorCode.DISABLED_PROFILE, ""))
            .when(authenticationService).authenticate(TENANT1, DISABLED_USERNAME, PASSWORD1);

    when(profileService.getProfile(PROFILE_ID1.toString(), new String[0])).thenReturn(getProfile1());
    when(profileService.getProfile(PROFILE_ID2.toString(), new String[0])).thenReturn(getProfile2());
    when(profileService.getProfileByTicket(TICKET_ID1, new String[0])).thenReturn(getProfile1());
    doThrow(new ProfileRestServiceException(HttpStatus.BAD_REQUEST, ErrorCode.NO_SUCH_TICKET, ""))
            .when(profileService).getProfileByTicket(INVALID_TICKET_ID, new String[0]);

    when(authenticationCache.getAuthentication(TICKET_ID1)).thenReturn(getAuthentication1());

    authenticationManager = new AuthenticationManagerImpl();
    authenticationManager.setAuthenticationService(authenticationService);
    authenticationManager.setProfileService(profileService);
    authenticationManager.setAuthenticationCache(authenticationCache);
}

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

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

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

/**
 * Delete an approved site/* w w w .j a  v  a2s .  c o  m*/
 * 
 */
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public String deleteApprovedSite(@PathVariable("id") Long id, ModelMap m, Principal p) {
    ApprovedSite approvedSite = approvedSiteService.getById(id);

    if (approvedSite == null) {
        logger.error("deleteApprovedSite failed; no approved site found for id: " + id);
        m.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        m.put(JsonErrorView.ERROR_MESSAGE,
                "Could not delete approved site. The requested approved site with id: " + id
                        + " could not be found.");
        return JsonErrorView.VIEWNAME;
    } else if (!approvedSite.getUserId().equals(p.getName())) {
        logger.error(
                "deleteApprovedSite failed; principal " + p.getName() + " does not own approved site" + id);
        m.put(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        m.put(JsonErrorView.ERROR_MESSAGE,
                "You do not have permission to delete this approved site. The approved site decision will not be deleted.");
        return JsonErrorView.VIEWNAME;
    } else {
        m.put(HttpCodeView.CODE, HttpStatus.OK);
        approvedSiteService.remove(approvedSite);
    }

    return HttpCodeView.VIEWNAME;
}

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

@ExceptionHandler(NoSuchAccessTokenIdException.class)
public ResponseEntity<Object> handleNoSuchAccessTokenException(NoSuchAccessTokenIdException e,
        WebRequest request) {//ww  w .  j a  v a  2  s .c  om
    return handleExceptionInternal(e, HttpStatus.FORBIDDEN, ErrorCode.NO_SUCH_ACCESS_TOKEN_ID, request);
}

From source file:org.mitre.oauth2.web.TokenAPI.java

@RequestMapping(value = "/access/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getAccessTokenById(@PathVariable("id") Long id, ModelMap m, Principal p) {

    OAuth2AccessTokenEntity token = tokenService.getAccessTokenById(id);

    if (token == null) {
        logger.error("getToken failed; token not found: " + id);
        m.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        m.put(JsonErrorView.ERROR_MESSAGE, "The requested token with id " + id + " could not be found.");
        return JsonErrorView.VIEWNAME;
    } else if (!token.getAuthenticationHolder().getAuthentication().getName().equals(p.getName())) {
        logger.error("getToken failed; token does not belong to principal " + p.getName());
        m.put(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        m.put(JsonErrorView.ERROR_MESSAGE, "You do not have permission to view this token");
        return JsonErrorView.VIEWNAME;
    } else {/*from  w  ww.  ja va  2 s .c  om*/
        m.put(JsonEntityView.ENTITY, token);
        return TokenApiView.VIEWNAME;
    }
}

From source file:org.dawnsci.marketplace.controllers.ExtendedRestApiController.java

@PreAuthorize("hasRole('UPLOAD')")
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity<String> postSolution(Principal principal, @RequestBody String solution) throws Exception {
    Account account = accountRepository.findOne(principal.getName());
    Node node = MarketplaceSerializer.deSerializeSolution(solution);
    Object result = marketplaceDAO.saveOrUpdateSolution(node, account);
    if (result instanceof Node) {
        return new ResponseEntity<String>(MarketplaceSerializer.serialize((Node) result), HttpStatus.OK);
    } else {/*from  w w  w  .j ava 2 s  .com*/
        if (result instanceof Exception) {
            ((Exception) result).printStackTrace();
            String message = ((Exception) result).getMessage();
            return new ResponseEntity<String>(message, HttpStatus.INTERNAL_SERVER_ERROR);
        } else
            return new ResponseEntity<String>(result.toString(), HttpStatus.FORBIDDEN);
    }
}

From source file:net.mamian.mySpringboot.interceptor.AuthInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
        ///*  w  ww  .  ja v a 2 s  . c  o m*/
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //
        Object target = handlerMethod.getBean();

        //FreeAccess
        if (target.getClass().isAnnotationPresent(FreeAccess.class)) {
            return true;
        }

        //LoginRequired
        boolean loginRequired = target.getClass().isAnnotationPresent(LoginRequired.class)
                || null != handlerMethod.getMethodAnnotation(LoginRequired.class);
        if (loginRequired && !checkLogin(request)) {
            //                response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }

        //EmployeeLoginRequired
        boolean employeeLoginRequired = target.getClass().isAnnotationPresent(EmployeeLoginRequired.class)
                || null != handlerMethod.getMethodAnnotation(EmployeeLoginRequired.class);
        Employee employee = null;
        if (employeeLoginRequired) {
            employee = ContextUtils.getEmployee(request);
            if (employee == null) {
                //                    response.setStatus(HttpStatus.PROXY_AUTHENTICATION_REQUIRED.value());
                response.sendRedirect(request.getContextPath() + "/login");
                return false;
            }
        }

        Set<Privilege> priv = new HashSet<>();

        //PrivilegeRequired
        PrivilegeRequired pr = target.getClass().getAnnotation(PrivilegeRequired.class);
        if (pr != null && pr.value() != null && pr.value().length > 0) {
            priv.addAll(Arrays.asList(pr.value()));
        }

        //PrivilegeRequired
        pr = handlerMethod.getMethodAnnotation(PrivilegeRequired.class);
        if (pr != null && pr.value() != null && pr.value().length > 0) {
            priv.addAll(Arrays.asList(pr.value()));
        }

        Privilege[] privileges = priv.toArray(new Privilege[priv.size()]);
        if (privileges.length > 0 && !checkPrivileges(employee, privileges)) {
            request.setAttribute("insufficientPrivilege", privileges[0].getMsg());
            response.setStatus(HttpStatus.FORBIDDEN.value());
            return false;
        }
    }
    return true;
}

From source file:edu.pitt.dbmi.ccd.anno.error.ErrorHandler.java

@ExceptionHandler(ForbiddenException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody/*from   w  ww. j a  v  a2s.com*/
public ErrorMessage handleForbiddenException(ForbiddenException ex, HttpServletRequest req) {
    LOGGER.info(ex.getMessage());
    return new ErrorMessage(HttpStatus.FORBIDDEN, FORBIDDEN_MESSAGE, req);
}

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

/**
 * Test HEAD method for human page about (should get 403)
 * {@link com.redblackit.web.controller.AdminRestController#getVersion()}
 * with https.//ww w.  ja  v a  2 s. co m
 */
@Test
@Ignore // Until Spring bug fixed
public void testHeadAbout() {
    helper.doHeadForHttpStatusCodeException(inaccessibleUrl, null, "inaccessible URL for REST",
            HttpStatus.FORBIDDEN);
}