Логика выхода не работает с базовой аутентификацией

Это мой код выхода. Он перенаправляется на logout.done, но если я снова зайду на hello, я все равно смогу получить к нему доступ.

public void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().anyRequest().authenticated().antMatchers(HttpMethod.GET, "/hello/**").hasRole("user")
    .and()
    .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
    .logoutSuccessUrl("/logout.done").deleteCookies("JSESSIONID")
    .invalidateHttpSession(true);
}

Что здесь не так?

вы пробовали добавить clearAuthentication(true)? сразу после .logout() можно добавить лайк ..logout().clearAuthentication(true)..

Amit Naik 29.05.2019 11:58

Обычная аутентификация и выход из системы не работают. Как только вы выйдете из системы, вы снова войдете в систему, поскольку клиент, вероятно, снова отправит основной заголовок. Если вы используете js-клиент, убедитесь, что основной заголовок аутентификации также находится на клиенте.

M. Deinum 29.05.2019 13:58
1
2
44
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Добавить безопасность Spring и специальный контроллер

public void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().anyRequest().authenticated().antMatchers(HttpMethod.GET, "/hello/**").hasRole("user")
    .and()
    .logout()
    .logoutSuccessUrl("/login?logout").invalidateHttpSession(true).deleteCookies("JSESSIONID");
}

    @RequestMapping(value = { "/", "/login" }, method = RequestMethod.GET)
public ModelAndView adminLogin(Model model,@RequestParam(value = "error", required = false) String error,
        @RequestParam(value = "logout", required = false) String logout, 
        @RequestParam(value = "expired", required = false) String expired,
        @RequestParam(value = "accessdenied", required = false) String accessdenied,
        HttpServletRequest request, HttpServletResponse response) {
    if (logout != null) {
        logger.info("logout application");
        SecurityContextHolder.getContext().setAuthentication(null);
        SecurityContextHolder.clearContext();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null){   
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        HttpSession session = request.getSession(false);
        Enumeration<?> e = session.getAttributeNames();
        while (e.hasMoreElements()) {
            String attr = (String) e.nextElement();
            session.setAttribute(attr, null);
        }
        if (session != null) {
            session.removeAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
            session.invalidate();
        }
        for (javax.servlet.http.Cookie cookie : request.getCookies()) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            cookie.setPath("/");
        }
        model.addAttribute(MESSAGE, "You have been logged out successfully.");
        model.addAttribute(SUCCESSMSG, true);
    }

    final ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("adminLogin", new AdminLogin());
    modelAndView.setViewName("login");
    return modelAndView;

}

Я не думаю, что есть необходимость указывать контроллер, поскольку выход из системы уже реализован в весенней безопасности. Поправьте меня если я ошибаюсь.

Hakunamatatatata 29.05.2019 12:15

да, я упомянул весеннюю безопасность и вручную, как выйти из системы и очистить сеанс, файлы cookie и т. д.

siddheshwaran muthusamy 30.05.2019 09:14
Ответ принят как подходящий

Этот код работал для меня:

public void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().anyRequest().authenticated().antMatchers(HttpMethod.GET, "/hello/**").hasRole("user").and().formLogin().and()
    .httpBasic()
    .and()
    .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
    .logoutSuccessUrl("/logout.done").deleteCookies("JSESSIONID")
    .invalidateHttpSession(true).clearAuthentication(true);
}

Другие вопросы по теме

Как добавить один и тот же параметр для нескольких идентичных страниц входа, если аутентификация не удалась?
Как сделать для авторизации конечных точек для анонимного пользователя с помощью весенней безопасности
Почему я не могу отключить автоматически сгенерированный пароль и пользователя весенней загрузки?
Сохраняйте имя пользователя в базе данных при выполнении вызовов API для отдыха или мыла из приложения A в приложение B в Java Spring 4
Как выйти из системы с запросом GET в SpringBoot WebFlux
LDAP: получение пользовательских значений во время события аутентификации
Инициализировать репозитории, защищенные аутентификацией Spring
Нужно ли помещать исходные учетные данные в UsernamePasswordAuthenticationToken после успешной аутентификации в AuthenticationProvider?
«AlreadyBuiltException: этот объект уже был построен» при построении «springSecurityFilterChain»
Spring Boot не возвращает имя пользователя с помощью CustomAuthenticationProvider