@parkito

Почему spring security не выполняет своих обязятельств?

Здравствуйте. Помогите, пожалуйста, решить следующую проблему.

Пытаюсь поднять spring security

Его конфигурация

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    CustomSuccessHandler customSuccessHandler;


    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/admin/*").access("hasRole('Manager')")
                .antMatchers("/user/*").access("hasRole('userAvailable')")
                //.and().formLogin().loginPage("/login")
                .and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
                .usernameParameter("username").passwordParameter("password")
                .and().csrf()
                .and().exceptionHandling().accessDeniedPage("/404");
    }

}


Разделение по ролям

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    CustomSuccessHandler customSuccessHandler;


    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/admin/*").access("hasRole('Manager')")
                .antMatchers("/user/*").access("hasRole('userAvailable')")
                //.and().formLogin().loginPage("/login")
                .and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
                .usernameParameter("username").passwordParameter("password")
                .and().csrf()
                .and().exceptionHandling().accessDeniedPage("/404");
    }

}


Но при авторизации меня кидает на login?error, а в сервлете

@RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginPage(HttpServletRequest request, Locale locale, Model model) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(auth.getDetails());
        System.out.println(auth.getPrincipal());
        System.out.println(principal);
        return "index";


вижу anonymousUser. Что я делаю неправильно?
  • Вопрос задан
  • 726 просмотров
Пригласить эксперта
Ответы на вопрос 2
loginPage - это страница, на которую Spring Security отправляет пользователя, если нужна аутентификация. Так что вполне закономерно, что на этой странице пользователь ещё не аутентифицирован.

username и password нужно отправлять POST-запросом на loginProcessingUrl, который в данной конфигурации не задан.

Ну а перенаправление на login?error значит, что аутентификация в UserDetailsService не произошла. Копайте там.
Ответ написан
Комментировать
badprogrammist
@badprogrammist
Senior java developer
Все правильно. Вы прописали "/login" как страницу для аутентификации, закономерно что там будет anonymousUser, потому что этот метод должен рендерить страницу для аутентификации.
Ответ написан
Комментировать
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы
Bell Integrator Ульяновск
До 400 000 ₽
Bell Integrator Хабаровск
До 400 000 ₽
Bell Integrator Ижевск
До 400 000 ₽