2017-02-18 139 views
0

我已經使用Feathers創建了一個應用程序。我一直在使用這個應用程序。它成功地託管了一個博客和一些其他網頁。但是,我現在已經達到了需要保護我的一些路線的地步。例如,我想爲我的管理活動(/ admin)設置路由,但我只希望特定的用戶有權訪問。我知道我需要使用authentication和授權組件。但是,在這個時候,我堅持授權。我的目標是通過Google使用OAuth進行身份驗證。但是,要通過身份驗證挑戰,只需使用硬編碼的用戶名/密碼就可以鎖定/admin路由(不,未部署),我很高興。羽毛 - 身份驗證和授權

目前,我有

const app = feathers(); 
const routes = require('./routes'); 

app.configure(configuration(path.join(__dirname, '..'))); 

app.use(compress()) 
    .options('*', cors()) 
    .use(cors()) 
    .use(favicon(path.join(app.get('public'), 'favicon.ico'))) 
    .use('/public', serveStatic(app.get('public'), staticFileSettings)) 
    .use(bodyParser.json()) 
    .use(bodyParser.urlencoded({ extended: true })) 
    .configure(routes)  
    .configure(hooks()) 
    .configure(rest()) 
    .configure(socketio()) 
    .configure(services) 
    .configure(middleware) 
    .configure(authentication()) 
; 

// Setup the authentication strategy. 
app.authenticate({ 
    type: 'local', 
    'email': '[email protected]', 
    'password': 'admin' 
}).then(function(result){ 
    console.log('Authenticated!', result); 
}).catch(function(error){ 
    console.error('Error authenticating!', error); 
}); 

我的問題是,當我添加的代碼塊與app.authenticate東西,我當我開始我的應用程序出現錯誤。錯誤說:

TypeError: app.authenticate is not a function 

如果我刪除app.authenticate(...);我的應用程序啓動正常,但沒有被鎖定。在我的./routes/index.js文件中,我有:

app.use('/admin', function(req, res) { 
    res.render('admin/index.html', {}); 
});  

其中,渲染就好。它僅限於經過認證和授權的用戶。我錯過了什麼?在儘量減少我試圖瞭解如何通過app.authenticate錯誤。

+0

你想做什麼? 'app.authenticate'只在客戶端可用('feathers-authentication/client')。 – Daff

+0

最終,我試圖阻止未經授權的用戶訪問路由'/ admin'上的視圖。根據我的理解,我需要做兩件事:1)驗證用戶(我想通過Google的OAuth登錄進行驗證); 2)授權用戶。上面的問題解釋了我是如何卡在#1上的。 – Gary

回答

0

爲了保護路由免受未經授權的訪問,您需要follow the documented usage of express middlewarefeathers-authentication程序包提供,該程序包在您執行feathers generate authentication時安裝。

以下是驗證/admin路由的示例。

const auth = require('feathers-authentication'); 

app.use(
    '/admin', 
    auth.express.authenticate('jwt'), // <-- this is a strategy, can local/jwt... etc 
    (req, res, next) => { 
    console.log("Request for '/admin'..."); 
    res.render('admin'); 
    } 
);