2

我在控制器中有三种方法。但是每种方法都有不同的访问角色。

@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
    }   

我想我在拦截 url 时感到困惑。无论如何,我只想授权控制器的方法。谁能解释如何做到这一点?

安全.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>
4

2 回答 2

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
}
于 2012-12-25T16:12:19.787 回答
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>
于 2014-02-17T10:35:10.023 回答