【发布时间】:2020-10-20 09:21:36
【问题描述】:
我在我的 Web 应用程序中使用 Spring Boot 和 Spring Security。现在我有一个 /api/login 端点,前端只需在请求正文中发布用户名和密码即可获取 JWT。
但我不断得到
Access to fetch at 'http://localhost:8081/api/login' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
我已经在控制器类上添加了 @CrossOrigin(origins = "*",maxAge = 3600) 来解决 cors 问题,所以现在 http get 工作正常。但是由于预检,所有帖子都不起作用。我也试过了
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
和
.and().cors();
在我的 WebSecurityConfigurerAdapter 中,但没有一个能解决问题。接下来我该怎么做?
这是完整的配置类:
package com.cyf.myblogserver.config;
import com.cyf.myblogserver.component.JwtRequestFilter;
import com.cyf.myblogserver.service.BlogUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsUtils;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private BlogUserDetailsService BlogUserDetailsService;
@Autowired
JwtRequestFilter jwtRequestFilter;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(BlogUserDetailsService);
}
@Bean
public PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.antMatchers(HttpMethod.POST,"/api/token").permitAll()
.antMatchers(HttpMethod.GET, "/api/articles").permitAll()
.anyRequest().authenticated().and().cors();
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
http.headers().cacheControl();
}
@Bean
public AuthenticationManager customAuthenticationManager() throws Exception {
return authenticationManager();
}
}
【问题讨论】:
标签: spring-boot spring-security