使用 angularjs 登录的离子身份验证

Ionic authentication for login with angularjs

由于 ionic 使用 angularjs,对于登录系统,没有任何浏览器可以保存 cookie 或会话以便对应用程序的每个部分进行身份验证。 一种方法是在 app.js:

中使用它来保护
$urlRouterProvider.otherwise('/login');

因为任何人都无法访问应用程序中的其他链接。当服务器(mysql 数据库)返回的答案是 true 时,我们可以使用:

$state.go('app.main');

这是个好主意吗?或者其他方式?

对于我们公司的应用程序,我们使用摘要式访问身份验证(https://en.wikipedia.org/wiki/Digest_access_authentication) with our ionic app and our node server that is hooked up to a sql database. Once the user is authenticated we send them a jwt (javascript web token). We can then store that webtoken locally (if they check the option for auto login) or they can re-authenticate whenever the app is reopened and we give them another web token. This has so far proven to be a safe and efficient method of user authentication. Here is a tutorial for using json web tokens and angular. http://www.toptal.com/web/cookie-free-authentication-with-json-web-tokens-an-example-in-laravel-and-angularjs

由于 ionic 本质上是调用后端 api,您可以实施任何标准 api 身份验证机制。

最常见的是基于令牌的身份验证,高级工作流程如下

1 - ionic 应用程序调用后端服务器端点并获取令牌(通过传递某种加密密钥)

2 - 后端服务器生成令牌(适合给定时间段)并发送回 ionic 应用程序。

3 - 此后,在每个请求中 ionic 发送令牌。 (最好在请求中 header)

要临时保存令牌,您可以使用简单的存储解决方案,例如 ng-storage or sqlite

有一个read here

我强烈建议您查看 John Papa 的 ng-demoes, especially one with JWT token,因为这是您现在想要使用的。 (这些不是特定于 ionic,而是一般 angular.js 应用程序)

基本上你有几件事需要做:

  • 处理所有需要检查用户是否已通过身份验证的地方并发出 unauthorized 事件

  • 处理事件并重定向到登录 state/route

在上面的示例中,您基本上添加了拦截器 (https://github.com/johnpapa/ng-demos/blob/master/ng-jwt/src/client/app/services/authInterceptor.js),它会查看是否有任何对 Web 服务的请求因 not authorized 而失败,并拒绝 $http 请求

返回的承诺

还有

As ionic uses angularjs, for login system there isn't any browser to save cookie or session in order to authenticate for each part of application.

您确实可以使用 localStorage/sessionStorage 来存储令牌并将该令牌添加到所有请求。这就是为什么您最好为 Web 服务使用基于令牌的身份验证,而不是基于 cookie 的身份验证。 (basic auth可以做,只是比较麻烦)