You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 2.0升级3.0后直接访问权限路径出现403白标错误

Spring Boot 3.0升级后直接访问受保护路径403问题解决

直接访问/admin这类受保护路径时返回403,但从根路径导航至该路径却能正常访问,核心原因是直接访问受保护资源时,Spring Security未触发SAML2认证流程,直接判定请求未授权;而从根路径访问时,Vaadin的初始化流程会触发会话建立或认证检查,间接完成了SAML2的认证引导。

以下是具体解决方案:

1. 配置认证入口点,引导未认证请求到SAML2登录

修改securityFilterChain方法,添加exceptionHandling配置,让未认证的受保护资源请求自动跳转到SAML2 IDP登录页面:

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http, RequestUtil requestUtil, RelyingPartyRegistrationRepository registrationRepository) throws Exception {
    http.csrf(cfg -> cfg.ignoringRequestMatchers(requestUtil::isFrameworkInternalRequest));
    http.authorizeHttpRequests(authorize -> authorize
            .requestMatchers("/user/*").hasAnyRole(ApplicationConstants.APPLICATION_USER.toString())
            .requestMatchers("/admin/*").hasAuthority(ApplicationConstants.APPLICATION_ADMIN.toString())
            .requestMatchers("/h2-console/**").permitAll()
            // 放行Vaadin核心静态资源,避免初始化受阻
            .requestMatchers("/VAADIN/**", "/favicon.ico", "/robots.txt", "/manifest.webmanifest").permitAll()
            .anyRequest().authenticated()
    )
    .saml2Login(saml2 -> {})
    // 配置认证入口点,触发SAML2登录流程
    .exceptionHandling(exceptions -> exceptions
            .authenticationEntryPoint(new Saml2WebSsoAuthenticationEntryPoint(new DefaultRelyingPartyRegistrationResolver(registrationRepository)))
    );

    return http.build();
}

2. 验证角色/权限匹配逻辑

Spring Security 6.x中,hasAnyRole()会自动为角色名添加ROLE_前缀,而hasAuthority()不会:

  • 如果IDP返回的权限带ROLE_前缀(如ROLE_ADMIN),需将hasAuthority(ApplicationConstants.APPLICATION_ADMIN.toString())改为hasAnyRole(ApplicationConstants.APPLICATION_ADMIN.toString())
  • 如果IDP返回的权限不带前缀,需确保ApplicationConstants.APPLICATION_ADMIN的值与IDP返回的权限完全一致

3. 同步Vaadin视图权限配置

确保Vaadin视图上的权限注解与Security配置匹配,比如:

@Route("admin")
@Secured(ApplicationConstants.APPLICATION_ADMIN.toString())
public class AdminView extends VerticalLayout {
    // 视图逻辑
}

4. 检查会话管理配置(可选)

显式配置会话策略,确保认证后会话被正确维护:

http.sessionManagement(session -> session
        .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
);

验证效果

修改配置后,直接访问http://localhost:8080/application/admin/会自动跳转到SAML2 IDP登录页面,登录成功后将直接进入admin页面,不再返回403错误。

内容的提问来源于stack exchange,提问作者user2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 06:12:02