首页 文章

如何在Spring安全性登录后访问资源?

提问于
浏览
-2

我正在尝试学习Spring安全性,但我遇到了问题 .

我有一个前端项目和一个后端项目 .

前端项目在localhost:8000上使用node.js http-server

后端项目在localhost:8090上使用Spring Boot Tomcat

我只是为我的后端项目增加了 spring 安全性 .

现在的问题是我登录login.html,并重定向到index.html,但在index.html我想访问我的后端项目中的资源,但是如果我输入网址,Spring安全总是给我401错误(例如http://localhost://8090/getName),浏览器会改变,并要求我输入用户名和密码 . 完成后,我输入另一个URL(http://localhost://8090/getName2),我得到了结果指令 . 而且似乎我没有问题?

这是我的Spring配置:

@Override
protected void configure(HttpSecurity http) throws Exception{

    http
            .httpBasic()
            .and()
            .authorizeRequests()
            .anyRequest().authenticated()
        ;
}

    @Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
}

这是我的控制者

@RequestMapping("/login")
    String login(Principal principal){
        return principal.getName();
    }

这是我的前端登录页面的js,我使用angular-js

loginApp.controller('navigation', function($rootScope, $http, $location, $scope, $window) {

$scope.login = function() {
    var h = {authorization : "Basic "+ btoa($scope.credentials.username + ":" + $scope.credentials.password)                };
    $http.get('http://localhost:8090/login/',{headers : h}).then(function(response) {
        onsole.log(response.data);
        $window.location.href='/index.html'; 
    });
};
   });

1 回答

  • 0

    我终于得到了答案 . 资源是我在使用AngularJS登录后,我没有设置标志 withCredentials ,所以当我需要再次访问资源时,我只是 $http.get('http://localhost:8090/test__2/',{withCredentials: true}).then 并且它有效 .

    感谢Angularjs $http does not seem to understand "Set-Cookie" in the response .

相关问题