【发布时间】:2015-05-31 20:03:13
【问题描述】:
我想为我的应用程序实施本地用户管理。对于后端,我使用 java spring REST。我不使用像 Auth0 或 UserApp 这样的云用户管理服务。由于某些功能,我想使用JWT 方法进行用户身份验证和授权,但是我不知道应该如何在 Java 和 AngularJS 中实现它?
【问题讨论】:
我想为我的应用程序实施本地用户管理。对于后端,我使用 java spring REST。我不使用像 Auth0 或 UserApp 这样的云用户管理服务。由于某些功能,我想使用JWT 方法进行用户身份验证和授权,但是我不知道应该如何在 Java 和 AngularJS 中实现它?
【问题讨论】:
我讨论了如何将 JWT 身份验证添加到 AngularJS 应用程序。
你可以在这里看到它:https://www.youtube.com/watch?v=lDb_GANDR8U
该演示文稿的代码在这里:https://github.com/auth0/angularjs-jwt-authentication-tutorial
在该示例中,服务器是 NodeJS。如果你需要 Java,你可以做类似https://github.com/auth0/spring-security-auth0/tree/master/examples/spring-boot-api-example 的事情。该示例适用于 Auth0,但 JWT 验证也适用于您的案例 :),因为它是通用的。
如果这有帮助,请告诉我。
干杯!
【讨论】:
试试satellizer。它们在示例文件夹中提供 Java 服务器实现。 检查一下
【讨论】:
虽然这看起来很复杂,但看看Stormpath 对您来说非常有用。我们有一个非常简单的解决方案。请查看Using Stormpath for API Authentication。
总而言之,您的解决方案将如下所示:
当用户按下登录按钮时,您的前端将通过其 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();
}
然后,对于每个经过身份验证的请求,您的后端都会这样做:
public void getEquipment(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
handleEquipmentRequest(response);
}
请查看here了解更多信息
希望有帮助!
免责声明,我是 Stormpath 的活跃贡献者。
【讨论】: