Spring Security OAuth2 阻止来自 Keycloak 的重定向 URL

问题描述 投票:0回答:1

我正在使用 Spring Security 和 Keycloak 在我的 Spring Boot 应用程序中集成 OAuth2 身份验证。该设置涉及一个魔术链接解决方案,用户单击魔术链接并使用授权代码重定向回客户端。但是,在日志中,我在重定向回客户端时看到了这一点。

Securing GET /login/oauth2/code/my-client?session_state=b8080c20-b622-47cd-b504-c95f482ee124&code=d520e689-2519-489b-8161-79169f99fefa.b8080c20-b622-47cd-b504-c95f482ee124
DEBUG 1 --- [nio-8080-exec-6] o.s.s.web.DefaultRedirectStrategy        : Redirecting to /login?error

这是我的安全配置

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, InMemoryClientRegistrationRepository clientRegistrationRepository) throws Exception {
        // Configure CSRF
        http.csrf(AbstractHttpConfigurer::disable);

        http.sessionManagement(sessionManagement -> sessionManagement
                        .sessionCreationPolicy(IF_REQUIRED)
                        .sessionFixation(SessionManagementConfigurer.SessionFixationConfigurer::newSession)
                        .maximumSessions(1)
                        .expiredUrl("/404")
                        .maxSessionsPreventsLogin(true));
        // Configure OAuth2 login
        http.oauth2Login(withDefaults());

        http.logout(logout -> logout.logoutSuccessHandler(oidcLogoutSuccessHandler()));
        http.oauth2Client(withDefaults());


        // Configure authorization rules
        http.authorizeHttpRequests(authorizeRequests ->
                authorizeRequests
                        .requestMatchers("/", "/login/**", "/oauth2/**", "/api/generate/**").permitAll()
                        .requestMatchers("/login?error").permitAll()
                        .requestMatchers("/login/oauth2/code/**").permitAll() // Explicitly permit OAuth2 code handling endpoint
                        .requestMatchers("/api/sessions").authenticated()
                        .requestMatchers("/something").hasAnyRole("admin", "user")
                        // Add more matchers for your application as required
                        .anyRequest().permitAll() //todo change to authenticated
        );

        return http.build();
    }

我预计不会收到“Secured GET”日志,因为我允许使用“.permitAll()”的端点

spring spring-security oauth-2.0 keycloak
1个回答
0
投票

我预计不会收到“Secured GET”日志,因为我允许使用“.permitAll()”的端点

这是对 Spring Security 如何处理身份验证端点的常见误解。

authorizeHttpRequests
中描述的是application端点的访问规则,而不是其身份验证端点。因此,声明允许
/login/oauth2/code/**
对于 Spring Security 的行为没有任何影响。

您要做的步骤是弄清楚为什么 Spring Security 拒绝

session_state
code
参数,因为它们是由 OAuth 设计的足以建立会话。

© www.soinside.com 2019 - 2024. All rights reserved.