Skip to main content
 首页 » 编程设计

spring之如何使用 Spring MVC 3.2 和 Spring Security 3.1 的方法安全性执行 RunAs

2025年01月19日12sxdcgaq8080

我有一个带有 Spring MVC 3.2 和 Spring Security 3.1 的 Web 应用程序

我正在使用基于角色的安全性并实现了 UserDetailsS​​ervice 和 UserDetails 以提供 GrantedAuthority。

我已经使用 jsr250-annotations 启用了全局方法安全性

到这里为止的所有内容都按预期工作,登录用户方法访问仅限于声明的角色。

我还有一个进一步的要求,即在应用程序初始化期间作为具有“系统角色”的特殊用户运行某些方法,理想情况下是沿着 JavaEE RunAs 的路线。
我不确定如何在 Spring Security 中执行此操作。

我应该尝试创建一个 PreAuthenticatedAuthenticationToken具有一些虚构的值(value)观和“系统角色”权限。
然后我可以做类似 SecurityContextHolder.getContext().setAuthentication(token); 的事情
在初始化应用程序时。

或者,我应该尝试使用 RunAsManager。这听起来像是我需要的,但我还没有找到任何关于如何实际使用它的简单示例。

我对 Spring Security 还很陌生,我不确定最好的方法是什么。

请您参考如下方法:

当我的应用程序启动时

  • 我在 spring bean 中运行了一个 post 构造方法,以在内存中创建一个具有系统角色的特殊用户。
  • 这个用户对象实现了
    org.springframework.security.core.userdetails.UserDetails
    interface.
  • I then use the user to create a security token
    org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken
  • The token is then set in the Security Context.

    @Service 
    @Transactional(readOnly = true) 
    public class ApplicationConfiguration{ 
        @Inject 
        MyService myService; 
        @PostConstruct 
        @Transactional(readOnly = false) 
        public void init(){ 
     
            // ######## Application Starting #######" 
     
            // Create a user that meets the contract of the Spring UserDetails interface 
     
            UserAccountImpl sysAcc = new UserAccountImpl("system", "system", "system"); 
            UserRole role = new UserRole(Role.SYSTEM_ROLE); 
            role.addUserPermission(Permission.SYSTEM); 
            sysAcc.addUserRole(role); 
            UserDetailsAdapter userDetails = new UserDetailsAdapter(sysAcc); 
     
            // Create a token and set the security context 
     
            PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( userDetails, userDetails.getPassword(), userDetails.getAuthorities()); 
            SecurityContextHolder.getContext().setAuthentication(token); 
     
            // Now call service method with roles allowed   
     
            myService.initialiseSystem(); 
        } 
    } 
    

    ....
    public interface MyService { 
        @RolesAllowed(SYSTEM) 
        public void initialiseSystem(); 
    }