想请教一下,在gateway中,使用security webflux组件,其他都成功了,就是想通过@PreAuthorize注解做权限鉴权一直注解失效,SecurityWebFluxConfig文件中也添加了@EnableReactiveMethodSecurity注解,就是不生效
完整配置:
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityWebFluxConfig {
//自定义的鉴权服务,通过鉴权的才能继续访问某个请求
@Resource
private MyRBACServiceWebFlux myRBACServiceWebFlux;
// 无权限访问被拒绝时的自定义处理器
@Resource
private MyAccessDeniedHandlerWebFlux myAccessDeniedHandlerWebFlux;
// 登录成功时自定义处理器
@Resource
private LoginSuccessHandlerWebFlux loginSuccessHandlerWebFlux;
// 登录失败时调用的自定义处理类
@Resource
private LoginFailedHandlerWebFlux loginFailedHandlerWebFlux;
// 成功登出时调用的自定义处理类
@Resource
private LogoutSuccessHandlerWebFlux logoutSuccessHandlerWebFlux;
// 未登录访问资源时的处理类
@Resource
private NotLoginHandlerWebFlux customHttpBasicServerAuthenticationEntryPoint;
@Autowired
private MyConfig myConfig;
@Bean
SecurityWebFilterChain webFluxSecurityFilterChain(ServerHttpSecurity http) throws Exception {
http
.authorizeExchange()
// 免登录访问,jwt和security共用
.pathMatchers(myConfig.getNoAuth()).permitAll()
// .pathMatchers(HttpMethod.OPTIONS).permitAll()
//.pathMatchers("/whoAmI").hasAuthority("ROLE_ADMIN")
.and()
.authorizeExchange()
//自定义的鉴权服务,通过鉴权的才能继续访问某个请求(就是url校验权限)
/*.pathMatchers("/**").access(myRBACServiceWebFlux)
.anyExchange().authenticated()*/
.and()
.formLogin()
.loginPage("/console/login")
.authenticationSuccessHandler(loginSuccessHandlerWebFlux) //认证成功
.authenticationFailureHandler(loginFailedHandlerWebFlux) //登陆验证失败
.and().exceptionHandling().authenticationEntryPoint(customHttpBasicServerAuthenticationEntryPoint) //未登录访问资源时的处理类,若无此处理类,前端页面会弹出登录窗口
.and().exceptionHandling().accessDeniedHandler(myAccessDeniedHandlerWebFlux)//访问被拒绝时自定义处理器
.and() .csrf().disable()//必须支持跨域
.logout().logoutUrl("/console/logout")
.logoutSuccessHandler(logoutSuccessHandlerWebFlux).and()
.httpBasic().disable();//成功登出时调用的自定义处理类
return http.build();
}
}
@RestController
public class BusinessController {
@RequestMapping("/adminCall")
public Mono<String> adminCall(WebSession session, ServerWebExchange exchange){
return Mono.just("通过");
}
//用户登录后,会把UserDetails对象放入context中,此接口用于测试存放的用户信息
@RequestMapping("/whoAmI")
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public String whoAmI(){
return JSONObject.toJSONString(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
}
}