Setting Up a Centralized Authentication Server with AWS Cognito and Spring Security Using JWT

i am using AWS Cognito as a custom provider, before i integrated aws cognito with spring security, where after successful login i took the id, access token and saved it in session. which worked fine. i did more research and now want to use the jwt token instead of session. i need help here

here is method that logs in a user in cognito

  public String login(String username, String password, String userPoolId, String clientId, CognitoIdentityProviderClient client) {
        logger.info("Login method called");
        if (userPoolId == null || userPoolId.isEmpty()) {
            userPoolId = awsCredentials.getCognitoPoolId();
        }
        if (clientId == null || clientId.isEmpty()) {
            clientId = awsCredentials.getCognitoClientId();
        }

        AdminInitiateAuthRequest authRequest = AdminInitiateAuthRequest.builder()
                .clientId(clientId)
                .userPoolId(userPoolId)
                .authFlow(AuthFlowType.ADMIN_NO_SRP_AUTH)
                .authParameters(Map.of("USERNAME", username, "PASSWORD", password))
                .build();
        AdminInitiateAuthResponse response = client.adminInitiateAuth(authRequest);

        if (response.authenticationResult() != null) {
            String accessToken = response.authenticationResult().accessToken();
            String idToken = response.authenticationResult().idToken();
            logger.info("Login successful for user: {}", username);
            return accessToken+ idToken;
        } else {
            throw new AuthenticationServiceException("Login failed: " + response.challengeName());
        }
    }

as you can see it returns tokens, I need a way to inform Spring Security that a user is authenticated using these tokens. how. i dont need to have custom jwt token since cognito provides it already. i just need a steps to fallow, the main goal is to make this server a centralized auth server where multiple client can register and login there account in aws cognito and get jwt tokens from this server to access spicific resources based on the scope they get in there account.

additional info

 @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(AbstractHttpConfigurer::disable)
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .addFilterBefore(tokenValidationFilter, CognitoAuthenticationFilter.class)
                .addFilterBefore(cognitoAuthenticationFilter(authenticationManager(http)), UsernamePasswordAuthenticationFilter.class)
                .authorizeHttpRequests(auth -> {
                    auth.requestMatchers("/admin").hasAuthority("SCOPE_aws.cognito.signin.user.admin");
                    auth.requestMatchers("/emails").hasAuthority("SCOPE_research.admin");
                    auth.requestMatchers("/register", "/verify").permitAll();
                    auth.requestMatchers("/images/**").permitAll();
                    auth.anyRequest().authenticated();
                })
                .formLogin(form -> form
                        .loginPage("/login")
                        .permitAll())
                .logout(logout -> logout
                        .logoutUrl("/logout")
                        .addLogoutHandler(customLogoutHandler)
                        .logoutSuccessUrl("/login?logout")
                );

        return http.build();
    }

  @Bean
    public CognitoAuthenticationFilter cognitoAuthenticationFilter(AuthenticationManager authenticationManager) {
        CognitoAuthenticationFilter filter = new CognitoAuthenticationFilter(cognitoAuthenticationProvider, authenticationManager);
        filter.setAuthenticationManager(authenticationManager);
        return filter;
    }

 @Bean
 public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
        log.info("calling AuthenticationManager");
        AuthenticationManagerBuilder builder = http.getSharedObject(AuthenticationManagerBuilder.class);
        builder.authenticationProvider(cognitoAuthenticationProvider);
        return builder.build();
    }

i did try this but after i loged in and AuthenticationManager > CognitoAuthenticationFilter > CognitoAuthenticationProvider was all seccessfull, but somehow even though i can see the seccessful login, spring secirity wont let me be authenticated

New contributor

Stykle Sty is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật