Example usage for org.springframework.security.access AccessDeniedException AccessDeniedException

List of usage examples for org.springframework.security.access AccessDeniedException AccessDeniedException

Introduction

In this page you can find the example usage for org.springframework.security.access AccessDeniedException AccessDeniedException.

Prototype

public AccessDeniedException(String msg) 

Source Link

Document

Constructs an AccessDeniedException with the specified message.

Usage

From source file:com.mothsoft.alexis.security.CurrentUserUtil.java

public static void assertAuthenticatedUserOrAdminOrSystem(final Long userId) {
    if (!isAuthenticated() || !getCurrentUserId().equals(userId)) {
        throw new AccessDeniedException(
                String.format("User %s lacks necessary permissions.", getCurrentUser().getUsername()));
    }// ww w  . java  2  s .  c  o m
}

From source file:org.trustedanalytics.platformcontext.StashErrorDecoder.java

@Override
public Exception decode(String methodKey, Response response) {
    if (response.status() == 403) {
        return new AccessDeniedException("You do not have permission to perform this action!");
    }/*from w w w  . j  a  va 2s .  c om*/
    return new ErrorDecoder.Default().decode(methodKey, response);
}

From source file:com.cfitzarl.cfjwed.core.security.SecurityContextWrapper.java

public static void authorize(Account account) {
    Object principal = getAuthentication().getPrincipal();
    if ((account == null || !account.getId().equals(principal)) && !"ROLE_ADMIN".equals(getRole())) {
        throw new AccessDeniedException("Unauthorized access detected");
    }/*ww w. jav  a2s.c o  m*/
}

From source file:com.poscoict.license.security.AjaxSessionTimeoutFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    if (isAjaxRequest(req)) {
        try {//w w  w . j a va2 s . c om
            String user = (String) req.getSession().getAttribute("USER_NO");
            if (user == null) {
                throw new AccessDeniedException(" ");
            } else {
                chain.doFilter(req, res);
            }
        } catch (AccessDeniedException e) {
            System.out.println(e.getMessage());
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (AuthenticationException e) {
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } else {
        chain.doFilter(req, res);
    }
}

From source file:net.paulgray.bbrest.people.BbPeopleService.java

public List<Person> getPeopleForUserAndCourse(String userId, String courseId) {
    try {/*  w w  w . j av a2  s  . co m*/
        if (!BbCourseService.currentUserCanViewCourse(courseId)) {
            throw new AccessDeniedException("User cannot view course: " + courseId);
        }

        Set<Person> people = new HashSet<Person>();
        UserDbLoader userDbLoader = UserDbLoader.Default.getInstance();

        List<User> users = userDbLoader
                .loadByCourseId(BlackboardUtilities.getIdFromPk(courseId, blackboard.data.course.Course.class));
        List<CourseMembership> courseMemberships = CourseMembershipDbLoader.Default.getInstance()
                .loadByCourseIdWithUserInfo(
                        BlackboardUtilities.getIdFromPk(courseId, blackboard.data.course.Course.class));

        for (CourseMembership enrollment : courseMemberships) {
            if (enrollment.getRole() != null) {
                for (User user : users) {
                    if (user.getId().equals(enrollment.getUserId())) {
                        people.add(new BbPerson(user, enrollment.getRole().getFieldName()));
                    }
                }
            }
        }
        return new ArrayList(people);
    } catch (PersistenceException ex) {
        Logger.getLogger(BbPeopleService.class.getName()).log(Level.SEVERE, null, ex);
        return new LinkedList<Person>();
    }

}

From source file:cn.net.withub.demo.bootsec.hello.security.CustomAccessDecisionManager.java

@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {
    if (configAttributes == null) {
        //??//ww  w. j  ava2  s .  co m
        throw new AccessDeniedException("Access Dendied");
    }

    //???(???)
    for (ConfigAttribute configAttribute : configAttributes) {
        //????
        String needPermission = configAttribute.getAttribute();

        System.out.println("needPermission is " + needPermission);

        //??authentication
        for (GrantedAuthority ga : authentication.getAuthorities()) {

            if (needPermission.equals(ga.getAuthority())) {
                return;
            }

        }

    }

    //??
    throw new AccessDeniedException("Access Dendied");
    //throw new InsufficientAuthenticationException("???");
}

From source file:fr.mael.microrss.util.SecurityUtil.java

public User getCurrentUser() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Object principal = auth.getPrincipal();
    if (principal == null || !(principal instanceof User)) {
        throw new AccessDeniedException("User is not logged in");
    }/*  w w  w . j a  v a  2 s .  c  o  m*/
    User user = (User) principal;
    //TODO the id is lost when the server is restarted
    //will it happen in production ?
    if (user.getId() == null) {
        throw new AccessDeniedException("User is not logged in");
    }

    return user;
}

From source file:org.cloudfoundry.identity.uaa.error.JsonAwareAccessDeniedHandlerTests.java

@Test
public void testCommenceWithJson() throws Exception {
    request.addHeader("Accept", MediaType.APPLICATION_JSON_VALUE);
    entryPoint.handle(request, response, new AccessDeniedException("Bad"));
    assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatus());
    assertEquals("{\"error\":\"Bad\"}", response.getContentAsString());
    assertEquals(null, response.getErrorMessage());
}

From source file:com.gcrm.security.UrlAccessDecisionManager.java

public void decide(Authentication authentication, Object securityObject,
        Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {

    try {/*  w  w w  .  j a  va 2  s.  c o  m*/
        if (authentication.getPrincipal() instanceof String
                && "anonymousUser".equals(authentication.getPrincipal())) {
            throw new AccessDeniedException(" no permission access?");
        }
        return;
    } catch (Exception e) {
        throw new AccessDeniedException("Role check fails.");
    }
}

From source file:org.trustedanalytics.uploader.security.PermissionVerifierTest.java

@Parameterized.Parameters(name = "{index} {0}")
public static Iterable<Object[]> data() {
    // @formatter:off
    return Arrays.asList(new Object[][] {
            { "User assigned to organization with all roles", grantedOrg,
                    mockUserManagement(allOrgRoles(grantedOrg)), null },
            { "User assigned to organization with no roles", grantedOrg,
                    mockUserManagement(noOrgRoles(grantedOrg)), null },
            { "User assigned to requested and other organizations", grantedOrg,
                    mockUserManagement(allOrgRoles(grantedOrg), allOrgRoles(otherGrantedOrg)), null },
            { "User not assigned to any organization", deniedOrg, mockUserManagement(),
                    new AccessDeniedException(OrgPermissionVerifier.ACCESS_DENIED_MSG) },
            { "User not assigned to requested organization", deniedOrg,
                    mockUserManagement(allOrgRoles(grantedOrg)),
                    new AccessDeniedException(OrgPermissionVerifier.ACCESS_DENIED_MSG) },
            { "User assigned to multiple other organizations", deniedOrg,
                    mockUserManagement(allOrgRoles(grantedOrg), allOrgRoles(otherGrantedOrg)),
                    new AccessDeniedException(OrgPermissionVerifier.ACCESS_DENIED_MSG) } });
    // @formatter:on
}