简体   繁体   English

基于Angular.js + Node.js / PassportJS的SPA上的oauth2 auth

[英]oauth2 auth on SPA based on Angular.js + Node.js/PassportJS

Which is a common way to implement oauth2 auth on the angular-based single page application? 在基于角度的单页应用程序上实现oauth2 auth的常用方法是什么? Is it possible to implement it without page reload? 是否可以在不重新加载页面的情况下实现它? If not - what is a best way to transfer auth data back to angular code from the page? 如果不是,将身份验证数据从页面传回角度代码的最佳方法是什么?

The authorization server must provide an api to authenticate user and return access token without redirecting. 授权服务器必须提供一个api来认证用户并返回访问令牌而无需重定向。 I will take facebook as authorization server and resource server in this example for easier understanding. 在本示例中,为了便于理解,我将把facebook作为授权服务器和资源服务器。 The flow is like this: 流程是这样的:

  1. Your user clicks on a button on the page. 您的用户单击页面上的按钮。

  2. Since this is SPA built with angularjs, the browser sends an ajax to your server to get data. 由于这是使用angularjs构建的SPA,因此浏览器会将ajax发送到您的服务器以获取数据。

  3. On server side, you find out that this action requires data from resource server (facebook), instead of redirecting the browser to resource server as we usually do, the server sends a response with a custom status (or any information indicating that this action needs an access token) to the browser. 在服务器端,您发现此操作需要资源服务器(facebook)中的数据, 而不是像通常那样将浏览器重定向到资源服务器,而是服务器发送带有自定义状态的响应(或任何表明该操作需要的信息)访问令牌)。

  4. On browser, when you receive response from server in your ajax success callback function. 在浏览器上,当您在ajax成功回调函数中收到服务器的响应时。 You can check the response and find out that this action needs an access token 您可以检查响应并发现此操作需要访问令牌

  5. The browser first tries to get this access token from resource server (if the user is already logged in). 浏览器首先尝试从资源服务器获取此访问令牌(如果用户已经登录)。 When working with facebook using FB javascript SDK, we usually use FB.getLoginStatus function. 使用FB javascript SDK与Facebook配合使用时,我们通常使用FB.getLoginStatus函数。

    a. 一种。 If we can get the access token in the success callback (the user is already logged in), just send this access token to server to get data (using ajax). 如果我们可以在成功回调中获取访问令牌(用户已经登录),只需将此访问令牌发送到服务器以获取数据(使用Ajax)。

    b. If the user is not logged in yet, use javascript to prompt the user to login by rendering a login button and the user has to click on it. 如果用户尚未登录,请使用javascript通过呈现登录按钮来提示用户登录,而用户必须单击该按钮。 When working with facebook using FB javascript SDK, we usually use FB.login function when user clicks on the login button. 当使用FB javascript SDK与Facebook一起使用时,当用户单击登录按钮时,我们通常使用FB.login函数。 After successful login, we will receive the access token in the success callback and just send it to server to get the response (using ajax). 成功登录后,我们将在成功回调中接收访问令牌,并将其发送到服务器以获取响应(使用ajax)。

There is no page reload because all actions are done with ajax (without browser's redirects) 没有页面重新加载,因为所有操作都使用ajax完成(没有浏览器的重定向)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM