AngularJS 的 Spring 安全性 - 注销时出现 404 [英] Spring security with AngularJS - 404 on logout

查看:26
本文介绍了AngularJS 的 Spring 安全性 - 注销时出现 404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究如何使用 Spring Boot、Spring Security 和 AngularJS 编写简单的单页应用程序的教程:

为什么要获取?我执行了POST.为什么是/login?logout",而不是/logout"?以下是用户单击注销按钮时调用的代码:

$scope.logout = function() {$http.post('logout', {}).success(function() {$rootScope.authenticated = false;$location.path("/");}).错误(函数(数据){console.log("注销失败")$rootScope.authenticated = false;});}

弹簧代码:

@SpringBootApplication@RestController公共类 UiApplication {@RequestMapping("/用户")公共主体用户(主体用户){返回用户;}@RequestMapping("/资源")公共地图<字符串,对象>家() {映射<字符串,对象>模型 = new HashMap();model.put("id", UUID.randomUUID().toString());model.put("content", "Hello World");退货模式;}公共静态无效主(字符串 [] args){SpringApplication.run(UiApplication.class, args);}@配置@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)受保护的静态类 SecurityConfiguration 扩展了 WebSecurityConfigurerAdapter {@覆盖protected void configure(HttpSecurity http) 抛出异常 {http.httpBasic().and().authorizeRequests().antMatchers("/index.html", "/home.html", "/login.html", "/").permitAll().anyRequest().authenticated().and().csrf().csrfTokenRepository(csrfTokenRepository()).and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);}私人过滤器 csrfHeaderFilter() {返回新的 OncePerRequestFilter() {@覆盖protected void doFilterInternal(HttpServletRequest 请求,HttpServletResponse 响应,FilterChain filterChain)抛出 ServletException,IOException {CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());如果(CSRF!=空){Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");String token = csrf.getToken();if (cookie == null || token != null&&!token.equals(cookie.getValue())) {cookie = new Cookie("XSRF-TOKEN", token);cookie.setPath("/");response.addCookie(cookie);}}filterChain.doFilter(请求,响应);}};}私人 CsrfTokenRepository csrfTokenRepository() {HttpSessionCsrfTokenRepository 存储库 = 新的 HttpSessionCsrfTokenRepository();repository.setHeaderName("X-XSRF-TOKEN");返回存储库;}}}

完整的 AngularJS 代码:

angular.module('hello', [ 'ngRoute' ]).config(function($routeProvider, $httpProvider) {$routeProvider.when('/', {templateUrl : 'home.html', 控制器: 'home' }).when('/login', { templateUrl : 'login.html', 控制器: '导航' }).除此以外('/');$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';}).controller('导航',功能($rootScope,$scope,$http,$location,$route){$scope.tab = 函数(路由){返回 $route.current &&路线 === $route.current.controller;};var 认证 = 函数(凭据,回调){var 标头 = 凭据?{授权:基本"+ btoa(credentials.username + ":"+ 凭据.密码)} : {};$http.get('用户', {标题:标题}).成功(功能(数据){如果(数据名称){$rootScope.authenticated = true;} 别的 {$rootScope.authenticated = false;}回调&&回调($rootScope.authenticated);}).错误(函数(){$rootScope.authenticated = false;回调&&回调(假);});}认证();$scope.credentials = {};$scope.login = function() {认证($scope.credentials,功能(认证){如果(经过身份验证){console.log("登录成功")$location.path("/");$scope.error = false;$rootScope.authenticated = true;} 别的 {console.log("登录失败")$location.path("/登录");$scope.error = true;$rootScope.authenticated = false;}})};$scope.logout = function() {$http.post('logout', {}).success(function() {$rootScope.authenticated = false;$location.path("/");}).错误(函数(数据){console.log("注销失败")$rootScope.authenticated = false;});}}).controller('home', function($scope, $http) {$http.get('/resource/').success(function(data) {$scope.greeting = 数据;}) });

我是 Spring 的新手.这是教程中的整个代码 - 也不起作用:https://github.com/dsyer/spring-security-angular/tree/主/单

解决方案

其实你需要的只是添加一个注销成功处理程序

@Component公共类 LogoutSuccess 实现 LogoutSuccessHandler {@覆盖public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication)抛出 IOException,ServletException {如果(身份验证!= null && authentication.getDetails() != null){尝试 {httpServletRequest.getSession().invalidate();//用户成功登录后可以在此处添加更多代码//出去,//例如更新数据库的最后一个活动.} 捕获(异常 e){e.printStackTrace();e = 空;}}httpServletResponse.setStatus(HttpServletResponse.SC_OK);}}

并向您的安全配置添加一个成功处理程序

http.authorizeRequests().anyRequest().authenticated().and().logout().logoutSuccessHandler(logoutSuccess).deleteCookies("JSESSIONID").invalidateHttpSession(false).permitAll();

I'm working with tutorial that describes how to write simple single-page app using Spring Boot, Spring Security and AngularJS: https://spring.io/guides/tutorials/spring-security-and-angular-js/

I cannot logout currently logged user - when I perform POST request to "/logout", I get "404 not found" - screen from Google Chrome debugger:

Why GET? I performed POST. Why "/login?logout", not "/logout"? Here is the code that is invoked when user clicks logout button:

$scope.logout = function() {
            $http.post('logout', {}).success(function() {
                $rootScope.authenticated = false;
                $location.path("/");
            }).error(function(data) {
                console.log("Logout failed")
                $rootScope.authenticated = false;
            });
        }

Spring code:

@SpringBootApplication
@RestController
public class UiApplication {

    @RequestMapping("/user")
    public Principal user(Principal user) {
        return user;
    }

    @RequestMapping("/resource")
    public Map<String, Object> home() {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("id", UUID.randomUUID().toString());
        model.put("content", "Hello World");
        return model;
    }

    public static void main(String[] args) {
        SpringApplication.run(UiApplication.class, args);
    }

    @Configuration
    @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
    protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.httpBasic().and().authorizeRequests()
                    .antMatchers("/index.html", "/home.html", "/login.html", "/").permitAll().anyRequest()
                    .authenticated().and().csrf()
                    .csrfTokenRepository(csrfTokenRepository()).and()
                    .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
        }

        private Filter csrfHeaderFilter() {
            return new OncePerRequestFilter() {
                @Override
                protected void doFilterInternal(HttpServletRequest request,
                        HttpServletResponse response, FilterChain filterChain)
                        throws ServletException, IOException {
                    CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
                            .getName());
                    if (csrf != null) {
                        Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                        String token = csrf.getToken();
                        if (cookie == null || token != null
                                && !token.equals(cookie.getValue())) {
                            cookie = new Cookie("XSRF-TOKEN", token);
                            cookie.setPath("/");
                            response.addCookie(cookie);
                        }
                    }
                    filterChain.doFilter(request, response);
                }
            };
        }

        private CsrfTokenRepository csrfTokenRepository() {
            HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
            repository.setHeaderName("X-XSRF-TOKEN");
            return repository;
        }
    }

}

Whole AngularJS code:

angular.module('hello', [ 'ngRoute' ]).config(function($routeProvider, $httpProvider) {

    $routeProvider
.when('/', {templateUrl : 'home.html', controller : 'home'  })
.when('/login', { templateUrl : 'login.html',   controller : 'navigation'   })
.otherwise('/');

    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

}).controller('navigation',

        function($rootScope, $scope, $http, $location, $route) {

            $scope.tab = function(route) {
                return $route.current && route === $route.current.controller;
           };

            var authenticate = function(credentials, callback) {

                var headers = credentials ? {
                    authorization : "Basic "
                            + btoa(credentials.username + ":"
                                    + credentials.password)
                } : {};

                $http.get('user', {
                    headers : headers
                }).success(function(data) {
                    if (data.name) {
                        $rootScope.authenticated = true;
                    } else {
                        $rootScope.authenticated = false;
                    }
                    callback && callback($rootScope.authenticated);
                }).error(function() {
                    $rootScope.authenticated = false;
                    callback && callback(false);
                });

            }

            authenticate();
            $scope.credentials = {};            
            $scope.login = function() {
                authenticate($scope.credentials, function(authenticated) {
                    if (authenticated) {
                        console.log("Login succeeded")
                        $location.path("/");
                        $scope.error = false;
                        $rootScope.authenticated = true;
                    } else {
                        console.log("Login failed")
                        $location.path("/login");
                        $scope.error = true;
                        $rootScope.authenticated = false;
                    }
                })          
            };

            $scope.logout = function() {
                $http.post('logout', {}).success(function() {
                    $rootScope.authenticated = false;
                    $location.path("/");
                }).error(function(data) {
                    console.log("Logout failed")
                    $rootScope.authenticated = false;
                });         
            }

        }).controller('home', function($scope, $http) { 
           $http.get('/resource/').success(function(data) {         
               $scope.greeting = data; }) });

I'm new to Spring. Here is the whole code from tutorial - doesn't work too: https://github.com/dsyer/spring-security-angular/tree/master/single

解决方案

In fact what you need is just to add a logout success handler

@Component
public class LogoutSuccess implements LogoutSuccessHandler {

@Override
public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication)
        throws IOException, ServletException {
    if (authentication != null && authentication.getDetails() != null) {
        try {
            httpServletRequest.getSession().invalidate();
            // you can add more codes here when the user successfully logs
            // out,
            // such as updating the database for last active.
        } catch (Exception e) {
            e.printStackTrace();
            e = null;
        }
    }

    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

}

}

and add a success handler to your security config

http.authorizeRequests().anyRequest().authenticated().and().logout().logoutSuccessHandler(logoutSuccess).deleteCookies("JSESSIONID").invalidateHttpSession(false).permitAll();

这篇关于AngularJS 的 Spring 安全性 - 注销时出现 404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆