ReactiveSecurityContextHolder不返回经过身份验证的用户

时间:2017-11-13 17:37:17

标签: spring authentication spring-boot spring-security reactive

我正在尝试在响应式Spring Boot应用程序中配置Spring Security,并包含依赖于新的Spring-Security版本 5.0.0.RC1 的父项目:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.M6</version>
</parent>

我将Spring WebSecurity配置为使用自定义AuthenticationFilter来检索我的身份验证信息以及使用我自己的提供程序的自定义AuthenticationManager。

配置:

@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class WebSecurityConfig {

    private ServerAuthenticationEntryPoint entryPoint = new CustomServerAuthenticationEntryPoint();

    @Bean
    SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception {
        return http
            // we rely on method security
            .authorizeExchange()
                .anyExchange().permitAll()
            .and()
                .logout().disable()
                .authenticationManager(authenticationManager())
                //Override BasicAuthenticationEntryPoint
                .exceptionHandling().serverAuthenticationEntryPoint(this.entryPoint)
            .and()
                .addFilterAt(upmAuthenticationWebFilter(), SecurityWebFiltersOrder.AUTHENTICATION)
            .build();
    }


    private ReactiveAuthenticationManager authenticationManager() {
        return new CustomReactiveAuthenticationManager()
            .authenticationProvider(new CustomAuthenticationProvider());
    }

    private AuthenticationWebFilter upmAuthenticationWebFilter() {
        try {
            AuthenticationWebFilter authenticationFilter = new AuthenticationWebFilter(authenticationManager());
            authenticationFilter.setServerAuthenticationFailureHandler(new ServerAuthenticationEntryPointFailureHandler(this.entryPoint));
            authenticationFilter.setAuthenticationConverter(new CustomAuthenticationConverter(););

            return authenticationFilter;
        } catch (Exception e) {
            throw new BeanInitializationException("Could not initialize AuthenticationWebFilter.", e);
        }
    }
}

ReactiveAuthenticationManager:

public class CustomReactiveAuthenticationManager implements ReactiveAuthenticationManager {

    private List<AuthenticationProvider> authenticationProvider = new ArrayList<>();

    public CustomReactiveAuthenticationManager customAuthenticationProvider(
        final AuthenticationProvider customAuthenticationProvider) {
        this.authenticationProvider.add(customAuthenticationProvider);
        return this;
    }

    @Override
    public Mono<Authentication> authenticate(final Authentication authentication) {
        Class<? extends Authentication> toTest = authentication.getClass();
        for(AuthenticationProvider provider: authenticationProvider) {
            if (provider.supports(toTest)) {
                try {

                    //The provider returns a full authenticated Authentication object.
                    //With authentication.setAuthenticated(true);
                    return Mono.just(provider.authenticate(authentication));
                } catch (Exception e) {
                    return Mono.error(new BadCredentialsException("Invalid Credentials"));
                }
            }
        }
        return Mono.error(new ProviderNotFoundException("Unsupported Credentials"));
    }
}

当我现在在需要经过身份验证的用户的端点上执行调用时。为:

public interface HelloService {
    /**
     * This method returns just 'Hello, world!'.
     *
     * @return Return 'Hello, world!'.
     */
    @PreAuthorize("isAuthenticated()")
    Mono<String> getHelloWorld();
}

我总是得到401 AccessDenied Exception。

在PrePostAdviceReactiveMethodInterceptor第75行调试之后

 auth -> this.preInvocationAdvice.before(auth, invocation, preAttr)

我看到传递的Authentication对象是匿名用户。

现在我的问题: 我是否忘记使用ReactiveSecurityContext配置一些内容?

上周我仍然使用之前的MilestoneRelease M5,其中反应性Spring-Security软件包仍然位于Spring-Security-Reactive下。在这种情况下,检索了身份验证对象,我的请求可以完成。

2 个答案:

答案 0 :(得分:0)

如果有人对此问题感兴趣。

我没有在AuthenticationWebFilter中设置 serverSecurityContextRepository

因此设置此解决了问题。

private AuthenticationWebFilter upmAuthenticationWebFilter() {
    try {
        AuthenticationWebFilter authenticationFilter = new AuthenticationWebFilter(authenticationManager());
        authenticationFilter.setServerAuthenticationFailureHandler(new ServerAuthenticationEntryPointFailureHandler(this.entryPoint));
        authenticationFilter.setAuthenticationConverter(new CustomAuthenticationConverter(););

        //Setting the Context Repo helped
        authenticationFilter.setServerSecurityContextRepository(new WebSessionServerSecurityContextRepository());

        return authenticationFilter;
    } catch (Exception e) {
        throw new BeanInitializationException("Could not initialize AuthenticationWebFilter.", e);
    }
}

答案 1 :(得分:0)

由于设置存储库对我来说不起作用,我只是将Principal添加到我的REST函数中:

@GetMapping("/select")
public Mono<String> select(java.security.Principal principal) {
     log.debug("Authorities: {}", ((Authentication) principal).getAuthorities());
}