如何在 Javascript 中实现安全的 OAuth2 消费? [英] How do I implement secure OAuth2 consumption in Javascript?

查看:25
本文介绍了如何在 Javascript 中实现安全的 OAuth2 消费?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 PHP 设计一个将使用 OAuth2.0 的 API.我的最终目标是用 javascript(使用 AngularJS)构建一个直接访问这个 API 的前端应用程序.我知道传统上没有办法保护 javascript 中的事务,因此直接访问 API 是不可行的.前端需要与服务器代码进行通信,而服务器代码又直接与 API 进行通信.但是,在研究 OAuth2 时,似乎 User-Agent Flow 旨在帮助解决这种情况.

我需要帮助的是在 javascript 中实现 OAuth2 User-Agent Flow(如果可能,特别是 AngularJS,因为这是我在前端使用的).我一直无法找到执行此操作的任何示例或教程.我真的不知道从哪里开始,也不想通读整个 OAuth2 规范,至少没有看到我将要做什么的例子.因此,将不胜感激任何示例、教程、链接等.

解决方案

隐式授权流程(您将其称为用户-代理流程)正是要走的路:

<块引用>

隐式授权是一种简化的授权代码流,针对使用 JavaScript 等脚本语言在浏览器中实现的客户端进行了优化.

要了解流程,请参阅 Google 提供的关于客户端应用程序 是一个非常好的起点.请注意,他们建议您采取额外的令牌验证步骤以避免混淆代理问题.

以下是使用 Soundcloud API 和 jQuery 的流程的简短示例实现,摘自 这个答案:>

<风格>.隐藏{显示:无;}</风格><div class="authenticate hidden"><一个类=连接"href="">Connect</a>

<div class="经过身份验证的隐藏"><p>您正在使用令牌<span class="token">[无标记]</span>.</p><p>您的 SoundCloud 用户名是<span class="user">[无用户名]</span>.</p>

用于发送 XMLHttpRequests(ajax() 函数在 jQuery 中)使用 AngularJS,请参阅他们的 $http 服务.

如果您想保留状态,在将用户发送到授权端点时,请查看 state 参数.

I'm in the process of designing an API in PHP that will use OAuth2.0. My end goal is to build a front-end application in javascript (using AngularJS) that accesses this API directly. I know that traditionally there's no way to secure transactions in javascript and so directly accessing an API isn't feasible. The front-end would need to communicate with server code that in turn communicated with the API directly. However, in researching OAuth2 it looks as if the User-Agent Flow is designed to help in this situation.

What I need help with is implementing the OAuth2 User-Agent Flow in javascript (particularly AngularJS if possible as that's what I'm using for my front-end). I haven't been able to find any examples or tutorials that do this. I really have no idea where to start and don't want to read through the entire OAuth2 spec without at least seeing an example of what I'll be looking at doing. So any examples, tutorials, links, etc would be greatly appreciated.

解决方案

The Implicit Grant flow (the one you're referring to as User-Agent Flow) is exactly the way to go:

The implicit grant is a simplified authorization code flow optimized for clients implemented in a browser using a scripting language such as JavaScript.

To understand the flow, the documentation from Google for client-side applications is a really good place to start. Note that they recommend you to take an additional token validation step to avoid confused deputy problems.

Here is a short example implementation of the flow using the Soundcloud API and jQuery, taken from this answer:

<script type="text/javascript" charset="utf-8">
  $(function () {
    var extractToken = function(hash) {
      var match = hash.match(/access_token=([\w-]+)/);
      return !!match && match[1];
    };

    var CLIENT_ID = YOUR_CLIENT_ID;
    var AUTHORIZATION_ENDPOINT = "https://soundcloud.com/connect";
    var RESOURCE_ENDPOINT = "https://api.soundcloud.com/me";

    var token = extractToken(document.location.hash);
    if (token) {
      $('div.authenticated').show();

      $('span.token').text(token);

      $.ajax({
          url: RESOURCE_ENDPOINT
        , beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', "OAuth " + token);
            xhr.setRequestHeader('Accept',        "application/json");
          }
        , success: function (response) {
            var container = $('span.user');
            if (response) {
              container.text(response.username);
            } else {
              container.text("An error occurred.");
            }
          }
      });
    } else {
      $('div.authenticate').show();

      var authUrl = AUTHORIZATION_ENDPOINT + 
        "?response_type=token" +
        "&client_id="    + clientId +
        "&redirect_uri=" + window.location;

      $("a.connect").attr("href", authUrl);
    }
  });
</script>
<style>
  .hidden {
    display: none;
  }
</style>

<div class="authenticate hidden">
  <a class="connect" href="">Connect</a>
</div>

<div class="authenticated hidden">
  <p>
    You are using token
    <span class="token">[no token]</span>.
  </p>

  <p>
    Your SoundCloud username is
    <span class="user">[no username]</span>.
  </p>
</div>

For sending XMLHttpRequests (what the ajax() function does in jQuery) using AngularJS, refer to their documentation of the $http service.

If you want to preserve state, when sending the user to the authorization endpoint, check out the state parameter.

这篇关于如何在 Javascript 中实现安全的 OAuth2 消费?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆