[英]How To Implement Rest Full Web Service with Auth Token using Spring Security 4.0.1.RELEASE
我正在嘗試使用RESTful webservice設計API Manager。 在Spring的新版本中,我們可以在不使用web.xml
和securityconfig.xml
情況下將Java代碼中的所有內容組合在一起。 根據Authtoken概念,API管理器應具有authtoken和刷新令牌以進行用戶身份驗證。 請問,任何人都可以給我示例源代碼或指導如何使用Spring Security實現RESTfull webservice。
本教程說出正確的方法來做到這一點。
http://www.beingjavaguys.com/2014/10/spring-security-oauth2-integration.html
但是Spring Configuration在Spring.xml文件中。
我還需要將它們放入Java級別。
Stormpath的人們有一個非常直接的解決方案來實現Oauth。 請查看使用Stormpath進行API身份驗證 。
總之,您的解決方案將如下所示:
當用戶按下登錄按鈕時,您的前端將通過其REST API將憑據安全地發送到后端。
2.1。 順便說一句,Stormpath極大地增強了這里的所有可能性。 您可以通過其IDSite將登錄/注冊功能完全委托給Stormpath ,也可以將其委托給Servlet插件 ,而不是擁有自己的登錄頁面。 Stormpath還支持Google,Facebook,LinkedIn和Github登錄。
然后,您的后端將嘗試針對Stormpath后端對用戶進行身份驗證,並將返回access token
:
/** This code will throw an Exception if the authentication fails */ public void postOAuthToken(HttpServletRequest request, HttpServletResponse response) { Application application = client.getResource(applicationRestUrl, Application.class); //Getting the authentication result AccessTokenResult result = (AccessTokenResult) application.authenticateApiRequest(request); //Here you can get all the user data stored in Stormpath Account account = accessTokenResult.getAccount(); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/json"); //Return the Access Token response.getWriter().print(token.toJson()); response.getWriter().flush(); }
然后,對於每個經過身份驗證的請求,您的后端將執行以下操作:
/** This is your protected API */ public void sayHello(HttpServletRequest request, HttpServletResponse response) { Application application = client.getResource(applicationRestUrl, Application.class); OauthAuthenticationResult result = (OauthAuthenticationResult) application.authenticateOauthRequest(request).execute(); System.out.println(result.getApiKey()); System.out.println(result.getAccount()); //At this point the authorization was successful, you can now allow the actual operation to be executed doSayHello(); }
所有這些都不需要任何特殊的Spring Security配置,這是可以在任何框架中運行的普通Java代碼。
請查看此處了解更多信息。
希望有所幫助!
免責聲明,我是Stormpath的積極貢獻者。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.