使用Spring Security的流程的自定义授权

时间:2019-12-27 13:17:12

标签: java spring spring-security

我有一个REST API,该API在Jetty容器中运行,并受@EnableWebSecurityWebSecurityConfigurerAdapter的Spring(5.2)Security保护,具有表单登录和注销等功能(一切正常,用户都具有角色,可以与REST API等交互)。换句话说:我可以在应用程序中的任何地方使用SecurityContextHolder.getContext().getAuthentication().getPrincipal()。现在,我要授权特定的流程/程序。假设我有一些日常工作,清理数据或将数据导出到运行在不同线程/池或诸如此类的其他系统中。我想为我的应用程序内的特定进程提供特定的安全性上下文(无需自己编写安全性)

我尝试过的事情:

具有自定义AuthenticationManager

public AuthenticationManager authenticationManager(
        final @Qualifier("myCustomAuthenticationProvider") AuthenticationProvider myCustomAuthenticationProvider) {
    return new ProviderManager(Arrays.asList(myCustomAuthenticationProvider));
}

该自定义AuthenticationManagersupportsAuthentication的自定义实现

public class MyCustomAuthenticationToken implements Authentication {
    // this class could define some static set of authorities
    // or load the them from a property or what so ever
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return whatsoever;
    }
}

为了使事情变得简单,我们假设一个非常简单的Provider实现,例如

public class MyCustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(final Authentication authentication) throws 
         AuthenticationException {
         // creating a authentcation... 
         return aFullyPopulatedAuthenticationObject
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass == null || aClass.equals(MyCustomAuthenticationToken.class);
    }
}

使用它的过程可能如下所示:

public class SomeAuthorizedProcess {

    private final AuthenticationManager authenticationManager;

    private final SomeService someServiceUsingSecurityContextHolder;

    public void doSomethingAuthorized() {
        this.authenticationManager.authenticate(new MyCustomAuthenticationToken());

        // returns null because nobody manages the context :-(
        SecurityContextHolder.getContext().getAuthentication()

        // Now I want to call services, that just use the authorizataion as if a 
        // normal user is interacting with the service (via REST API), how ever, the context
        // is here null aswell
        this.someServiceUsingSecurityContextHolder.doSomethingDependingOnGrantedAuthorities();
    }
}

现在我的问题是,我当然没有springSecurityFilterChain来管理SecurityContextHolder的内容。我可以手动设置它,但这感觉非常错误。 Spring Security有办法做到这一点吗?我想错过要点

注意:我不使用Spring Boot,仅使用Spring

0 个答案:

没有答案