Spring security 如果CORS标头‘;访问控制允许原点’;is‘*’;
我已经完成了服务工作,部署没有问题,但我需要添加更多功能[实时通知]。我使用的是SockJS、StompJS、Spring-security和LDAP身份验证 这是我的AuthenticationFilter,我使用令牌作为登录LDAP后生成的密码Spring security 如果CORS标头‘;访问控制允许原点’;is‘*’;,spring-security,spring-websocket,sockjs,stompjs,Spring Security,Spring Websocket,Sockjs,Stompjs,我已经完成了服务工作,部署没有问题,但我需要添加更多功能[实时通知]。我使用的是SockJS、StompJS、Spring-security和LDAP身份验证 这是我的AuthenticationFilter,我使用令牌作为登录LDAP后生成的密码 @Log4j2 public class AuthenticationFilter extends OncePerRequestFilter { @Autowired private JWTUtil jwtUtil; private
@Log4j2
public class AuthenticationFilter extends OncePerRequestFilter {
@Autowired
private JWTUtil jwtUtil;
private final String authHeader = "token";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
//CORS
response.addHeader("Access-Control-Allow-Origin", "*");
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.addHeader("Access-Control-Allow-Headers", "token");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
}
final String authHeader = request.getHeader(this.authHeader);
if (authHeader != null) {
String token = authHeader;
try {
Claims claims = jwtUtil.getAllClaimsFromToken(token);
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
new User(claims.getSubject()),
null,
authorities
);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (Exception e) {
log.debug("Error ", e);
}
}
if (!request.getMethod().equalsIgnoreCase("OPTIONS")) {
chain.doFilter(request, response);
}
}
}
最后一个是我的WebSocketConfig
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public UnauthorizedHandler unauthorizedHandler() throws Exception {
return new UnauthorizedHandler();
}
@Bean
public ForbiddenHandler forbiddenHandler() throws Exception {
return new ForbiddenHandler();
}
@Bean
public AuthenticationFilter authenticationFilterBean() throws Exception {
return new AuthenticationFilter();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// we don't need CSRF because our token is invulnerable
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler()).and()
.exceptionHandling().accessDeniedHandler(forbiddenHandler()).and()
// don't create session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
// allow auth url
.antMatchers("/login","/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**", "/notif/**", "/mealnotif/**", "/topic/**", "/websocket/**", "/resources/**", "/META-INF/resources/**").permitAll()
.anyRequest().authenticated();
// custom JWT based security filter
httpSecurity.addFilterBefore(authenticationFilterBean(), UsernamePasswordAuthenticationFilter.class);
// disable page caching
httpSecurity.headers().cacheControl();
}
}
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/mealnotif");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/notif").setAllowedOrigins("*")
.withSockJS();
}
}
但作为回报,我的角度项目总是返回交叉原点请求被阻止
如何解决此问题?我可以通过在application.properties中添加允许来源的白名单来解决此问题
management.endpoints.web.cors.allowed-origins=http://localhost,http://localhost:4200
通过这一点,我成功地对客户做出了正确的回应
我可以通过在application.properties中添加允许来源的白名单来解决这个问题
management.endpoints.web.cors.allowed-origins=http://localhost,http://localhost:4200
通过这一点,我成功地对客户做出了正确的回应