У меня есть аутентифицированный класс, который расширяет org.springframework.security.core.userdetails.user. Он построен из jwt. < /P>
Каждый запрос из браузера имеет JWT, прикрепленный к запросу. Страницы либо защищены, либо публики. Если страница защищена, мой @AuthenticationPrincipal AuthenticatedUser Принципал заполняется, но если страница не защищена, моя @AuthenticationPrincipal AuthenticatedUser Principal не заполнена. И проблема возникает здесь. Теперь у меня есть случай, когда я хочу получить @AuthenticationPrincipal AuthenticatedUser Principal , даже если страница не защищена. Но теперь на незащищенных страницах мой @AuthenticationPrincipal AuthenticatedUser Принципал кажется нулевым, хотя я отправляю jwt.
@Configuration
@EnableWebSecurity
public class ResourceServerConfig {
private final List protectedPaths = List.of(
"/secret/*/**",
"/private"
);
// here if I add the public into the list principal is populated but the anon users cannot access the public link. If I don't add the public link then principal appears to be null.
@Bean
@Order(2)
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.securityMatchers(customizer -> customizer.requestMatchers(protectedPaths.toArray(new String[0])))
.csrf().disable()
.authorizeHttpRequests(requests -> requests.anyRequest().authenticated())
.oauth2ResourceServer()
.jwt(customizer -> customizer.jwtAuthenticationConverter(new UserAuthenticationTokenConverter()));
return http.build();
}
}
< /code>
и мой контроллер: < /p>
@GetMapping(path = "/public/{id}")
public ListingDetailedView
findById(@PathVariable String id, @AuthenticationPrincipal AuthenticatedUser principal) {
// here principal is null
return listingService.findBySearchId(id, principal);
}
< /code>
Как я могу заполнить принципал на не защищенных страницах? < /p>
@Configuration
@RequiredArgsConstructor
public class PartnerResourceServerConfig {
private final PartnerUserDetailsService userDetailsService;
private final AuthenticationFailureHandler failureHandler;
@Bean
@Order(1)
public SecurityFilterChain partnerSecurityFilterChain(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
authManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
var authenticationManager = authManagerBuilder.build();
http.securityMatcher("/hidden/**")
.authorizeHttpRequests(customizer -> customizer.anyRequest().authenticated())
.authenticationManager(authenticationManager)
.addFilterBefore(partnerApiKeyAuthenticationFilter(authenticationManager), UsernamePasswordAuthenticationFilter.class)
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(sessionManagementCustomizer -> sessionManagementCustomizer
.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
PartnerApiKeyAuthenticationFilter partnerApiKeyAuthenticationFilter(AuthenticationManager authenticationManager) {
var filter = new PartnerApiKeyAuthenticationFilter("/hidden/**");
filter.setAuthenticationFailureHandler(failureHandler);
filter.setAuthenticationManager(authenticationManager);
return filter;
}
}
Подробнее здесь: https://stackoverflow.com/questions/794 ... ected-urls
Как получить идентификатор пользователя от незащищенных URL -адресов? ⇐ JAVA
Программисты JAVA общаются здесь
1738349648
Anonymous
У меня есть аутентифицированный класс, который расширяет org.springframework.security.core.userdetails.user. Он построен из jwt. < /P>
Каждый запрос из браузера имеет JWT, прикрепленный к запросу. Страницы либо защищены, либо публики. Если страница защищена, мой @AuthenticationPrincipal AuthenticatedUser Принципал заполняется, но если страница не защищена, моя @AuthenticationPrincipal AuthenticatedUser Principal не заполнена. И проблема возникает здесь. Теперь у меня есть случай, когда я хочу получить @AuthenticationPrincipal AuthenticatedUser Principal , даже если страница не защищена. Но теперь на незащищенных страницах мой @AuthenticationPrincipal AuthenticatedUser Принципал кажется нулевым, хотя я отправляю jwt.
@Configuration
@EnableWebSecurity
public class ResourceServerConfig {
private final List protectedPaths = List.of(
"/secret/*/**",
"/private"
);
// here if I add the public into the list principal is populated but the anon users cannot access the public link. If I don't add the public link then principal appears to be null.
@Bean
@Order(2)
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.securityMatchers(customizer -> customizer.requestMatchers(protectedPaths.toArray(new String[0])))
.csrf().disable()
.authorizeHttpRequests(requests -> requests.anyRequest().authenticated())
.oauth2ResourceServer()
.jwt(customizer -> customizer.jwtAuthenticationConverter(new UserAuthenticationTokenConverter()));
return http.build();
}
}
< /code>
и мой контроллер: < /p>
@GetMapping(path = "/public/{id}")
public ListingDetailedView
findById(@PathVariable String id, @AuthenticationPrincipal AuthenticatedUser principal) {
// here principal is null
return listingService.findBySearchId(id, principal);
}
< /code>
Как я могу заполнить принципал на не защищенных страницах? < /p>
@Configuration
@RequiredArgsConstructor
public class PartnerResourceServerConfig {
private final PartnerUserDetailsService userDetailsService;
private final AuthenticationFailureHandler failureHandler;
@Bean
@Order(1)
public SecurityFilterChain partnerSecurityFilterChain(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
authManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
var authenticationManager = authManagerBuilder.build();
http.securityMatcher("/hidden/**")
.authorizeHttpRequests(customizer -> customizer.anyRequest().authenticated())
.authenticationManager(authenticationManager)
.addFilterBefore(partnerApiKeyAuthenticationFilter(authenticationManager), UsernamePasswordAuthenticationFilter.class)
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(sessionManagementCustomizer -> sessionManagementCustomizer
.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
PartnerApiKeyAuthenticationFilter partnerApiKeyAuthenticationFilter(AuthenticationManager authenticationManager) {
var filter = new PartnerApiKeyAuthenticationFilter("/hidden/**");
filter.setAuthenticationFailureHandler(failureHandler);
filter.setAuthenticationManager(authenticationManager);
return filter;
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79400317/how-do-i-get-user-id-from-unprotected-urls[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия