Spring+Vue项目如何通过Spring Security控制API端点暴露保障数据安全
你完全可以通过Spring Security实现该控制,你当前遇到的问题核心是现有安全配置仅对少量指定路径做了权限规则,其余所有路径(包括/contracts接口)默认只要完成身份认证就可直接访问,没有额外限制。
方案1:补全基础权限控制(最简实现)
在你现有的WebSecurityConfig的configure(HttpSecurity http)方法的authorizeRequests配置块末尾,添加接口的权限规则,以及全局默认规则:
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/css/**", "/js/**", "/img/**", "favicon.ico", "/materialize/**", "/style/**").permitAll() .antMatchers(HttpMethod.GET, "/new-user").hasRole("ADMIN") .antMatchers(HttpMethod.POST, "/new-user").hasRole("ADMIN") .antMatchers("/login").permitAll() .antMatchers("/signup").permitAll() // 新增:给业务接口配置对应权限,按需调整角色范围 .antMatchers("/contracts").hasAnyRole("USER", "ADMIN") // 新增:所有未显式配置的路径,默认需要登录后访问 .anyRequest().authenticated() .and().csrf().disable().formLogin().successHandler(customizeAuthenticationSuccessHandler) .loginPage("/login").failureUrl("/login?error=true").usernameParameter("email") .passwordParameter("password").and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/").and().exceptionHandling(); }
如果需要更严格的控制,避免用户直接在浏览器地址栏输入接口地址拿到JSON响应,可以继续叠加下面的方案。
方案2:限制仅前端AJAX请求可访问接口
可以通过校验请求头实现,前端发起AJAX请求时统一携带自定义请求头(比如X-Requested-With: XMLHttpRequest,大部分AJAX库默认会带),直接浏览器访问时不会携带该请求头,此时直接拦截请求:
- 新增自定义请求校验过滤器:
@Component public class AjaxRequestCheckFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String requestUri = request.getRequestURI(); // 匹配所有业务接口路径,按需调整规则 if (requestUri.startsWith("/contracts") || requestUri.startsWith("/other-api")) { String requestedWith = request.getHeader("X-Requested-With"); if (!"XMLHttpRequest".equals(requestedWith)) { // 非AJAX请求直接重定向到首页或者返回403 response.sendRedirect("/"); return; } } filterChain.doFilter(request, response); } }
- 在
WebSecurityConfig中注册过滤器:
@Autowired private AjaxRequestCheckFilter ajaxRequestCheckFilter; @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore(ajaxRequestCheckFilter, UsernamePasswordAuthenticationFilter.class) // 其余原有配置保持不变 .authorizeRequests() // ... 原有配置省略 }
方案3:统一API前缀管理
更规范的做法是给所有后端接口统一添加/api前缀,比如把/contracts改成/api/contracts,一方面方便安全规则统一配置,另一方面也可以避免和前端路由路径冲突,安全配置可以直接批量限制所有/api/**路径的访问规则。
内容的提问来源于stack exchange,提问作者Kelvyn Cavalcante
相关产品推荐
相关产品推荐

