2012-12-25 190 views
1

我在控制器中有三種方法。但是每種方法都有不同的訪問角色。彈簧安全:控制器訪問某些角色的方法

@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。反正,我只是想授權控制的方法。任何人都可以解釋如何做到這一點?

的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> 

回答

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