我在控制器中有三种方法。但每种方法都有不同的访问角色。
@RequestMapping("/deleteMethod.htm")
public String deleteMethod(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// Can be accessed by only ROLE_ADMIN
}
@RequestMapping("/editMethod.htm")
public String editMethod(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// Can be accessed by ROLE_ADMIN and ROLE_USER
}
@RequestMapping("/viewMethod.htm")
public ModelAndView viewMethod(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// Anyone can access this method
}
我觉得我在拦截网址时感到困惑。不管怎样,我只想授权控制器的方法。任何人都可以解释如何做到这一点?
security.xml文件
<http auto-config="true">
<intercept-url pattern="/welcome*" access="ROLE_USER" />
<form-login login-page="/login.htm" default-target-url="/welcome.htm"
authentication-failure-url="/loginfailed.htm" />
<logout logout-success-url="/logout.htm" />
</http>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="
select username,password,enabled
from tbl_users where username=?"
authorities-by-username-query="
select u.username, ur.authority from tbl_users u, tbl_user_roles ur
where u.user_id = ur.user_id and u.username =? "
/>
</authentication-provider>
</authentication-manager>
答案 0 :(得分:4)
这可以通过使用注释来完成。在配置中启用安全注释。
<global-method-security secured-annotations="enabled" />
并在方法声明上使用@Secured
注释。
@Secured("ROLE_ADMIN")
public String deleteMethod(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// Can be accessed by only ROLE_ADMIN
}
答案 1 :(得分:0)
您也可以使用
<http auto-config="true" use-expressions="true" >
<intercept-url pattern="/welcome*" access="ROLE_USER" />
<intercept-url pattern="/deleteMethod.htm*" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/editMethod.htm*" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/viewMethod.htm*" access="hasRole('ROLE_ADMIN')" />
<form-login login-page="/login.htm" default-target-url="/welcome.htm"
authentication-failure-url="/loginfailed.htm" />
<logout logout-success-url="/logout.htm" />
</http>