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:io.fourfinanceit.homework.controller.ClientController.java

@RequestMapping(value = "/client", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<LoanApplication> createClient(@RequestBody Client client, HttpServletRequest request) {

    LoanApplication loanApplication = null;

    while (client.getLoanApplications().iterator().hasNext()) {
        loanApplication = client.getLoanApplications().iterator().next();
        loanApplication.setIpAddress(ipAddressDefiner.getIpAddress(request));
    }//  ww w.j  av  a 2  s  .c  o  m

    Client savedClient = clientRepository.save(client);

    while (savedClient.getLoanApplications().iterator().hasNext()) {
        if (!savedClient.getLoanApplications().iterator().hasNext()) {
            loanApplication = savedClient.getLoanApplications().iterator().next();
        }
    }

    if (loanApplication.getStatus() == LoanApplicationStatusEnum.ACTIVE.getStatus()) {
        return new ResponseEntity<LoanApplication>(loanApplication, HttpStatus.CREATED);
    } else {
        return new ResponseEntity<LoanApplication>(loanApplication, HttpStatus.FORBIDDEN);
    }

}

From source file:de.thm.arsnova.controller.SecurityExceptionControllerAdvice.java

@ExceptionHandler(AccessDeniedException.class)
public void handleAccessDeniedException(final Exception e, final HttpServletRequest request,
        final HttpServletResponse response) {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || authentication.getPrincipal() == null
            || authentication instanceof AnonymousAuthenticationToken) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return;//  w w  w.  j a va 2s . co m
    }
    response.setStatus(HttpStatus.FORBIDDEN.value());
}

From source file:reconf.server.services.security.UpsertUserService.java

@RequestMapping(value = "/user", method = RequestMethod.PUT)
@Transactional//from www.  j a va 2s  .c  o m
public ResponseEntity<Client> doIt(@RequestBody Client client, Authentication authentication) {

    List<String> errors = DomainValidator.checkForErrors(client);
    if (!errors.isEmpty()) {
        return new ResponseEntity<Client>(new Client(client, errors), HttpStatus.BAD_REQUEST);
    }
    HttpStatus status = null;

    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("USER"));

    if (ApplicationSecurity.isRoot(authentication)) {
        if (ApplicationSecurity.isRoot(client.getUsername())) {
            return new ResponseEntity<Client>(new Client(client, cannotChangeRootPassword),
                    HttpStatus.BAD_REQUEST);
        }
        status = upsert(client, authorities);

    } else if (StringUtils.equals(client.getUsername(), authentication.getName())) {
        if (!userDetailsManager.userExists(client.getUsername())) {
            return new ResponseEntity<Client>(new Client(client, mustBeRoot), HttpStatus.BAD_REQUEST);
        }
        User user = new User(client.getUsername(), client.getPassword(), authorities);
        userDetailsManager.updateUser(user);
        status = HttpStatus.OK;

    } else {
        return new ResponseEntity<Client>(HttpStatus.FORBIDDEN);
    }

    return new ResponseEntity<Client>(new Client(client), status);
}

From source file:com.stormcloud.ide.api.filter.UserFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {

    try {//from  w w  w. j  a  v a 2 s.co  m

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        LOG.info("Filter Request [" + request.getRemoteAddr() + "]");

        MDC.put("api", httpRequest.getRequestURI());

        if (httpRequest.getRequestURI().endsWith("/api/login")) {

            // configure MDC for the remainging trip
            MDC.put("userName", httpRequest.getRemoteUser());

            LOG.debug("Login Request.");

            // it's a login request which succeeded (Basic Auth)
            // so we now need to genereate an authentication token
            // and store it in a cookie we sent back
            // create the cookie with key for consecutive Rest API Calls

            // Get user from db and add to the localthread
            User user = dao.getUser(httpRequest.getRemoteUser());

            if (user == null) {

                LOG.error("User not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;
            }

            // update last login
            user.setLastLogin(Calendar.getInstance().getTime());

            dao.save(user);

            RemoteUser.set(user);

            try {

                // set the key cookie
                Cookie keyCookie = new Cookie("stormcloud-key", createKey(user, httpRequest.getRemoteAddr()));

                keyCookie.setMaxAge(60 * 60 * 24); // 1 day

                keyCookie.setPath("/");
                keyCookie.setSecure(true);

                httpResponse.addCookie(keyCookie);

                // set the username cookie
                Cookie userCookie = new Cookie("stormcloud-user", user.getUserName());

                userCookie.setMaxAge(60 * 60 * 24); // 1 day

                userCookie.setPath("/");
                userCookie.setSecure(true);

                httpResponse.addCookie(userCookie);

            } catch (NoSuchAlgorithmException e) {

                LOG.error(e);

                try {

                    // no go
                    httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());

                    httpResponse.flushBuffer();
                    return;

                } catch (IOException ioe) {
                    LOG.error(ioe);
                }
            }

        } else if (httpRequest.getRequestURI().endsWith("/api/user/createAccount")) {

            // intercept and do something with create account
            LOG.debug("Create Account Request.");

        } else {

            LOG.info("API Request.");

            // any other request than a login
            // we need to check the username and received key
            Cookie[] cookies = httpRequest.getCookies();

            String userName = null;
            String key = null;

            if (cookies != null) {

                LOG.info("Found " + cookies.length + " Cookies");

                // loop trough the cookies
                for (int i = 0; i < cookies.length; i++) {

                    if (cookies[i].getName().equals("stormcloud-user")) {

                        LOG.debug("userName = " + cookies[i].getValue());
                        userName = cookies[i].getValue();
                    }

                    if (cookies[i].getName().equals("stormcloud-key")) {

                        LOG.debug("key = " + cookies[i].getValue());
                        key = cookies[i].getValue();
                    }
                }
            }

            if (userName == null || key == null) {

                LOG.info("Required credentials not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;

            } else {

                // configure MDC for the remainging trip
                MDC.put("userName", userName);

                // get user
                LOG.debug("Get Persisted User");
                User user = dao.getUser(userName);

                if (user == null) {
                    httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                    httpResponse.flushBuffer();
                    return;
                }

                RemoteUser.set(user);

                try {

                    String matchKey = createKey(user, httpRequest.getRemoteAddr());

                    LOG.info("Validating Key.");

                    if (!matchKey.equals(key)) {

                        LOG.warn("Invalid Key!");
                        httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                        httpResponse.flushBuffer();
                        return;

                    } else {

                        LOG.info("Request Authenticated");
                    }

                } catch (NoSuchAlgorithmException e) {

                    LOG.error(e);

                    try {

                        // no go
                        httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
                        httpResponse.flushBuffer();
                        return;

                    } catch (IOException ioe) {
                        LOG.error(ioe);
                    }
                }

            }
        }

        chain.doFilter(request, response);

    } catch (IOException e) {
        LOG.error(e);
    } catch (ServletException e) {
        LOG.error(e);
    } finally {

        // clear the logging diagnostics context
        MDC.clear();

        // Remove the user from memoty
        RemoteUser.destroy();
    }
}

From source file:com.auditbucket.company.endpoint.CompanyEP.java

@RequestMapping(value = "/{companyName}", method = RequestMethod.GET)
@ResponseBody/*  www.ja va 2 s  .c  o  m*/
public ResponseEntity<Company> getCompany(@PathVariable("companyName") String companyName, String apiKey,
        @RequestHeader(value = "Api-Key", required = false) String apiHeaderKey) throws DatagioException {
    // curl -u mike:123 -X GET http://localhost:8080/ab/company/Monowai

    getCompany(apiHeaderKey, apiKey);
    Company company = companyService.findByName(companyName);
    if (company == null)
        return new ResponseEntity<>(company, HttpStatus.NOT_FOUND);
    //ToDo figure out companyName strategy
    SystemUser sysUser = securityHelper.getSysUser(true);
    if (!sysUser.getCompany().getId().equals(company.getId())) {
        // Not Authorised
        return new ResponseEntity<>(company, HttpStatus.FORBIDDEN);
    } else {
        return new ResponseEntity<>(company, HttpStatus.OK);
    }
}

From source file:ru.codemine.ccms.router.api.ApiSecurityRouter.java

@RequestMapping(value = "/api/login", method = RequestMethod.POST)
public ResponseEntity<?> authRequest(HttpServletRequest req) {
    String reqUsername = req.getHeader("username");
    String reqPass = req.getHeader("password");

    String token = null;/*from w  w  w  . jav a 2 s .c  om*/
    Map<String, String> headers = new HashMap();

    try {
        Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(reqUsername, reqPass));

        SecurityContextHolder.getContext().setAuthentication(authentication);

        Employee employee = employeeService.getByUsername(reqUsername);
        token = apiTokenUtils.generateToken(employee);

        headers.put("X-Auth-Token", token);
    } catch (BadCredentialsException e) {
        log.warn("    , ?: "
                + reqUsername);
    }

    return token == null ? new ResponseEntity<>(HttpStatus.FORBIDDEN)
            : new ResponseEntity<>(headers, HttpStatus.OK);
}

From source file:de.thm.arsnova.controller.SecurityExceptionControllerAdvice.java

@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(ForbiddenException.class)
public void handleForbiddenException(final Exception e, final HttpServletRequest request) {
}

From source file:org.bonitasoft.web.designer.controller.ResourceControllerAdvice.java

@ExceptionHandler(NotAllowedException.class)
public ResponseEntity<ErrorMessage> handleNotAllowedException(NotAllowedException exception) {
    logger.error("Not Allowed Exception", exception);
    return new ResponseEntity<>(new ErrorMessage(exception), HttpStatus.FORBIDDEN);
}

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

/**
 * Test POST method for human page about (should get 403)
 * {@link com.redblackit.web.controller.AdminRestController#getVersion()}
 * with https.//from  w  w w.j  a  v a  2 s . c  om
 */
@Test
public void testPostAbout() {
    helper.doPostForHttpStatusCodeException(inaccessibleUrl, "About", null, "inaccessible URL for REST",
            HttpStatus.FORBIDDEN);
}

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

@Secured({ "ROLE_USER", "ROLE_ADMIN" })
@RequestMapping("{id}")
HttpEntity<Recipe> get(@PathVariable("id") Long id) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication instanceof RecipeManagerAuthenticationToken) {
        RecipeManagerAuthenticationToken token = (RecipeManagerAuthenticationToken) authentication;
        Recipe recipe = repository.findOne(id);
        if (recipe == null) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } else if (recipe.isPublicVisible() || ROLE_ADMIN.name().equals(token.getRole())
                || token.getPrincipal().equals(recipe.getAuthor().getId())) {
            return new ResponseEntity<>(recipe, HttpStatus.OK);
        }//from  w  w w  . j a  va2 s  .  c  o m
    }
    return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}