2016-10-04 99 views
1

Angular2啓用了Spring安全性。Angular2如何使用彈簧安全登錄並進行其他安全調用

我沒有得到關於以下問題的很多信息,我非常感謝任何幫助。

使用angular2我試圖讓http獲得調用來休息api,它需要首先使用spring安全登錄,然後訪問休息api。

我使用lite-server在jboss eap和angular2 web項目下運行resp應用程序。

彈簧配置如下訪問資源

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) 

} 
+0

問題是您的登錄系統重定向到登錄頁面,並且您使用的會話cookie在REST(無狀態api)中無效。您應該配置您的spring-security以從請求(頭文件)中獲取密鑰並使用此密鑰來檢查身份驗證。見http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/#ch_3_3 – Supamiu

+0

我感謝你的幫助,你可以發佈它作爲ans我會接受 –

回答

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); 
    } 
}) 

你告訴彈簧要進行身份驗證,您必須將用戶重定向到登錄頁面,這不可能使用API​​調用(只有一個r eQUEST的)。

此外,您必須刪除會話cookie的使用,因爲根據定義,REST是無狀態的。

您必須基於每個請求提供的令牌實施無狀態身份驗證。一個很好的教程可以在here找到,但是如果你尋找spring rest api的無狀態身份驗證,你仍然可以找到更多的教程。

+0

我已經結合了angular2代碼和寧靜的項目。在其餘項目web-apps文件夾中放置角碼配置和代碼。在intellij中打開打字稿觀察器和更新代碼熱插拔就像魅力一樣。我只是想爲開發環境做點什麼 –