@sltay

Как «положить» данные пользователя в Principal?

У меня есть конфигурация SpringSecurity
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // для включения аннотации PreAuthorize
@SuppressWarnings("deprecation")
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    private final UserDetailsService userDetailsService;

    @Autowired
    public SpringSecurityConfig(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder());
    }

    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests()
//                .antMatchers("/admin").hasRole("ADMIN")
                .antMatchers("/main").hasAnyRole("USER", "ADMIN") //указываем что в /main могут попасть только роли USER и ADMIN
                .antMatchers("/auth/login", "/auth/registration", "/error").permitAll() //в логин, регистарцию и ошибку могут попасть все
                .and()
                .formLogin().loginPage("/auth/login") //указываем НЕ стандартную страницу логина, а кастомную
                .loginProcessingUrl("/processor_login") // action который перенаправляет нас при попытке залогиниться
                .defaultSuccessUrl("/", true) // если авторизовался
                .failureUrl("/auth/login?error") //если нет
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/auth/login"); //адрес для логаута
    }


    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Вопрос : сейчас если я попытаюсь вытащить данные Principle
GetMapping
    public String afterRegistrationRedirect() {
        System.out.println(SecurityContextHolder.getContext().getAuthentication());
        return "auth/profilePage";
    }

я получаю
AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=null], Granted Authorities=[ROLE_ANONYMOUS]]

я так понял что авторизация пройдена успешна, но принципал заполнился специальными "анонимными" данными
Note that there is no real conceptual difference between a user who is "anonymously authenticated" and an unauthenticated user. Spring Security’s anonymous authentication just gives you a more convenient way to configure your access-control attributes.


как мне в него поместить данные авторизированного пользователя. Подскажите куда копать, заранее спасибо
  • Вопрос задан
  • 180 просмотров
Решения вопроса 1
@eldd
Вот хорошая статья: https://sysout.ru/kak-ustroena-autentifikatsiya-v-...
А так же WebSecurityConfigurerAdapter, уже депрекейтед
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
25 апр. 2024, в 09:29
2500 руб./за проект
25 апр. 2024, в 09:27
4000 руб./за проект
25 апр. 2024, в 09:20
10000 руб./за проект