Spring MVC Security允许访问的URL返回403错误求助
问题排查与解决方案
核心原因分析
你的问题出在默认根路径转发到index.jsp未被放行:当访问应用时,浏览器默认请求的是/Muzej/(上下文根路径),Tomcat这类容器会自动把根路径转发到/index.jsp,但你只配置了/login、/register为公共URL,/index.jsp不在放行列表里,所以被拦截返回403。把PUBLIC_URLS设为**时所有路径都放行,页面自然能正常加载。
具体解决步骤
放行必要的默认入口与静态资源
在SecurityFilterChain的公共URL列表里,除了/login、/register,还要加上/index.jsp,以及登录页面依赖的CSS、JS等静态资源路径:private static final String[] PUBLIC_URLS = { "/login", "/register", "/index.jsp", "/static/**" // 静态资源路径根据实际情况调整 };明确登录页面的访问配置
要么确保前端直接访问/Muzej/login而非根路径,要么在Security配置里指定登录页面路径并放行:@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers(PUBLIC_URLS).permitAll() .anyRequest().authenticated() ) .formLogin(form -> form .loginPage("/login") // 这里的路径是相对上下文路径的,对应实际请求的/Muzej/login .permitAll() ) .addFilterBefore(jwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); return http.build(); }控制JwtTokenFilter的拦截范围
自定义的JwtTokenFilter要跳过公共URL的校验,避免误拦截:@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String path = request.getServletPath(); AntPathMatcher matcher = new AntPathMatcher(); // 匹配到公共URL直接放行 for (String publicUrl : PUBLIC_URLS) { if (matcher.match(publicUrl, path)) { filterChain.doFilter(request, response); return; } } // 非公共URL执行JWT认证逻辑 // ... 你的JWT校验代码 }验证路径匹配逻辑
用Spring的AntPathMatcher确认路径匹配是否正确,比如判断请求的Servlet路径(去掉上下文路径后的部分)是否和配置的公共URL匹配:AntPathMatcher matcher = new AntPathMatcher(); boolean match = matcher.match("/login", request.getServletPath());
额外注意事项
- 不要在PUBLIC_URLS里加应用上下文路径
/Muzej,Spring Security的路径匹配是基于Servlet路径(即去掉上下文路径后的部分)。 - 检查
login.jsp里有没有引用未放行的资源,哪怕页面本身放行,引用的资源被拦截也会导致页面加载异常。
内容的提问来源于stack exchange,提问作者samax
相关产品推荐
相关产品推荐

