在Spring MVC Controller中授权方法

时间:2013-06-17 19:28:14

标签: java authentication spring-mvc spring-security annotations

我的目标是保护Spring 2.5 MVC Controller中的某些方法只能被特定用户访问,例如,Managers可以访问所有方法,但是Viewers可以访问其中的一些方法。虽然我必须访问会话对象以了解当前登录的用户是否是管理员。我有一个方法。

 public boolean isManager(HttpSession session){

//Dome some check
}

我想要保护的控制器方法看起来像这样

@RequestMapping(value = "/getInfo", method = RequestMethod.GET)
    public ModelAndView getInfo(ModelMap model, HttpSession session) {

      //do something

        return new ModelAndView("info_page", model);
    }

所以在上面的方法中,我希望有一个注释,只允许管理员访问该方法。

例如,我希望有类似的东西

@RolesAllowed(AcessType.ManagerOnly)   
@RequestMapping(value = "/getInfo", method = RequestMethod.GET)
    public ModelAndView getInfo(ModelMap model, HttpSession session) {

      //do something

        return new ModelAndView("info_page", model);
    }

我看过this问题,但它并没有帮助我如何将角色(经理或其他东西)传递给注释并完成工作。

我是否必须创建AccessType枚举。并根据会话设置角色?我们已经使用Spring Security进行身份验证和授权。

任何帮助将不胜感激!!

2 个答案:

答案 0 :(得分:2)

您需要实施spring security。请参阅链接以查看可以开始查看的地方和Google搜索,因为我认为这个主题的完整教程超出了本问题的范围。当你实现了一个spring安全上下文时,每个用户都会有相关的角色,你可以像你的例子一样使用@RolesAllowed注释。

Here's a blog引导您通过spring实现自己的安全过滤器。

- 回应评论:

Spring安全性也可以与自定义角色一起使用。在spring安全上下文中,您可以定义身份验证提供程序:

<authentication-provider user-service-ref='daoAuthenticationProvider'>
    <password-encoder hash="md5"/>
</authentication-provider>
<beans:bean id="daoAuthenticationProvider" class="com.custom.DaoAuthenticationProvider"/>

并扩展了AbstractUserDetailsAuthenticationProvider。在这里,您可以使用自定义代码为特定用户提供UserDetails对象。 UserDetails对象将具有您希望用于限制其他位置访问的角色。

答案 1 :(得分:2)

我在博客中解释的相同场景,您可以参考博客文章available here,我已经使用了基于Spring Security AOP的授权。使用基于Spring安全性AOP的授权,您可以在方法声明之上使用带有角色名称的@Secured注释,以允许仅对定义用户角色进行访问。

//access will be granted only the users with ROLE_MANAGER
@Secured("ROLE_MANAGER")
public ModelAndView showManagerHomePage(){

}

//access will be granted only the users with ROLE_MANAGER or ROLE_ADMIN
@Secured({"ROLE_MANAGER","ROLE_ADMIN"})
public ModelAndView showAdminUserHomePage(){

}
相关问题