Java Spring API REST、Cors和AngularJS
我有弹簧靴和Cors的问题 经过一些搜索,我找到了解决方案,我试过了,但没有解决我的问题。 我的JWT身份验证代码Java Spring API REST、Cors和AngularJS,java,spring,rest,spring-security,spring-boot,Java,Spring,Rest,Spring Security,Spring Boot,我有弹簧靴和Cors的问题 经过一些搜索,我找到了解决方案,我试过了,但没有解决我的问题。 我的JWT身份验证代码 public class AuthenticationFilter extends AbstractAuthenticationProcessingFilter { private final Logger log = LoggerFactory.getLogger(AuthenticationFilter.class); private final String token
public class AuthenticationFilter extends AbstractAuthenticationProcessingFilter
{
private final Logger log = LoggerFactory.getLogger(AuthenticationFilter.class);
private final String tokenHeader = "Authorization";
private final TokenUtils tokenUtils = new TokenUtils();
public AuthenticationFilter()
{
super("/api/v1/**");
tokenUtils.expiration = 86400;
tokenUtils.secret = "papipapo123popo";
}
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException
{
String header = httpServletRequest.getHeader(tokenHeader);
if(header == null || !header.startsWith("Bearer "))
{
log.error("Not found JWT token in request headers","Not found header Authorization");
throw new JwtTokenMissingException("No JWT token found in request headers");
}
String token = header.substring(7);
JwtAuthentication jwtAuthentication = new JwtAuthentication(token);
boolean isValid = tokenUtils.validateToken(token);
if(!isValid)
{
log.error("JWT token is expired",token);
throw new JwtTokenExpired("JWT token is expired");
}
return this.getAuthenticationManager().authenticate(jwtAuthentication);
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException
{
super.successfulAuthentication(request, response, chain, authResult);
String token = ((JwtAuthentication)authResult).getToken();
log.info("Token is authenticated : ",token);
chain.doFilter(request, response);
}
@Override
protected AuthenticationManager getAuthenticationManager()
{
return authentication -> (JwtAuthentication) authentication;
}
}
我的配置安全代码
@Configuration
@EnableWebSecurity
@EnableAutoConfiguration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter
{
@Inject
private EntryPointUnauthorizedHandler entryPointUnauthorizedHandler;
@Inject
private JwtAuthenticationProvider jwtAuthenticationProvider;
@Bean
@Override
public AuthenticationManager authenticationManager() throws Exception
{
return new ProviderManager(Arrays.asList(jwtAuthenticationProvider));
}
@Bean
public AuthenticationFilter authenticationFilter() throws Exception
{
AuthenticationFilter authenticationFilter = new AuthenticationFilter();
authenticationFilter.setAuthenticationManager(authenticationManager());
authenticationFilter.setAuthenticationSuccessHandler(new EntryPointSuccessHandler());
return authenticationFilter;
}
@Bean
public FilterRegistrationBean corsFilter()
{
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
source.registerCorsConfiguration("/**",config);
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new CorsFilter(source));
filterRegistrationBean.setOrder(0);
return filterRegistrationBean;
}
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(entryPointUnauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers(HttpMethod.POST,"/api/auth").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationFilter(),UsernamePasswordAuthenticationFilter.class);
http.headers().cacheControl();
}
}
我总是收到一个错误401拒绝访问。
我是一个春天靴子的初学者。
您可以帮助我。我通过添加一个实现过滤器的类解决了我的问题
@Component
public class CorsConfig implements Filter
{
@Override
public void init(FilterConfig filterConfig) throws ServletException
{}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest) servletRequest;
String method = request.getMethod();
if(method.equals("OPTIONS") || method.equals("options"))
{
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
response.setStatus(200);
filterChain.doFilter(servletRequest, servletResponse);
}
else
{
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
filterChain.doFilter(servletRequest, servletResponse);
}
}
@Override
public void destroy()
{}
}
我通过添加一个实现过滤器的类来解决我的问题
@Component
public class CorsConfig implements Filter
{
@Override
public void init(FilterConfig filterConfig) throws ServletException
{}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest) servletRequest;
String method = request.getMethod();
if(method.equals("OPTIONS") || method.equals("options"))
{
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
response.setStatus(200);
filterChain.doFilter(servletRequest, servletResponse);
}
else
{
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
filterChain.doFilter(servletRequest, servletResponse);
}
}
@Override
public void destroy()
{}
}
头等舱:
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
}
二等舱:
@EnableWebSecurity
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**").authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.anyRequest().fullyAuthenticated().and().httpBasic().and().csrf().disable();
}
}
祝我的朋友快乐,头等舱:
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
}
二等舱:
@EnableWebSecurity
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**").authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.anyRequest().fullyAuthenticated().and().httpBasic().and().csrf().disable();
}
}
祝你快乐,我的朋友:创建一个类WebMvcConfig扩展WebMvcConfiguration并覆盖addCorsMappings方法 2:别忘了在@Configuration注释中使用它
@Configuration
public class WebMvcCofig implements WebMvcConfigurer{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true);
}
}
1:创建一个类WebMvcConfig扩展WebMvcConfiguration并重写addCorsMappings方法 2:别忘了在@Configuration注释中使用它
@Configuration
public class WebMvcCofig implements WebMvcConfigurer{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true);
}
}
使用弹簧靴版本1.4.1使用弹簧靴版本1.4.1