MIP SDK 实现了一个身份验证委派来处理身份验证质询并使用令牌进行响应。 但该委派本身并未实现令牌获取。 令牌获取过程由开发人员决定,通过扩展 mip::AuthDelegate 类(特别是 AcquireOAuth2Token 成员函数)来完成。
构建 AuthDelegateImpl
为了扩展基类 mip::AuthDelegate,我们将创建一个名为 的新类 sample::auth::AuthDelegateImpl。 此类将实现 AcquireOAuth2Token 功能,并设置构造函数来使用我们的身份验证参数。
auth_delegate_impl.h
对于此示例,默认构造函数只接受用户名、密码和应用程序 的应用程序 ID。 这些变量将存储在私有变量 mUserName中, mPassword以及 mClientId。
请务必注意,身份提供者或资源 URI 等信息不需要实现,至少在 AuthDelegateImpl 构造函数中不需要实现。 该信息作为AcquireOAuth2Token对象中的OAuth2Challenge一部分传递。 相反,我们会在 AcquireOAuth2Token 中将这些详细信息传递给 AcquireToken 调用。
//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() 生成代码。 下面的示例讨论了获取令牌的几种方法。