Angular 10对接Spring Security登录后遇请求拒绝及JSON解析异常求助
问题根因
- 后端
RequestRejectedException触发原因:Spring Security 5.x默认的StrictHttpFirewall会将URL中的双斜杠//判定为恶意字符串拦截。该报错通常出现在未认证请求被重定向到默认登录页的流程中——重定向拼接URL时自动产生双斜杠,直接被防火墙拦截。 - 前端JSON解析报错原因:当前配置是Spring Security默认的服务端渲染表单登录逻辑,和前后端分离架构不匹配:
- 你在
UserController中写的自定义/user/login接口仅做了认证校验,没有将认证信息写入Spring Security的上下文,后续Angular发起的/home/default请求因为没有携带有效认证态,被Spring Security自动重定向到默认的/login页面,返回的是HTML格式的登录页内容,Angular将其按JSON解析就会报Unexpected token <的错误。 - 前端控制台显示请求URL为
http://localhost:8080/login,就是重定向逻辑直接导致的。
- 你在
- 配置冲突原因:你同时在多处配置CORS规则(
CorsConfigurationSourceBean、WebMvcConfigurer的映射配置、Controller上的@CrossOrigin注解),会导致CORS响应头重复,干扰请求处理。
解决方案
1. 修复防火墙双斜杠拦截问题
在WebSecurityConfig中注册自定义的防火墙规则,放行双斜杠URL:
@Bean public StrictHttpFirewall strictHttpFirewall() { StrictHttpFirewall firewall = new StrictHttpFirewall(); firewall.setAllowUrlEncodedDoubleSlash(true); firewall.setAllowSemicolon(true); return firewall; }
2. 改造为适配前后端分离的认证逻辑
修改configure(HttpSecurity http)方法,关闭默认的页面跳转逻辑,未认证请求直接返回JSON格式的401响应,不做页面重定向:
@Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() // 关闭默认表单登录的页面跳转逻辑 .formLogin().disable() .httpBasic().disable() // 未认证请求返回401 JSON,替代原来的重定向到/login的逻辑 .exceptionHandling() .authenticationEntryPoint((request, response, authException) -> { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setContentType("application/json;charset=utf-8"); response.getWriter().write("{\"code\":401,\"msg\":\"未完成认证\"}"); }) .and() .authorizeRequests() .antMatchers("/home/**", "/user/login", "/admin/**").permitAll() .anyRequest().authenticated() .and() .cors(); }
补全自定义登录接口的认证上下文写入逻辑,确保Spring Security能识别登录态:
@PostMapping("/login") public ResponseEntity<Object> login(@RequestBody loginDetails data) { try { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(data.getUsername(), data.getPassword()) ); // 关键:将认证信息写入Security上下文,否则后续请求无法识别登录态 SecurityContextHolder.getContext().setAuthentication(authentication); Map<Object, Object> model = new HashMap<>(); model.put("username", data.getUsername()); return new ResponseEntity<>(model, HttpStatus.OK); } catch (AuthenticationException e) { return new ResponseEntity<>("invalid", HttpStatus.NOT_ACCEPTABLE); } }
Angular侧需要调整HttpClient配置,给所有请求开启
withCredentials: true,确保会话cookie能跨域携带,否则认证态无法传递。
3. 清理冗余CORS配置
- 删除
WebSecurityConfig中的CorsConfig内部类、删除Controller上的@CrossOrigin注解,仅保留你已定义的CorsConfigurationSourceBean即可,Spring Security的cors()方法会自动加载该配置,重复配置会导致跨域头冲突。
内容的提问来源于stack exchange,提问作者AKSHAY GULATI
相关产品推荐
相关产品推荐

