Role-based access control with Spring MVC
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 accesse开发者_StackOverflow中文版s 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.
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>
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.
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;
}
}
精彩评论