【发布时间】:2020-07-14 11:03:02
【问题描述】:
我的设置是一个 Zuul 网关服务器,它重定向到一个图书处理 API (Spring)。问题是当路由未经过身份验证时它重定向很好,但是当我尝试访问经过身份验证的路由时 - 它失败了。我会补充一点,直接访问 API 可以正常工作。
这是我在网关的安全配置:
@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("admin").password("{noop}admin").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/book-service/books").permitAll()
.antMatchers("/eureka/**").hasRole("ADMIN")
.anyRequest().authenticated().and()
.formLogin().usernameParameter("username").passwordParameter("password")
.defaultSuccessUrl("/success").and()
.logout().permitAll().and()
.csrf().disable();
}
}
我在 Gateway 的 Zuul 属性:
zuul.routes.book-service.path=/book-service/**
zuul.routes.book-service.sensitive-headers=Set-Cookie,Authorization
zuul.routes.book-service.url=http://localhost:8085
hystrix.command.book-service.execution.isolation.thread.timeoutInMilliseconds=600000
这是我在 Gateway 的 Zuul 过滤器:
@Component
public class SessionSavingZuulPreFilter
extends ZuulFilter {
@Autowired
private SessionRepository repository;
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
RequestContext context = RequestContext.getCurrentContext();
HttpSession httpSession = context.getRequest().getSession();
Session session = repository.findById(httpSession.getId());
context.addZuulRequestHeader(
"Cookie", "SESSION=" + httpSession.getId());
return null;
}
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 0;
}
}
现在,在客户端 API 中,我有以下安全配置:
http.httpBasic()
.disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/books").permitAll()
.antMatchers(HttpMethod.GET, "/books/*").hasRole("ADMIN")
.antMatchers(HttpMethod.POST, "/books").hasRole("ADMIN")
.antMatchers(HttpMethod.PATCH, "/books/*").hasRole("ADMIN")
.antMatchers(HttpMethod.DELETE, "/books/*").hasRole("ADMIN")
//.antMatchers("/encrypt/**").permitAll()
//.antMatchers("/decrypt/**").permitAll()
.anyRequest().authenticated()
.and()
.csrf()
.disable();
我可以在身份验证后访问http://localhost:8085/books/1(因此过滤器似乎工作正常),但http://localhost:[gateway]/book-service/books/1 给了我错误。有人可以帮忙吗?
【问题讨论】:
标签: spring spring-security spring-cloud netflix-zuul