简体   繁体   English

带有Node.js API和标准JavaScript应用的OAuth2

[英]OAuth2 with nodejs api and standard javascript app

I'm trying to create an sort of plugin that users can simply add to a website and it will make COR calls to my app and return JSON that will be handled by the client side javascript. 我正在尝试创建一种插件,用户可以将其简单地添加到网站中,它将对我的应用程序进行COR调用,并返回将由客户端JavaScript处理的JSON。

This is working how I want it to, but now I'm trying to make sure that the user logs into my app before being allowed to receive any JSON from my server side app. 这是我想要的方式,但是现在我试图确保用户登录到我的应用程序,然后再允许其从服务器端应用程序接收任何JSON。

From here on I'll refer to my Node.js API as Server and the straight JS plugin as Client 从这里开始,我将把Node.js API称为服务器 ,将JS插件称为Client。

I found a npm plugin for node that handles OAuth2 on the Server, but I'm not sure I'm really understanding how to use it. 我在节点上找到了一个N​​pm插件来处理服务器上的OAuth2,但是我不确定我是否真的了解如何使用它。 Here's the link and I found this for taking care of it on the Client side. 这是链接 ,我发现是在客户端进行的。

Client -> App initializer: 客户端->应用初始化程序:

define [
  'oauth2'
], (oauth2) ->
  App =
    Models: {}
    Collections: {}
    Views: {}

    initialize: () ->
      $.get "/javascripts/mu-config.json", (config) =>
        @api_url = config.api
        @site = config.site
        @credentials = config.credentials
        @make_oauth_call()


    make_oauth_call: ->
      @xhr = new oauth2.OAuth2XMLHttpRequest
        authorizeEndpoint: "#{this.api_url}/callback"
        tokenEndpoint: "#{this.api_url}/oauth/access_token"
        clientID: this.credentials.clientID
        clientSecret: this.credentials.clientSecret
        localStoragePrefix: "oauth2.#{this.site.name}"
        requestAuthorization: (callback) ->
          console.log 'what?'
          console.log callback


    @xhr.onreadystatechange =  () ->
      console.log "do something"


    @xhr.open "GET", "#{this.api_url}/notes?site=1&user=1"
    @xhr.setRequestHeader 'Content-type', 'application/x-www-form-urlencoded'
    @xhr.send "site=1&user=1"

So what works here? 那么什么在这里起作用? Well the @xhr.open ... does in fact grab JSON from the Server, but that's about it. @xhr.open ...实际上确实可以从服务器获取JSON,仅此而已。 I'm not getting any errors from the Client, but the console.log 'what?' 我没有从客户端得到任何错误,但是console.log 'what?' does not fire and I don't believe anything is getting authenticated. 不会触发,我也不相信任何东西会得到认证。

Server -> oauth.coffee 服务器-> oauth.coffee

  token = null
  credentials =
    clientID: "sparkmasterflex"
    clientSecret: "bob_the_builder"
    site: 'http://marking_up.dev'

  OAuth2 = require('simple-oauth2') credentials


  authorization_uri = OAuth2.AuthCode.authorizeURL
    redirect_uri: 'http://localhost:3000/callback'
    scope: 'sites'
    state: '55fce6241c8e6432e8dfee583141aa58'

  res.redirect(authorization_uri)

  OAuth2.AuthCode.getToken
    code: "something here"
    redirect_uri: "http://localhost:3000/callback"
  , saveToken

  saveToken = (error, result) ->
    console.log('Access Token Error', error.message) if error
    token = OAuth2.AccessToken.create(result)

  module.exports = OAuth2

Server -> router 服务器->路由器

express = require("express")
db = require "../database"
oauth2 = require "../oauth"

router = express.Router()

# GET home page.
router.get "/", (req, res) ->
  res.render 'index',
    title: "Hello world"

# Initial page redirecting to Github
router.get '/auth', (req, res) ->
  res.redirect authorization_uri


# Callback service parsing the authorization token and asking for the access token
# router.get '/callback', (req, res) ->
router.route('/callback')
  .get (req, res) ->
    code = req.query.code
    console.log '/callback'
    oauth2.AuthCode.getToken
      code: code
      redirect_uri: 'http://localhost:3000/callback'
    , saveToken

    saveToken = (error, result) ->
      console.log('Access Token Error', error.message) if error
      token = oauth2.AccessToken.create(result)

module.exports = router

Running the node server I get this error: 运行节点服务器时出现此错误:

/Users/raymondke99/Sites/marking_up_api/oauth.js:19

res.redirect(authorization_uri);
^

ReferenceError: res is not defined
   at Object.<anonymous> (/Users/raymondke99/Sites/marking_up_api/oauth.js:19:1)
   at Module._compile (module.js:456:26)
   at Object.Module._extensions..js (module.js:474:10)
   at Module.load (module.js:356:32)
   at Function.Module._load (module.js:312:12)
   at Module.require (module.js:364:17)
   at require (module.js:380:17)
   at Object.<anonymous> (/Users/raymondke99/Sites/marking_up_api/routes/index.js:7:10)
   at Module._compile (module.js:456:26)
   at Object.Module._extensions..js (module.js:474:10)

I'm kinda at a loss here. 我有点不知所措。 The documentation for both of these seem pretty thorough but I still feel like I'm missing a huge chunk of information. 这两个文件的文档看起来都很详尽,但是我仍然觉得我缺少大量信息。 Can anyone help and/or lead me to help? 任何人都可以帮助和/或引导我提供帮助吗?

Thank you 谢谢

EDIT 编辑

I removed res.redirect() from oauth.coffee and I get the following error: 我从oauth.coffee中删除了res.redirect() ,并收到以下错误消息:

/Users/raymondke99/Sites/marking_up_api/node_modules/simple-oauth2/lib/core.js:16

  throw new Error('Callback not provided on API call');

    ^

Error: Callback not provided on API call
  at Object.api (/Users/raymondke99/Sites/marking_up_api/node_modules/simple-oauth2/lib/core.js:16:13)
  at Object.getToken (/Users/raymondke99/Sites/marking_up_api/node_modules/simple-oauth2/lib/client/auth-code.js:34:8)
  at Object.<anonymous> (/Users/raymondke99/Sites/marking_up_api/oauth.js:19:17)
  at Module._compile (module.js:456:26)
  at Object.Module._extensions..js (module.js:474:10)
  at Module.load (module.js:356:32)
  at Function.Module._load (module.js:312:12)
  at Module.require (module.js:364:17)
  at require (module.js:380:17)
  at Object.<anonymous> (/Users/raymondke99/Sites/marking_up_api/routes/index.js:7:10)

I have more than one router because I'm using expressjs and I'm not sure where I'm supposed to have the 'catch-all' redirect. 我有一个以上的路由器,因为我使用的是expressjs,但我不确定应该在何处进行“全部捕获”重定向。 Does it need to go into every router? 是否需要进入每个路由器?

Why do you have "res.redirect(authorization_uri)" in the oath file? 为什么宣誓文件中包含“ res.redirect(authorization_uri)”? You seem to already have the GET endpoint in your router? 您似乎已经在路由器中拥有GET端点了?

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

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