我有两个使用 Spring boot 创建的端点。一个是安全的,第二个是非安全的。
安全是/api/v1/hello
非安全是/api/v1/auth/hello
我已经实现了如下的安全过滤器链
...
...
...
private final JwtAuthenticationFilter jwtAuthFilter;
private final AuthenticationProvider authenticationProvider;
private final LogoutHandler logoutHandler;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {d
http
.csrf()
.disable()
.authorizeHttpRequests()
.requestMatchers("/api/v1/auth/**")
.permitAll()
.requestMatchers("/api/v1/admin/**").hasAuthority("ADMIN")
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.logout()
.logoutUrl("/api/v1/auth/logout")
.addLogoutHandler(logoutHandler)
.logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder.clearContext())
;
return http.build();
}
对于 JwtAuthenticationFilter 类中的安全端点,当我尝试打印令牌时它为空。 由于这个错误,我也遇到了 cors 政策的问题
Access to fetch at 'http://localhost:8080/api/v1/hello' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
对于非安全端点,一切都很好,没有与 cors 相关的错误,甚至当我尝试为非安全端点传递承载令牌时,它也被正确传递。我只是为了安全端点而变得空。
在邮递员中一切都很好但是通过浏览器它看起来像是删除了不记名令牌。
cors配置
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/v1/hello")
.allowedOrigins("http://localhost:3000")
.allowedMethods("GET", "POST","PUT", "DELETE")
.allowedHeaders("Content-Type","Authorization")
.allowCredentials(true);
registry.addMapping("/api/v1/auth/hello")
.allowedOrigins("http://localhost:3000")
.allowedMethods("GET", "POST","PUT", "DELETE");
}
};
}
和前端部分
const handleClickNonSecured = async ()=>{
const response = await fetch("http://localhost:8080/api/v1/auth/hello");
...
}
const handleClickSecured =async ()=> {
const token =......;
const requestParams = {
method: "GET",
headers:{
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
}
}
const response = await fetch("http://localhost:8080/api/v1/hello",requestParams);
...
}
有人有类似的问题吗?也许我对安全过滤器链的理解是错误的?