在 CoffeeScript 中使用 Express 连接身份验证

发布于 2024-12-12 03:43:12 字数 2423 浏览 0 评论 0原文

我运行了 connect-auth 和 Google OAuth2 的示例,但无法在我自己的代码中运行它。不知何故,我从 Google 获得了 access_token,但是当我尝试使用访问令牌通过curl 获取数据时,出现 401 - 您的请求中存在错误。这与我使用示例代码时从 Google 得到的响应相同,但令牌一定有问题吗?

我想使用中间件,因为我需要在整个项目中进行身份验证。另外,我使用的是快速路由器而不是连接路由器。这是代码:

express     = require 'express'
app         = module.exports = express.createServer()
connect     = require 'connect'
auth        = require 'connect-auth'
store       = require('connect-redis')(express)
keys        = require './keys_file'
routes      = require("./routes")

auth_middleware = ->
  (req, res, next) ->
    urlp = url.parse(req.url, true)
    if urlp.query.login_with
      req.authenticate [ urlp.query.login_with ], (error, authenticated) ->
        if error
          console.log error
          res.end()
        else
          next()  unless authenticated is `undefined`
    else
      next()

app.configure ->
  app.set 'views', __dirname + '/views'
  app.set 'view engine', 'jade'
  app.use connect.logger()
  app.use express.bodyParser()
  app.use express.cookieParser()
  app.use express.session({ secret: 'keyboard cat', store: new store })
  app.use express.static(__dirname + '/public')
  app.use auth({strategies: [
    auth.Twitter({  consumerKey: keys.twitterConsumerKey, consumerSecret: keys.twitterConsumerSecret}),
    auth.Google2({  appId : keys.google2Id, appSecret: keys.google2Secret, scope: "email", callback: keys.google2CallbackAddress})
  ], trace: true})
  app.use auth_middleware
  app.use app.router

app.configure "development", ->
  app.use express.errorHandler(
    dumpExceptions: true
    showStack: true
  )

app.configure "production", ->
  app.use express.errorHandler()

app.dynamicHelpers
  session: (req, res) ->
    return req.session

app.dynamicHelpers
  messages: require 'express-messages'

app.get /.*/, routes.index

app.listen 3000

console.log 'Express server listening on port %d in %s mode', app.address().port, app.settings.env

index.js 路由:

exports.index = function(req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'})
  if( req.isAuthenticated() ) {
    res.end( authenticatedContent.replace("#USER#", JSON.stringify( req.getAuthDetails().user )  ) );
  } else {
     res.end( unAuthenticatedContent.replace("#PAGE#", req.url) );
  }
};

I got the example for connect-auth and Google OAuth2 running, but can't get it working in my own code. Somehow, I get an access_token from Google, but when I try to get data via curl with the access token, there's a 401 - There was an error in your request. It's the same response I get from Google when I use the example code, but something must be wrong with the token?

I'd like to use the middleware, as I need authentication in the whole project. Also, I'm using the express router instead of the connect router. Here's the code:

express     = require 'express'
app         = module.exports = express.createServer()
connect     = require 'connect'
auth        = require 'connect-auth'
store       = require('connect-redis')(express)
keys        = require './keys_file'
routes      = require("./routes")

auth_middleware = ->
  (req, res, next) ->
    urlp = url.parse(req.url, true)
    if urlp.query.login_with
      req.authenticate [ urlp.query.login_with ], (error, authenticated) ->
        if error
          console.log error
          res.end()
        else
          next()  unless authenticated is `undefined`
    else
      next()

app.configure ->
  app.set 'views', __dirname + '/views'
  app.set 'view engine', 'jade'
  app.use connect.logger()
  app.use express.bodyParser()
  app.use express.cookieParser()
  app.use express.session({ secret: 'keyboard cat', store: new store })
  app.use express.static(__dirname + '/public')
  app.use auth({strategies: [
    auth.Twitter({  consumerKey: keys.twitterConsumerKey, consumerSecret: keys.twitterConsumerSecret}),
    auth.Google2({  appId : keys.google2Id, appSecret: keys.google2Secret, scope: "email", callback: keys.google2CallbackAddress})
  ], trace: true})
  app.use auth_middleware
  app.use app.router

app.configure "development", ->
  app.use express.errorHandler(
    dumpExceptions: true
    showStack: true
  )

app.configure "production", ->
  app.use express.errorHandler()

app.dynamicHelpers
  session: (req, res) ->
    return req.session

app.dynamicHelpers
  messages: require 'express-messages'

app.get /.*/, routes.index

app.listen 3000

console.log 'Express server listening on port %d in %s mode', app.address().port, app.settings.env

index.js routing:

exports.index = function(req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'})
  if( req.isAuthenticated() ) {
    res.end( authenticatedContent.replace("#USER#", JSON.stringify( req.getAuthDetails().user )  ) );
  } else {
     res.end( unAuthenticatedContent.replace("#PAGE#", req.url) );
  }
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

偷得浮生 2024-12-19 03:43:12

我不知道咖啡脚本,但是 :

auth_middleware = ->
  (req, res, next) ->
    urlp = url.parse(req.url, true)
    if urlp.query.login_with
      req.authenticate [ urlp.query.login_with ], (error, authenticated) ->
        if error
          console.log error
          res.end()
        else
          next()  unless authenticated is `undefined`
   else
      next()

应该是 :

auth_middleware = (req, res, next)->
  urlp = url.parse(req.url, true)
  if urlp.query.login_with
    req.authenticate [ urlp.query.login_with ], (error, authenticated) ->
      if error
        console.log error
        res.end()
   else
    next()  unless authenticated is `undefined`

else
next()

我认为最大的问题是你要发送一个“范围”,尝试:

    auth.Google2({  appId : keys.google2Id, appSecret: keys.google2Secret, callback: keys.google2CallbackAddress})

I don't know coffeescript, but :

auth_middleware = ->
  (req, res, next) ->
    urlp = url.parse(req.url, true)
    if urlp.query.login_with
      req.authenticate [ urlp.query.login_with ], (error, authenticated) ->
        if error
          console.log error
          res.end()
        else
          next()  unless authenticated is `undefined`
   else
      next()

should be :

auth_middleware = (req, res, next)->
  urlp = url.parse(req.url, true)
  if urlp.query.login_with
    req.authenticate [ urlp.query.login_with ], (error, authenticated) ->
      if error
        console.log error
        res.end()
   else
    next()  unless authenticated is `undefined`

else
next()

I think the big issue though is you're sending a 'scope' up, try:

    auth.Google2({  appId : keys.google2Id, appSecret: keys.google2Secret, callback: keys.google2CallbackAddress})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文