Angular2如何使用spring security登录并进行rest api调用

时间:2016-10-04 14:00:00

标签: spring-mvc angular spring-security

启用Angular2 Spring安全性。

我没有获得有关以下问题的更多信息,我感谢任何帮助。

使用angular2我试图让http调用rest api,这需要首先使用spring security登录,然后访问rest api。

我正在使用lite-server在jboss eap和angular2 web项目下运行resp app。

spring配置如下以访问资源

context.setSessionTrackingModes(singleton(COOKIE));
context.getSessionCookieConfig().setHttpOnly(true);

context.addFilter("springSecurity", new DelegatingFilterProxy("springSecurityFilterChain"))
    .addMappingForUrlPatterns(null, false, "/*");

    context.addServlet("login", new HttpServlet() {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String loginPage = "login.html";
        String query = request.getQueryString();
        response.sendRedirect(query != null ? loginPage + '?' + query : loginPage);
    }
}).addMapping("/login");

这是我的angular2 api电话,我正在

XMLHttpRequest cannot load http://localhost:8080/abc/api/menu. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

getItems():Promise<Item>{
    return this.http.get('http://localhost:8080/abc/api/menu').toPromise().
    then(response => response.json() as Menu).catch(this.handleError)

}

1 个答案:

答案 0 :(得分:1)

当你这样做时

context.addServlet("login", new HttpServlet() {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String loginPage = "login.html";
        String query = request.getQueryString();
        response.sendRedirect(query != null ? loginPage + '?' + query : loginPage);
    }
})

你告诉spring要进行身份验证,你必须将用户重定向到登录页面,而且这不可能使用API​​调用(只有一个请求)。

此外,您必须删除会话cookie的使用,因为根据定义,REST是无状态的。

您必须基于每个请求提供的令牌实现无状态身份验证。可以找到一个很好的教程here但是如果你为spring rest api寻找无状态身份验证,你仍然可以找到更多。