0
我得到了connect-auth和Google OAuth2運行的示例,但無法在我自己的代碼中使用它。不知何故,我從Google獲得一個access_token,但是當我試圖通過curl訪問令牌獲取數據時,有一個401 - 請求中有錯誤。當我使用the example code時,我從Google那裏得到的迴應是一樣的,但令牌一定是錯的?在CoffeeScript中使用express連接驗證
我想使用中間件,因爲我需要在整個項目中進行身份驗證。另外,我使用express路由器而不是連接路由器。下面的代碼:
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));
}
};