MIP SDK 實作了認證代理來處理認證挑戰並以令牌回應。 它本身並不實作代幣取得。 代幣取得過程由開發者決定,透過擴充 mip::AuthDelegate 類別,特別是 AcquireOAuth2Token 成員函式來完成。
建築 AuthDelegateImpl
為了擴展基底類別 mip::AuthDelegate,我們建立一個新的類別,稱為 sample::auth::AuthDelegateImpl。 這個類別實作了這個 AcquireOAuth2Token 功能,並設定建構子來接收我們的認證參數。
auth_delegate_impl.h
在這個例子中,預設建構子只接受使用者名稱、密碼和應用程式的 應用程式 ID。 這些會儲存在私有變數 mUserName、 mPassword、 mClientId中。
值得注意的是,像身份提供者或資源 URI 這類資訊不必在建構子 AuthDelegateImpl 內實作。 這些資訊會作為AcquireOAuth2Token的一部分在OAuth2Challenge物件中傳遞。 相反地,我們將這些細節交給在AcquireToken中的AcquireOAuth2Token呼叫。
//auth_delegate_impl.h
#include <string.h>
#include "mip/common_types.h"
namespace sample {
namespace auth {
class AuthDelegateImpl final : public mip::AuthDelegate { //extend mip::AuthDelegate base class
public:
AuthDelegateImpl() = delete;
//constructor accepts username, password, and mip::ApplicationInfo.
AuthDelegateImpl::AuthDelegateImpl(
const mip::ApplicationInfo& applicationInfo,
std::string& username,
const std::string& password)
: mApplicationInfo(applicationInfo),
mUserName(username),
mPassword(password) {
}
bool AcquireOAuth2Token(const mip::Identity& identity, const OAuth2Challenge& challenge, OAuth2Token& token) override;
private:
std::string mUserName;
std::string mPassword;
std::string mClientId;
mip::ApplicationInfo mApplicationInfo;
};
}
}
auth_delegate_impl.cpp
AcquireOAuth2Token 是撥打 OAuth2 服務提供者的通話地點。 在範例中如下所示,有兩個呼叫AcquireToken()。 實際上,只會進行一次呼叫。 這些實作將在「下一步步驟」下的章節中介紹
//auth_delegate_impl.cpp
#include "auth_delegate_impl.h"
#include <stdexcept>
#include "auth.h" //contains the auth class used later for token acquisition
using std::runtime_error;
using std::string;
namespace sample {
namespace auth {
AuthDelegateImpl::AuthDelegateImpl(
const string& userName,
const string& password,
const string& clientId)
: mApplicationInfo(applicationInfo),
mUserName(userName),
mPassword(password) {
}
//Here we could simply add our token acquisition code to AcquireOAuth2Token
//Instead, that code is implemented in auth.h/cpp to demonstrate calling an external library
bool AuthDelegateImpl::AcquireOAuth2Token(
const mip::Identity& /*identity*/, //This won't be used
const OAuth2Challenge& challenge,
const OAuth2Token& token) {
//sample::auth::AcquireToken is the code where the token acquisition routine is implemented.
//AcquireToken() returns a string that contains the OAuth2 token.
//Simple example for getting hard coded token. Comment out if not used.
string accessToken = sample::auth::AcquireToken();
//Practical example for calling external OAuth2 library with provided authentication details.
string accessToken = sample::auth::AcquireToken(mUserName, mPassword, mApplicationInfo.applicationId, challenge.GetAuthority(), challenge.GetResource());
//set the passed in OAuth2Token value to the access token acquired by our provider
token.SetAccessToken(accessToken);
return true;
}
}
}
後續步驟
要完成認證實作,必須在函式背後 AcquireToken() 建置程式碼。 以下範例討論了幾種取得該代幣的方法。