2016-03-03 77 views
0

我在獲取OAuth2與通用OAuth2提供者一起工作時遇到了很多問題。這是情況。OAuth2與衛星和通用OAuth2提供者

服務提供了一個OAuth2身份驗證方法,用於我要授權的位置。我創建了一個AngularJS應用程序,有satellizer以下配置:

authProvider.baseUrl = 'http://localhost:3030/user/authorize'; 
    $authProvider.oauth2({ 
     name: 'customname', 
     url: '/token', 
     clientId: 'someapp', 
     requiredUrlParams: ['scope'], 
     scope: ['profile'], 
     authorizationEndpoint: 'http://location.to.oathserver', 
     redirectUri: 'http://localhost:3000' 
    }); 

的的baseUrl指向應處理中間件部分我的節點服務器。

我也有下面的代碼觸發驗證部分。

$scope.authenticate = function(provider) { 
    $auth.authenticate(provider) 
     .then(function(response) { 
      console.log(response); 
     }) 
     .catch(function() { 
      //something went wrong 
     }); 
} 

到目前爲止,這一切似乎都很好,看起來與Satellizer記錄的非常相似!現在,一旦我啓動角度應用程序並開始身份驗證,就會看到目標Node服務發出的請求。

Next我有我的node.js服務掛鉤到'用戶/授權/令牌'URL。下面的代碼:

router.options('/authorize/token', function(req, res, next) { 
    //var token = req.header('Authorization').split(' ')[1]; 
    res.end(); 
}); 

和:

router.post('/authorize/token', function(req, res, next) { 
    var authCode = req.param('code'); 
    var cliendId = req.param('clientId'); 
    var payload = jwt.decode(authCode, 'mySecret'); 
}); 

在此處,這一切似乎出問題。首先我似乎得到一個OPTIONS請求。我真的不知道該如何處理它,因爲我似乎無法在有關OPTIONS請求的文檔中找到任何內容。我認爲它可能會包含'授權'標題,但似乎並非如此,所以我用res.end()關閉了連接。

我也檢查了Chrome中的請求,但我似乎無法找到具有此確切名稱的標頭。

接下來我得到一個POST請求。這似乎包含一些東西,萬歲!我得到以下對象:

{ 
    code: "ZFFeat9pWfHzw4rGmjFYwucPRMFnBOkd2odEObvo", 
    cliendId: "someapp", 
    redirectiUri: "http://localhost:3000" 
} 

這在我看來像我應該有解碼的授權碼。這就是你看到我在上面的代碼中試着做的。不幸的是,這似乎把我的錯誤

Error: Not enough or too many segments

這告訴我,我做的可能出錯了,我卡住了。

我確實有一些似乎適用於其他人的PHP代碼,但我並沒有完全理解並且不能真正將代碼與我的代碼聯繫起來,因爲PHP不是我的專業,node.js/JavaScript也不是他的代碼。所以在這裏不用PHP代碼:

handle_cors(); // Handle CORS for cross domain requests 

// Get JSON data 
$input = json_decode(file_get_contents("php://input"), true); 

// Create Provider 
$provider = new SomeApp\OAuth2\Client\Provider\SomeApp([ 
    'clientId'   => 'someapp', 
    'clientSecret'  => 'mySecret', 
    'redirectUri'  => $input['redirectUri'], 
]); 

// Optional: Now you have a token you can look up a users profile data 
try { 

    // Try to get an access token (using the authorization code grant) 
    $token = $provider->getAccessToken('authorization_code', [ 
     'code' => $input['code'] 
    ]); 

    // We got an access token, let's now get the user's details 
    $user = $provider->getResourceOwner($token); 

    header('Content-Type: application/json'); 

    $result = $user->toArray(); 
    $result['token'] = create_token('my-example-key', $user->getId()); 
    echo json_encode($result); 
    exit(); 

} catch (Exception $e) { 
    // Failed to get user details 
    exit('Oh dear...' . $e->getMessage()); 
} 

希望有人能幫助我!提前致謝。

回答

0

對不起,我已經能夠自己解決它。我發現我錯過了一些URL來POST和GET。之後,來自Satellizer的例子變得清晰,並且幾乎可以將它們用作副本。