【问题标题】:Rest Authentication - Token validation with a database look up Vs alternativesRest Authentication - 使用数据库查找的令牌验证与替代方案
【发布时间】:2015-09-30 15:48:26
【问题描述】:
【问题讨论】:
标签:
java
rest
spring-security
token
endpoint
【解决方案1】:
您需要的可以通过Oauth解决。
您的后端 (REST-API) 将需要对您的 API 操作进行身份验证的访问权限。反过来,您的客户端/前端将需要在与后端通信时发出经过身份验证的请求。这是通过发送access tokens 来实现的。
虽然这看起来很复杂,但看看Stormpath 对您来说非常有用。我们有一个非常简单的解决方案。请查看Using Stormpath for API Authentication。
总而言之,您的解决方案将如下所示:
- 您将使用Stormpath Java SDK 轻松委派您的所有用户管理需求。
-
在您的前端,当用户按下登录按钮时,您的前端将通过其 REST API 将凭据安全地发送到您的后端。
2.1。顺便说一句,Stormpath 极大地增强了这里的所有可能性。除了拥有自己的登录页面,您还可以通过 IDSite 将登录/注册功能完全委托给 Stormpath,或者您也可以将其委托给我们的 Servlet Plugin。 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");
//Output the json of the Access Token
response.getWriter().print(token.toJson());
response.getWriter().flush();
}
-
然后,对于每个经过身份验证的请求,您的后端都会这样做:
/** This is your (now protected) exposed operation */
public void getOrder(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());
//Return what you need to return in the response
doGetOrder(request, response);
}
请查看here了解更多信息
希望有帮助!
免责声明,我是 Stormpath 的活跃贡献者。