【问题标题】:Spring security: Controller method access to certain rolesSpring security:控制器方法访问某些角色
【发布时间】:2012-12-25 15:49:07
【问题描述】:

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

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

【问题讨论】:

    标签: spring jakarta-ee spring-mvc spring-security


    【解决方案1】:

    这可以通过使用注释来完成。在您的配置中启用安全注释。

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

    【讨论】:

      【解决方案2】:

      你也可以使用

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

      【讨论】:

        猜你喜欢
        • 2020-12-19
        • 1970-01-01
        • 2012-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-28
        • 2020-02-21
        • 2017-10-19
        相关资源
        最近更新 更多