Как выйти из клиента oauth2 в Spring? - PullRequest
0 голосов
/ 15 мая 2018

У меня самый простой клиент oauth2:

@EnableAutoConfiguration
@Configuration
@EnableOAuth2Sso
@RestController
public class ClientApplication {

    @RequestMapping("/")
    public String home(Principal user, HttpServletRequest request, HttpServletResponse response) throws ServletException {       
        return "Hello " + user.getName();
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(ClientApplication.class)
                .properties("spring.config.name=application").run(args);
    }

}

У меня также есть следующее application.yml:

server:
  port: 9999
  servlet:
    context-path: /client
security:
  oauth2:
    client:
      client-id: acme
      client-secret: acmesecret
      access-token-uri: http://localhost:8080/oauth/token
      user-authorization-uri: http://localhost:8080/oauth/authorize
    resource:
      user-info-uri: http://localhost:8080/me

logging:
  level:
    org.springframework.security: DEBUG
    org.springframework.web: DEBUG

Это полный код.У меня нет никакого дополнительного исходного кода.Он работает правильно.

Но теперь я хочу добавить функцию выхода из системы.Я добавил конечную точку, но она не работает.Я попытался сделать следующее:

@RequestMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        authentication.setAuthenticated(false);
        new SecurityContextLogoutHandler().logout(request,response,authentication);
        SecurityContextHolder.clearContext();
        request.logout();
        request.getSession().invalidate();
    }

Но я все еще вошел в систему и могу получить доступ к / url, и он отвечает мне с именем пользователя.

Можете ли вы помочь мне исправить этоПроблема?

Обновление

Я попробовал подход, описанный здесь https://spring.io/guides/tutorials/spring-boot-oauth2/#_social_login_logout:

@EnableAutoConfiguration
@Configuration
@EnableOAuth2Sso
@Controller
public class ClientApplication extends WebSecurityConfigurerAdapter {
    private Logger logger = LoggerFactory.getLogger(ClientApplication.class);

    @RequestMapping("/hello")
    public String home(Principal user, HttpServletRequest request, HttpServletResponse response, Model model) throws ServletException {
        model.addAttribute("name", user.getName());
        return "hello";
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.antMatcher("/**")
                .authorizeRequests()
                .antMatchers( "/login**", "/webjars/**", "/error**").permitAll()
                .anyRequest()
                .authenticated()
                .and().logout().logoutSuccessUrl("/").permitAll()
                .and()
                    .csrf()
                    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
        // @formatter:on
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(ClientApplication.class)
                .properties("spring.config.name=application").run(args);
    }
}

и на FE я написал:

<script type="text/javascript">
        $.ajaxSetup({
            beforeSend: function (xhr, settings) {
                if (settings.type == 'POST' || settings.type == 'PUT'
                    || settings.type == 'DELETE') {
                    if (!(/^http:.*/.test(settings.url) || /^https:.*/
                            .test(settings.url))) {
                        // Only send the token to relative URLs i.e. locally.
                        xhr.setRequestHeader("X-XSRF-TOKEN",
                            Cookies.get('XSRF-TOKEN'));
                    }
                }
            }
        });
        var logout = function () {
            $.post("/client/logout", function () {
                $("#user").html('');
                $(".unauthenticated").show();
                $(".authenticated").hide();
            });
            return true;
        };
        $(function() {
            $("#logoutButton").on("click", function () {
                logout();
            });
        });

    </script>

и

<input type="button" id="logoutButton" value="Logout"/>

Но это все равно не работает.Это приводит к следующему поведению:

Post http://localhost:9999/client/logout перенаправляет на http://localhost:9999/client, но эта страница не существует

исходный код на gitub:
клиент - https://github.com/gredwhite/logour_social-auth-client (используйте localhost:9999/client/hello url)
сервер - https://github.com/gredwhite/logout_social-auth-server

Ответы [ 4 ]

0 голосов
/ 04 января 2019

Вы можете изменить сообщение, чтобы получить http://localhost:9999/client/logout

это работает для меня

0 голосов
/ 23 мая 2018

Попробуйте добавить URL выхода из системы в вашу конфигурацию безопасности.

    .logout()
        .logoutUrl("/logout")
        .logoutSuccessUrl("/")
        .permitAll();
0 голосов
/ 24 мая 2018

Добавьте следующий фрагмент кода в ваш класс ClientApplication.Это также очистит детали вашего сеанса.

Замените приведенный ниже код методом configure класса вашего адаптера веб-безопасности.

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**")
                .authorizeRequests()
                .antMatchers( "/login**", "/webjars/**", "/error**").permitAll()
                .anyRequest()
                .authenticated()
                .and().logout().invalidateHttpSession(true)
                .clearAuthentication(true).logoutSuccessUrl("/login?logout").deleteCookies("JSESSIONID").permitAll().and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }
0 голосов
/ 22 мая 2018

Возможно, вы захотите использовать встроенную поддержку Spring Security для конечной точки / logout, которая будет делать правильные вещи (очистить сеанс и аннулировать cookie).Для настройки конечной точки расширьте существующий метод configure () в нашем WebSecurityConfigurer:

@Override
protected void configure(HttpSecurity http) throws Exception {
  http.antMatcher("/**")
     .and().logout().logoutSuccessUrl("/").permitAll();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...