Anonymous
Контроллер Ping недоступен в Spring Security
Сообщение
Anonymous » 28 сен 2024, 04:10
Я использую Spring Security для базового входа и знака oauth2 в своем приложении Spring Boot. Я просто делюсь всеми цепочками фильтров безопасности. Я также создал все остальные необходимые компоненты, такие как BCrypt, JwtDecoder и JwtEncoder. Все необходимые аннотации также присутствуют. Также укажите на любую другую ошибку, которую вы заметили. Вот мой файл SecurityConfig:
Код: Выделить всё
public class SecurityConfig {
private final RSAKeyRecord rsaKeyRecord;
private final JwtTokenUtils jwtTokenUtils;
private final RefreshTokenRepository refreshTokenRepository;
private final UserLogoutHandler logoutHandlerService;
private final UserInfoService userInfoService;
private final GoogleOAuth2Service googleOAuth2Service;
@Bean
@Order(1)
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.securityMatcher(new AntPathRequestMatcher("/ping/**"))
.csrf(AbstractHttpConfigurer::disable)
.cors(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(registry -> {
registry.requestMatchers(new AntPathRequestMatcher("/ping/**")).permitAll();
registry.anyRequest().permitAll();
})
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.httpBasic(withDefaults())
.build();
}
@Bean
@Order(2)
public SecurityFilterChain signInSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.securityMatcher(new AntPathRequestMatcher(ApiEndPoint.SecurePaths.SIGN_IN))
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.userDetailsService(userInfoService)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(ex -> ex.authenticationEntryPoint((request, response, authException) ->
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage())))
.httpBasic(withDefaults())
.build();
}
@Bean
@Order(3)
public SecurityFilterChain apiSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.securityMatcher(new AntPathRequestMatcher(ApiEndPoint.SecurePaths.API))
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults()))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(new JwtAccessTokenFilter(rsaKeyRecord, jwtTokenUtils), UsernamePasswordAuthenticationFilter.class)
.exceptionHandling(ex -> {
log.error("SecurityConfig :: apiSecurityFilterChain Exception due to :{}", ex);
ex.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint());
ex.accessDeniedHandler(new BearerTokenAccessDeniedHandler());
})
.httpBasic(withDefaults())
.build();
}
@Bean
@Order(4)
public SecurityFilterChain refreshTokenSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.securityMatcher(new AntPathRequestMatcher(ApiEndPoint.SecurePaths.REFRESH_TOKEN))
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults()))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(new JwtRefreshTokenFilter(rsaKeyRecord, jwtTokenUtils, refreshTokenRepository), UsernamePasswordAuthenticationFilter.class)
.exceptionHandling(ex -> {
log.error("SecurityConfig :: refreshTokenSecurityFilterChain Exception due to :{}", ex);
ex.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint());
ex.accessDeniedHandler(new BearerTokenAccessDeniedHandler());
})
.httpBasic(withDefaults())
.build();
}
@Bean
@Order(5)
public SecurityFilterChain logoutSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.securityMatcher(new AntPathRequestMatcher(ApiEndPoint.SecurePaths.LOGOUT))
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults()))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(new JwtAccessTokenFilter(rsaKeyRecord, jwtTokenUtils), UsernamePasswordAuthenticationFilter.class)
.logout(logout -> logout
.logoutUrl("/logout")
.addLogoutHandler(logoutHandlerService)
.logoutSuccessHandler(((request, response, authentication) -> SecurityContextHolder.clearContext()))
)
.exceptionHandling(ex -> {
log.error("SecurityConfig :: logoutSecurityFilterChain Exception due to :{}", ex);
ex.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint());
ex.accessDeniedHandler(new BearerTokenAccessDeniedHandler());
})
.httpBasic(withDefaults())
.build();
}
@Bean
@Order(6)
public SecurityFilterChain registerSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.securityMatcher(new AntPathRequestMatcher(ApiEndPoint.SecurePaths.SIGN_UP))
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth ->
auth.anyRequest().permitAll())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.build();
}
@Order(7)
@Bean
public SecurityFilterChain googleOAuth2SecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.securityMatcher(new AntPathRequestMatcher("/oauth2/**"))
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/oauth2/**", "/login/oauth2/**", "/login").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(oauth2 -> oauth2
.loginPage("/login")
.defaultSuccessUrl("/dashboard", true)
.failureUrl("/login?error=true")
.userInfoEndpoint(userInfo -> userInfo.userService(googleOAuth2Service))
.successHandler((request, response, authentication) -> {
DefaultOAuth2User oauth2User = (DefaultOAuth2User) authentication.getPrincipal();
String token = oauth2User.getAttribute("token");
response.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token);
})
)
.exceptionHandling(ex -> ex
.authenticationEntryPoint(new CustomOAuth2AuthenticationEntryPoint())
.accessDeniedHandler(new CustomAccessDeniedHandler())
)
.logout(logout -> logout
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout=true")
.addLogoutHandler(logoutHandlerService)
)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.build();
}
}
Определите проблему в этом файле.
Подробнее здесь:
https://stackoverflow.com/questions/790 ... g-security
1727485807
Anonymous
Я использую Spring Security для базового входа и знака oauth2 в своем приложении Spring Boot. Я просто делюсь всеми цепочками фильтров безопасности. Я также создал все остальные необходимые компоненты, такие как BCrypt, JwtDecoder и JwtEncoder. Все необходимые аннотации также присутствуют. Также укажите на любую другую ошибку, которую вы заметили. Вот мой файл SecurityConfig: [code]public class SecurityConfig { private final RSAKeyRecord rsaKeyRecord; private final JwtTokenUtils jwtTokenUtils; private final RefreshTokenRepository refreshTokenRepository; private final UserLogoutHandler logoutHandlerService; private final UserInfoService userInfoService; private final GoogleOAuth2Service googleOAuth2Service; @Bean @Order(1) public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity httpSecurity) throws Exception { return httpSecurity .securityMatcher(new AntPathRequestMatcher("/ping/**")) .csrf(AbstractHttpConfigurer::disable) .cors(AbstractHttpConfigurer::disable) .authorizeHttpRequests(registry -> { registry.requestMatchers(new AntPathRequestMatcher("/ping/**")).permitAll(); registry.anyRequest().permitAll(); }) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .httpBasic(withDefaults()) .build(); } @Bean @Order(2) public SecurityFilterChain signInSecurityFilterChain(HttpSecurity httpSecurity) throws Exception { return httpSecurity .securityMatcher(new AntPathRequestMatcher(ApiEndPoint.SecurePaths.SIGN_IN)) .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .userDetailsService(userInfoService) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .exceptionHandling(ex -> ex.authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()))) .httpBasic(withDefaults()) .build(); } @Bean @Order(3) public SecurityFilterChain apiSecurityFilterChain(HttpSecurity httpSecurity) throws Exception { return httpSecurity .securityMatcher(new AntPathRequestMatcher(ApiEndPoint.SecurePaths.API)) .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults())) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .addFilterBefore(new JwtAccessTokenFilter(rsaKeyRecord, jwtTokenUtils), UsernamePasswordAuthenticationFilter.class) .exceptionHandling(ex -> { log.error("SecurityConfig :: apiSecurityFilterChain Exception due to :{}", ex); ex.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint()); ex.accessDeniedHandler(new BearerTokenAccessDeniedHandler()); }) .httpBasic(withDefaults()) .build(); } @Bean @Order(4) public SecurityFilterChain refreshTokenSecurityFilterChain(HttpSecurity httpSecurity) throws Exception { return httpSecurity .securityMatcher(new AntPathRequestMatcher(ApiEndPoint.SecurePaths.REFRESH_TOKEN)) .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults())) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .addFilterBefore(new JwtRefreshTokenFilter(rsaKeyRecord, jwtTokenUtils, refreshTokenRepository), UsernamePasswordAuthenticationFilter.class) .exceptionHandling(ex -> { log.error("SecurityConfig :: refreshTokenSecurityFilterChain Exception due to :{}", ex); ex.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint()); ex.accessDeniedHandler(new BearerTokenAccessDeniedHandler()); }) .httpBasic(withDefaults()) .build(); } @Bean @Order(5) public SecurityFilterChain logoutSecurityFilterChain(HttpSecurity httpSecurity) throws Exception { return httpSecurity .securityMatcher(new AntPathRequestMatcher(ApiEndPoint.SecurePaths.LOGOUT)) .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults())) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .addFilterBefore(new JwtAccessTokenFilter(rsaKeyRecord, jwtTokenUtils), UsernamePasswordAuthenticationFilter.class) .logout(logout -> logout .logoutUrl("/logout") .addLogoutHandler(logoutHandlerService) .logoutSuccessHandler(((request, response, authentication) -> SecurityContextHolder.clearContext())) ) .exceptionHandling(ex -> { log.error("SecurityConfig :: logoutSecurityFilterChain Exception due to :{}", ex); ex.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint()); ex.accessDeniedHandler(new BearerTokenAccessDeniedHandler()); }) .httpBasic(withDefaults()) .build(); } @Bean @Order(6) public SecurityFilterChain registerSecurityFilterChain(HttpSecurity httpSecurity) throws Exception { return httpSecurity .securityMatcher(new AntPathRequestMatcher(ApiEndPoint.SecurePaths.SIGN_UP)) .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(auth -> auth.anyRequest().permitAll()) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .build(); } @Order(7) @Bean public SecurityFilterChain googleOAuth2SecurityFilterChain(HttpSecurity httpSecurity) throws Exception { return httpSecurity .securityMatcher(new AntPathRequestMatcher("/oauth2/**")) .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(auth -> auth .requestMatchers("/oauth2/**", "/login/oauth2/**", "/login").permitAll() .anyRequest().authenticated() ) .oauth2Login(oauth2 -> oauth2 .loginPage("/login") .defaultSuccessUrl("/dashboard", true) .failureUrl("/login?error=true") .userInfoEndpoint(userInfo -> userInfo.userService(googleOAuth2Service)) .successHandler((request, response, authentication) -> { DefaultOAuth2User oauth2User = (DefaultOAuth2User) authentication.getPrincipal(); String token = oauth2User.getAttribute("token"); response.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token); }) ) .exceptionHandling(ex -> ex .authenticationEntryPoint(new CustomOAuth2AuthenticationEntryPoint()) .accessDeniedHandler(new CustomAccessDeniedHandler()) ) .logout(logout -> logout .logoutUrl("/logout") .logoutSuccessUrl("/login?logout=true") .addLogoutHandler(logoutHandlerService) ) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .build(); } } [/code] Определите проблему в этом файле. Подробнее здесь: [url]https://stackoverflow.com/questions/79033275/ping-controller-inaccessible-in-spring-security[/url]