# Implementing your own IWebAuthenticator
如果內置身份驗證器無法滿足您的需求,您可以創建自己的身份驗證器。 以下是我在新的V1.1 REST API中為Twitter的僅應用程序身份驗證設置新身份驗證器的示例。
## [](#create-iwebauthenticator-implementation)創建IWebAuthenticator實現
將`EmptyAuthenticator`類導入到項目中,并將其重命名為所需的類名。
~~~vbnet
Implements IWebAuthenticator
Public Sub Setup()
'// 定義身份驗證所需的任何特定于用戶的變量
End Sub
Private Sub IWebAuthenticator_BeforeExecute(ByVal Client As WebClient, ByRef Request As WebRequest)
'// 例如 添加 headers, cookies, 等.
End Sub
Private Sub IWebAuthenticator_AfterExecute(ByVal Client As WebClient, ByVal Request As WebRequest, ByRef Response As WebResponse)
'// 例如 處理401未經授權或其他問題
End Sub
Private Sub IWebAuthenticator_PrepareHttp(ByVal Client As WebClient, ByVal Request As WebRequest, ByRef Http As Object)
'// 例如更新option, headers,等.
End Sub
Private Sub IWebAuthenticator_PrepareCurl(ByVal Client As WebClient, ByVal Request As WebRequest, ByRef Curl As String)
'// 例如添加flags到cURL
End Sub
~~~
## [](#about-this-example)關于本示例
Twitter的僅應用程序身份驗證使用OAuth 2.0客戶端憑據流的變體,其中應用程序被授予訪問權限,并具有將包含在每個請求中的唯一token。 以下流程用于獲取token,然后驗證請求:
1. Request token: POST Consumer Key和Consumer Secret使用基本身份驗證和Twitter指定的請求信息到`https://api.twitter.com/oauth2/token`來接收token
2. 在每個API請求的標頭中包含token`Authorization:Bearer{token}`
[Twitter Documentation](https://dev.twitter.com/docs/auth/application-only-auth)
## [](#define-setup)定義Setup()
`Setup`函數是一種約定,用于定義身份驗證所需的任何特定于用戶的變量。 獲取持有人token需要使用Consumer Key和Consumer Secret,以便在設置期間傳遞和存儲這些token。
~~~vbnet
Public ConsumerKey As String
Public ConsumerSecret As String
Public Sub Setup(ConsumerKey As String, ConsumerSecret As String)
Me.ConsumerKey = ConsumerKey
Me.ConsumerSecret = ConsumerSecret
End Sub
~~~
## [](#define-beforeexecute)定義BeforeExecute()
`BeforeExecute`函數用于在執行之前向`Request`添加字段。 示例包括向查詢字符串添加參數,向請求添加標頭或更新資源以指向安全路由。 `Request`在`ByRef`中傳遞,因此可以直接添加字段。 將`BeforeExecute`函數留空以通過`Request`未修改)
在此示例中,我們將請求承載token,然后將其作為“Authorization”標頭附加到請求。 幾點說明:
* 使用傳遞給`BeforeExecute`的`WebClient`來獲取token,以便任何代理值用于token請求
* 克隆`WebClient`,以便與傳遞給`BeforeExecute`的原始文件沒有無法預料的交互
### [](#get-a-token)獲取Token
~~~vbnet
Public Function GetToken(Client As WebClient) As String
On Error GoTo Cleanup
Dim TokenClient As WebClient
Dim Request As New WebRequest
Dim Response As WebResponse
' Clone client (to avoid accidental interactions)
Set TokenClient = auth_Client.Clone
Set TokenClient.Authenticator = Nothing
TokenClient.BaseUrl = "https://api.twitter.com/"
' Prepare token request
Request.Resource = "oauth2/token"
Request.Method = WebMethod.HttpPost
Request.RequestFormat = WebFormat.FormUrlEncoded
Request.ResponseFormat = WebFormat.Json
' Request a token using Basic authentication
Request.AddHeader "Authorization", _
"Basic " & WebHelpers.Base64Encode(Me.ConsumerKey & ":" & Me.ConsumerSecret)
Request.AddBodyParameter "grant_type", "client_credentials"
Set Response = TokenClient.Execute(auth_Request)
If Response.StatusCode = WebStatusCode.Ok Then
GetToken = Response.Data("access_token")
Else
Err.Raise 11041 + vbObjectError, Description:=Response.StatusCode & ": " & Response.Content
End If
Cleanup:
Set TokenClient = Nothing
Set Request = Nothing
Set Response = Nothing
' Rethrow error
If Err.Number <> 0 Then
' Error handling...
End If
End Function
~~~
### [](#add-token-to-header)添加Token到Header
~~~vbnet
Private Sub IWebAuthenticator_BeforeExecute(ByVal Client As RestClient, ByRef Request As RestRequest)
If Me.Token = "" Then
Me.Token = Me.GetToken(Client)
End If
Request.AddHeader "Authorization", "Bearer " & Me.Token
End Sub
~~~
就是這樣! 現在您可以使用任何您想要的身份驗證方案,盡管主要的(Basic和OAuth 1.0)已經創建并且可以在authenticators /目錄中找到。 這里創建的`TwitterAuthenticator`位于那里,包括一些小的更改,用于在請求之間緩存Token。
## [](#define-afterexecute)定義AfterExecute()
`AfterExecute`函數用于處理Unauthorized或Forbidden響應,并使用添加的憑據或其他行為重試。
在此示例中,不需要執行后行為并且該方法保留為空,但是有關如何使用它的示例,請參閱`DigestAuthenticator`。
## [](#define-preparehttp--preparecurl)定義PrepareHttp() / PrepareCurl()
`PrepareHttp`和`PrepareCurl`可用于更新將用于執行請求的基礎`WinHttpRequest`或cURL命令。 有關如何使用它的示例,請參閱`HttpBasicAuthenticator`。
## [](#finally-use-the-new-authenticator)最后,使用新的身份驗證器
~~~vbnet
Dim TwitterClient As New WebClient
Dim Auth As New TwitterAuthenticator
Auth.Setup _
ConsumerKey:="Your consumer key", _
ConsumerSecret:="Your consumer secret"
Set TwitterClient.Authenticator = Auth
~~~
- README
- 指南
- 概述
- GET Request
- WebRequest
- 屬性
- Resource
- Method
- Body
- Format
- RequestFormat
- ResponseFormat
- CustomRequestFormat
- CustomResponseFormat
- ContentType
- Accept
- ContentLength
- FormattedResource
- Cookies
- Headers
- QuerystringParams
- UrlSegments
- 方法
- AddHeader
- SetHeader
- AddUrlSegment
- AddQuerystringParam
- AddCookie
- AddBodyParameter
- CreateFromOptions
- WebClient
- 屬性
- BaseUrl
- Authenticator
- TimeoutMs
- ProxyServer
- ProxyBypassList
- ProxyUsername
- ProxyPassword
- EnableAutoProxy
- Insecure
- FollowRedirects
- 方法
- Execute
- GetJson
- PostJson
- SetProxy
- GetFullUrl
- WebResponse
- 屬性
- StatusCode
- StatusDescription
- Content
- Data
- Body
- Headers
- Cookies
- 方法
- Update
- WebHelpers
- 屬性
- WebStatusCode
- WebMethod
- WebFormat
- UrlEncodingMode
- EnableLogging
- 方法
- LogDebug
- LogWarning
- LogError
- LogRequest
- LogResponse
- Obfuscate
- ParseJson
- ConvertToJson
- ParseUrlEncoded
- ConvertToUrlEncoded
- ParseXml
- ConvertToXml
- ParseByFormat
- ConvertToFormat
- UrlEncode
- UrlDecode
- Base64Encode
- Base64Decode
- RegisterConverter
- JoinUrl
- UrlParts
- CloneDictionary
- CloneCollection
- CreateKeyValue
- FindInKeyValues
- AddOrReplaceInKeyValues
- FormatToMediaType
- MethodToName
- HMACSHA1
- HMACSHA256
- MD5
- CreateNonce
- IWebAuthenticator
- 方法
- BeforeExecute
- AfterExecute
- PrepareHttp
- PrepareCurl
- WebAsyncWrapper
- 屬性
- Client
- 方法
- ExecuteAsync
- 范例
- Salesforce網站
- Google APIs
- Todoist API
- 其他主題
- 調試
- 授權
- 實現自己的IWebAuthenticator
- Url編碼