Spring 方法安全性对我不起作用

发布于 2024-12-11 16:09:19 字数 14646 浏览 0 评论 0原文

我是春季安全的新手。

我尝试在我的应用程序中使用 spring security。基本的 Spring Security 功能运行良好。

但是,当我尝试确保方法仅允许特定角色时,它并不安全,并且该方法可以适用于每个角色。

在这里我给出了我的代码片段。我可以知道我哪里做错了吗?

我用于此应用程序的库是

01.aopalliance-1.0.jar
02.jcl-over-slf4j-1.6.1.jar
03.jstl-1.2.jar
04.logback-classic-0.9.29.jar
05.logback-core-0.9.29.jar
06.mysql-connector-java-5.1.12-bin.jar
07.org.springframework.jdbc-3.1.0.RC1.jar
08.org.springframework.transaction-3.1.0.RC1.jar
09.slf4j-api-1.6.1.jar
10.spring-aop-3.0.6.RELEASE.jar
11.spring-asm-3.0.6.RELEASE.jar
12.spring-beans-3.0.6.RELEASE.jar
13.spring-context-3.0.6.RELEASE.jar
14.spring-context-support-3.0.6.RELEASE.jar
15.spring-core-3.0.6.RELEASE.jar
16.spring-expression-3.0.6.RELEASE.jar
17.spring-security-config-3.1.0.RC3.jar
18.spring-security-core-3.1.0.RC3.jar
19.spring-security-crypto-3.1.0.RC3.jar
20.spring-security-taglibs-3.1.0.RC3.jar
21.spring-security-web-3.1.0.RC3.jar
22.spring-web-3.0.6.RELEASE.jar
23.spring-webmvc-3.0.6.RELEASE.jar

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml
            /WEB-INF/security-app-context.xml
            /WEB-INF/application-data-source.xml
        </param-value>
    </context-param>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
      <filter-name>springSecurityFilterChain</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--
      - Provides core MVC application controller. See bank-servlet.xml.
     -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                           http://www.springframework.org/schema/security
                           http://www.springframework.org/schema/security/spring-security-3.1.xsd"
       xmlns:ns1="http://www.springframework.org/schema/security">

    <ns1:global-method-security pre-post-annotations="enabled"/>

    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/pages/result/"
          p:suffix=".jsp" >
          <property name="viewClass">
            <value>
              org.springframework.web.servlet.view.JstlView
            </value>
          </property>
    </bean>

    <!--
    The index controller.
    -->

    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />

    <bean name="/action.htm" id="action" class="com.spt3.controller.ActionController">
        <property name="methodNameResolver">
            <ref bean="paramResolver"/>
        </property>
    </bean>

    <bean id="paramResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
        <property name="paramName">
            <value>action</value>
        </property>
    </bean>

</beans>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">


</beans>

security-app-context.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                    http://www.springframework.org/schema/security 
                    http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <global-method-security pre-post-annotations="enabled"/>

    <http use-expressions="true" auto-config="true" access-denied-page="/pages/accessDenied.jsp">
            <intercept-url pattern="/index.jsp" access="permitAll" />
            <intercept-url pattern="/**.htm" access="isAuthenticated()"/>
            <intercept-url pattern="/pages/*" access="permitAll" />
            <intercept-url pattern="/user/*" access="isAuthenticated()"/>            
            <intercept-url pattern="/md/*" access="hasRole('MD')"/>
            <intercept-url pattern="/admin/*" access="hasAnyRole('Administrator','MD')"/>
            <intercept-url pattern="/manager/*" access="hasAnyRole('Manager','MD')"/>
            <form-login login-page="/pages/login.jsp" authentication-failure-url="/pages/loginfailed.jsp"/>
            <logout logout-success-url="/index.jsp"/>
    </http>

    <beans:bean id="encoder" class="com.spt3.encoder.MyPasswordEncoder"/>

    <authentication-manager>
      <authentication-provider>
        <password-encoder ref="encoder"/>
        <jdbc-user-service data-source-ref="dataSource"

                   users-by-username-query="
                      select username,password, enabled
                      from users where username=?"

                   authorities-by-username-query="
                      select u.username, ur.authority from users u, user_roles ur where u.user_id = ur.user_id and u.username =?  "
        />
      </authentication-provider>
    </authentication-manager>

</beans:beans>

application-data-source.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="dataSource"    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/app" />
        <property name="username" value="uname" />
        <property name="password" value="pword" />
    </bean>

</beans>

ActionController.java

package com.spt3.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.spt3.infc.ActionInterface;
import org.springframework.security.access.prepost.PreAuthorize;

public class ActionController extends MultiActionController implements ActionInterface {

    public ActionController(){
    }

    public ModelAndView getResult(HttpServletRequest request,HttpServletResponse response)throws Exception{
        System.out.println(" - - - - - getResult() - - - - - ");
        try{
            this.getPersonalInformation("MD");
        }catch(Exception e){
            System.out.println(" Exception : "+e);
        }
        return new ModelAndView("result");
    }

    public void getPersonalInformation(String role){
        System.out.println(" "+role+"'s-Personal Information.");
    }
}

ActionInterface.java

package com.spt3.infc;

import org.springframework.security.access.prepost.PreAuthorize;
public interface ActionInterface {

    @PreAuthorize("hasRole('MD')") // Secured method only for role MD
    public void getPersonalInformation(String role);
}

从 url 访问 getResult() 方法时( http://127.0.0.1:8080/myapp/action.htm?action=getResult )可以调用安全方法。

我的预期结果应该是

  • getPersonalInformation() 方法只能访问用户角色 MD

现在实际结果

  • getPersonalInformation() 方法正在调用每个用户角色。

使用bean之后 - 编辑(1)此处

使用bean注入时也出现了同样的问题。

在这里我用代码片段更改了文件。

ActionController.java 就像

package com.spt3.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.spt3.infc.ActionInterface;

public class ActionController extends MultiActionController {

    private ActionInterface actionInterface;

    public ActionController(){
    }

    public ActionController(ActionInterface actionInterface){
        this.actionInterface=actionInterface;
    }

    public ModelAndView getResult(HttpServletRequest request,HttpServletResponse response)throws Exception{
        System.out.println(" - - - - - getResult() - - - - - ");
        try{
            actionInterface.getPersonalInformation("MD");
        }catch(Exception e){
            System.out.println(" Exception : "+e);
        }
        return new ModelAndView("result");
    }

}

ActionInterface.java

package com.spt3.infc;

public interface ActionInterface {

    public void getPersonalInformation(String role);
}

bean 类,称为 ActionBean.java

package com.spt3.bean;


import com.spt3.infc.ActionInterface;
import org.springframework.security.access.annotation.Secured;

public class ActionBean implements ActionInterface{

    @Secured("MD")
    public void getPersonalInformation(String role){
        System.out.println(" "+role+"'s-Personal Information.");
    }

}

我使用构造函数注入来注入对象。

<bean id="actionBean" class="com.spt3.bean.ActionBean"/> <!-- Bean class -->
<bean name="/action.htm" id="action" class="com.spt3.controller.ActionController">
        <property name="methodNameResolver">
            <ref bean="paramResolver"/>
        </property>
        <constructor-arg index="0" ref="actionBean"/> <!-- Injecting object to controller -->
    </bean>

我哪里做错了。请给我解决方案。

问题已解决。

这些是我遵循的步骤。

  1. 在适当的 xml 文件中配置 bean
  2. 我使用了 bean 注入。
  3. 我使用了@PreAuthorize注释。

最后,当程序成功运行时,这些类看起来像下面的代码片段。

ActionBean 是我创建的一个单独的类,我实现了 ActionInterface.java 类并实现了 getPersonalInformation() 方法。

ActionInterface.java 看起来像这样

package com.spt3.infc;

public interface ActionInterface {

    public void getPersonalInformation(String role);
}

,ActionBean.java 看起来像这样

package com.spt3.bean;


import com.spt3.infc.ActionInterface;
import org.springframework.security.access.prepost.PreAuthorize;

public class ActionBean implements ActionInterface{

    @PreAuthorize("hasRole('MD')")
    public void getPersonalInformation(String role){
        System.out.println(" "+role+"'s-Personal Information.");
    }

}

ActionController.java 看起来像这样

package com.spt3.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.spt3.infc.ActionInterface;

public class ActionController extends MultiActionController {

    private ActionInterface actionInterface;

    public ActionController(){
    }

    public ActionController(ActionInterface actionInterface){
        this.actionInterface=actionInterface;
    }

    public ModelAndView getResult(HttpServletRequest request,HttpServletResponse response)throws Exception{
        System.out.println(" - - - - - getResult() - - - - - ");
        try{
            actionInterface.getPersonalInformation("MD");
        }catch(Exception e){
            System.out.println(" Exception : "+e);
        }
        return new ModelAndView("result");
    }

}

祝你好运... 多谢。

i am new to spring security.

i try to use spring security in my application. the basic spring security functionality works fine.

but when i try to secure methods to allow only for specific role, it does not secured and that method can work for every role.

here i given my code snippet. may i know where i did mistake.

library that i used for this application are

01.aopalliance-1.0.jar
02.jcl-over-slf4j-1.6.1.jar
03.jstl-1.2.jar
04.logback-classic-0.9.29.jar
05.logback-core-0.9.29.jar
06.mysql-connector-java-5.1.12-bin.jar
07.org.springframework.jdbc-3.1.0.RC1.jar
08.org.springframework.transaction-3.1.0.RC1.jar
09.slf4j-api-1.6.1.jar
10.spring-aop-3.0.6.RELEASE.jar
11.spring-asm-3.0.6.RELEASE.jar
12.spring-beans-3.0.6.RELEASE.jar
13.spring-context-3.0.6.RELEASE.jar
14.spring-context-support-3.0.6.RELEASE.jar
15.spring-core-3.0.6.RELEASE.jar
16.spring-expression-3.0.6.RELEASE.jar
17.spring-security-config-3.1.0.RC3.jar
18.spring-security-core-3.1.0.RC3.jar
19.spring-security-crypto-3.1.0.RC3.jar
20.spring-security-taglibs-3.1.0.RC3.jar
21.spring-security-web-3.1.0.RC3.jar
22.spring-web-3.0.6.RELEASE.jar
23.spring-webmvc-3.0.6.RELEASE.jar

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml
            /WEB-INF/security-app-context.xml
            /WEB-INF/application-data-source.xml
        </param-value>
    </context-param>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
      <filter-name>springSecurityFilterChain</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--
      - Provides core MVC application controller. See bank-servlet.xml.
     -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                           http://www.springframework.org/schema/security
                           http://www.springframework.org/schema/security/spring-security-3.1.xsd"
       xmlns:ns1="http://www.springframework.org/schema/security">

    <ns1:global-method-security pre-post-annotations="enabled"/>

    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/pages/result/"
          p:suffix=".jsp" >
          <property name="viewClass">
            <value>
              org.springframework.web.servlet.view.JstlView
            </value>
          </property>
    </bean>

    <!--
    The index controller.
    -->

    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />

    <bean name="/action.htm" id="action" class="com.spt3.controller.ActionController">
        <property name="methodNameResolver">
            <ref bean="paramResolver"/>
        </property>
    </bean>

    <bean id="paramResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
        <property name="paramName">
            <value>action</value>
        </property>
    </bean>

</beans>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">


</beans>

security-app-context.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                    http://www.springframework.org/schema/security 
                    http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <global-method-security pre-post-annotations="enabled"/>

    <http use-expressions="true" auto-config="true" access-denied-page="/pages/accessDenied.jsp">
            <intercept-url pattern="/index.jsp" access="permitAll" />
            <intercept-url pattern="/**.htm" access="isAuthenticated()"/>
            <intercept-url pattern="/pages/*" access="permitAll" />
            <intercept-url pattern="/user/*" access="isAuthenticated()"/>            
            <intercept-url pattern="/md/*" access="hasRole('MD')"/>
            <intercept-url pattern="/admin/*" access="hasAnyRole('Administrator','MD')"/>
            <intercept-url pattern="/manager/*" access="hasAnyRole('Manager','MD')"/>
            <form-login login-page="/pages/login.jsp" authentication-failure-url="/pages/loginfailed.jsp"/>
            <logout logout-success-url="/index.jsp"/>
    </http>

    <beans:bean id="encoder" class="com.spt3.encoder.MyPasswordEncoder"/>

    <authentication-manager>
      <authentication-provider>
        <password-encoder ref="encoder"/>
        <jdbc-user-service data-source-ref="dataSource"

                   users-by-username-query="
                      select username,password, enabled
                      from users where username=?"

                   authorities-by-username-query="
                      select u.username, ur.authority from users u, user_roles ur where u.user_id = ur.user_id and u.username =?  "
        />
      </authentication-provider>
    </authentication-manager>

</beans:beans>

application-data-source.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="dataSource"    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/app" />
        <property name="username" value="uname" />
        <property name="password" value="pword" />
    </bean>

</beans>

ActionController.java

package com.spt3.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.spt3.infc.ActionInterface;
import org.springframework.security.access.prepost.PreAuthorize;

public class ActionController extends MultiActionController implements ActionInterface {

    public ActionController(){
    }

    public ModelAndView getResult(HttpServletRequest request,HttpServletResponse response)throws Exception{
        System.out.println(" - - - - - getResult() - - - - - ");
        try{
            this.getPersonalInformation("MD");
        }catch(Exception e){
            System.out.println(" Exception : "+e);
        }
        return new ModelAndView("result");
    }

    public void getPersonalInformation(String role){
        System.out.println(" "+role+"'s-Personal Information.");
    }
}

ActionInterface.java

package com.spt3.infc;

import org.springframework.security.access.prepost.PreAuthorize;
public interface ActionInterface {

    @PreAuthorize("hasRole('MD')") // Secured method only for role MD
    public void getPersonalInformation(String role);
}

When accessing getResult() method from url (
http://127.0.0.1:8080/myapp/action.htm?action=getResult) secured method can be invoked.

My Expected Result should be

  • getPersonalInformation() method can access only for user role MD

Now Actual Result is

  • getPersonalInformation() method is invoking every user roles.

After using beans - Edited (1) Here

Same problem has been occurred when using bean injection.

Here i changed the files with the code snippet.

ActionController.java is like

package com.spt3.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.spt3.infc.ActionInterface;

public class ActionController extends MultiActionController {

    private ActionInterface actionInterface;

    public ActionController(){
    }

    public ActionController(ActionInterface actionInterface){
        this.actionInterface=actionInterface;
    }

    public ModelAndView getResult(HttpServletRequest request,HttpServletResponse response)throws Exception{
        System.out.println(" - - - - - getResult() - - - - - ");
        try{
            actionInterface.getPersonalInformation("MD");
        }catch(Exception e){
            System.out.println(" Exception : "+e);
        }
        return new ModelAndView("result");
    }

}

ActionInterface.java

package com.spt3.infc;

public interface ActionInterface {

    public void getPersonalInformation(String role);
}

bean class called ActionBean.java

package com.spt3.bean;


import com.spt3.infc.ActionInterface;
import org.springframework.security.access.annotation.Secured;

public class ActionBean implements ActionInterface{

    @Secured("MD")
    public void getPersonalInformation(String role){
        System.out.println(" "+role+"'s-Personal Information.");
    }

}

i used constructor injection to inject the object.

<bean id="actionBean" class="com.spt3.bean.ActionBean"/> <!-- Bean class -->
<bean name="/action.htm" id="action" class="com.spt3.controller.ActionController">
        <property name="methodNameResolver">
            <ref bean="paramResolver"/>
        </property>
        <constructor-arg index="0" ref="actionBean"/> <!-- Injecting object to controller -->
    </bean>

Where i did mistake. please give me the solution.

The problem is solved.

These are the steps i followed.

  1. Configure bean in appropriate xml file
  2. I used bean injection.
  3. i used @PreAuthorize annotation.

Finally the classes are looks like the following snippet when the program is successfully ran.

ActionBean is a separate class i created and i implemented ActionInterface.java class and implemented the method getPersonalInformation() method.

ActionInterface.java looks like this

package com.spt3.infc;

public interface ActionInterface {

    public void getPersonalInformation(String role);
}

and ActionBean.java looks like this

package com.spt3.bean;


import com.spt3.infc.ActionInterface;
import org.springframework.security.access.prepost.PreAuthorize;

public class ActionBean implements ActionInterface{

    @PreAuthorize("hasRole('MD')")
    public void getPersonalInformation(String role){
        System.out.println(" "+role+"'s-Personal Information.");
    }

}

ActionController.java is look like this

package com.spt3.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.spt3.infc.ActionInterface;

public class ActionController extends MultiActionController {

    private ActionInterface actionInterface;

    public ActionController(){
    }

    public ActionController(ActionInterface actionInterface){
        this.actionInterface=actionInterface;
    }

    public ModelAndView getResult(HttpServletRequest request,HttpServletResponse response)throws Exception{
        System.out.println(" - - - - - getResult() - - - - - ");
        try{
            actionInterface.getPersonalInformation("MD");
        }catch(Exception e){
            System.out.println(" Exception : "+e);
        }
        return new ModelAndView("result");
    }

}

Good luck...
Thanks a lot.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蔚蓝源自深海 2024-12-18 16:09:19

Spring 安全性通过在 spring bean 周围使用代理来工作,代理拦截对 bean 方法的调用,并在用户没有适当的角色时抛出异常。但你的控制器不会调用任何 spring bean 方法。它确实调用了一个实例方法:this.getPersonalInformation()

执行此操作时,您不会调用另一个 Spring bean 方法,因此 Spring 无法拦截该调用,因此无法验证用户是否具有适当的角色。

getPersonalInformation 方法放入另一个 Spring bean 中,将该 bean 注入到您的控制器中,一切都应该没问题。

旁注:为什么在这种情况下不简单地使用 @Secured("MD") 注释呢?为什么不直接将注解放在 getResult 方法上呢?

Spring security works by using proxies around the spring beans, which intercept the calls to methods of the beans, and throw an exception if the user doesn't have the appropriate role. But your controller doesn't call any spring bean method. It does call an instance method : this.getPersonalInformation().

When doing this, you're not calling another Spring bean method, so Spring can't intercept the call, and thus can't verify that the user has the appropriate roles.

Put the getPersonalInformation method in another Spring bean, inject this bean in your controller, and all should be fine.

Side note : why not simply using the @Secured("MD") annotation for such a case? And why not put the annotation on the getResult method directly?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文