Role-based access control with Spring MVC

北战南征 提交于 2019-12-10 04:15:05

问题


I would like to know the best practices for the role based access control with spring.

My requirements are,

I will have set of roles assigned to users say,

user1=admin, user2=expert

user1 will have the accesses write like

/admin/member-management

/admin/project-management

......

for user2....

/myproject1/*

so if user2 tries to access the url

/admin/member-management

will be redirect to authorization failure page.


回答1:


The standard framework to use with Spring MVC is Spring Security. While it can be very complex, here's a minimal version of what you need: 4.2.2 A Minimal Configuration

In your case, the config would be something like this:

<http auto-config='true'>
    <intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
</http>



回答2:


Spring Security has the concept of roles but out of the box it does not have a concept of permissions. It does have a concept of ACLs but this ACLs are a lot more complicated than permissions, and they are tied to acting on specific objects, versus authorizing actions in general.

Take a look at Apache Shiro. It has roles and permissions that look very similar to what you gave as an example (using wildcards). It is also easy to use with Spring.




回答3:


public class DashBoardController {

@Autowired
UserService userService;

private static final Logger logger = LoggerFactory.getLogger(DashBoardController.class);

@SuppressWarnings("unchecked")
@RequestMapping(value = PathProxy.DashBoardUrls.SHOW_DASHBOARD, method = RequestMethod.GET)
public String role(Locale locale, Model model) {
    String userRole = null;
    logger.info("dashboard Controller");
    Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) SecurityContextHolder
            .getContext().getAuthentication().getAuthorities();
    for (SimpleGrantedAuthority simpleGrantedAuthority : authorities) {
        userRole = simpleGrantedAuthority.toString();
    }

    switch (userRole) {

    case "ROLE_ADMIN":

        return "dashboard/admin";

    case "ROLE_HR_MANAGER":

        return "dashboard/hr_manager";

    case "ROLE_MANAGER":

        return "dashboard/manager";

    case "ROLE_EMPLOYEE":

        return "dashboard/employee";

    case "ROLE_COMPANY_ADMIN":

        return "dashboard/admin";

    default:

        break;
    }

    return userRole;

}

}



来源:https://stackoverflow.com/questions/7173910/role-based-access-control-with-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!