[英]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.