在春季启动响应中登录后未经授权



我正在尝试使用spring-boot-webflux创建表单登录。我可以登录,登录后我被成功重定向。但当我浏览到一个需要身份验证的页面时,我会出错。如果我从安全配置中删除该页面并从ReactiveSecurityContextHolder中获取主体,我将获得用户详细信息。

这是我的安全配置:

public class SecurityConfig {
@Autowired
private UserService userService;
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http
.csrf().disable()
.authorizeExchange()
.pathMatchers("/user/account")
.authenticated()
.anyExchange().permitAll()
.and()
.formLogin()
.loginPage("/user/login")
.authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("/"))
.authenticationManager(reactiveAuthenticationManager())
.and()
.logout()
.and()
.build();
}
@Bean
public ReactiveAuthenticationManager reactiveAuthenticationManager() {
return authentication -> userService.loginUser(authentication)
.switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication.getName())))
.map(user -> new UsernamePasswordAuthenticationToken(user, null));
}
}

我需要在ReactiveAuthenticationManager中做其他事情吗?这是必须的吗?

在此存储库中:https://github.com/mohamedanouarbencheikh/dashboard-auth-microservice您有一个完整的例子,在微服务架构中使用jwt实现spring安全,使用spring云路由(网关(,它基于反应式编程,Netty作为应用服务器,angular作为前端

回答我自己的问题,这样任何面临同样问题的人都可以得到一些帮助:

当我更改了UsernamePasswordAuthenticationToken构造函数并将authority参数传递为null时,问题得到了解决。这真是荒谬。这是更新后的代码:

@Bean
public ReactiveAuthenticationManager reactiveAuthenticationManager() {
return authentication -> userService.loginUser(authentication)
.switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication.getName())))
.map(user -> new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()));
}

我还通过从配置中删除authenticationSuccessHandlerauthenticationManager简化了配置。Spring自动重定向到/。对于authenticationManager,它会自动检查ReactiveAuthenticationManagerbean并使用if find。这是我更新的配置:

public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http
.csrf().disable()
.authorizeExchange()
.pathMatchers("/user/account")
.authenticated()
.anyExchange().permitAll()
.and()
.formLogin()
.loginPage("/user/login")
.and()
.logout()
.logoutUrl("/user/logout")
.logoutSuccessHandler(logoutSuccessHandler("/user/bye"))
.and()
.build();
}

最新更新