簡體   English   中英

如何將OAuth 2.0授權代碼交換為訪問令牌?

[英]How do I exchange a OAuth 2.0 authorization code for an access token?

我需要與HMRC(英國內陸稅收)REST API進行交互。 他們給了我Java的示例代碼,有人可以幫助我將其轉換為C#嗎? 我假設我必須將客戶端ID,客戶端機密,重定向Uri和授權代碼添加到HttpClient或HttpRequest中,但是我遇到了麻煩。 提前致謝。 吉姆。

這是Java示例:

// extract the authorization code from the request querystring
OAuthAuthzResponse response =
OAuthAuthzResponse.oauthCodeAuthzResponse(httpServletRequest);
String authorizationCode = response.getCode();

// create OAuth 2.0 Client using Apache HTTP Client
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

// construct OAuth 2.0 Token request for the authorization code
OAuthClientRequest request = OAuthClientRequest
  .tokenLocation("https://test-api.service.hmrc.gov.uk/oauth/token")
  .setGrantType(GrantType.AUTHORIZATION_CODE)
  .setClientId(clientId)
  .setClientSecret(clientSecret)
  .setRedirectURI(redirectUri)
  .setCode(authorizationCode)
  .buildBodyMessage();

// request the token via the OAuth 2.0 client
OAuthJSONAccessTokenResponse response = oAuthClient.accessToken(request);

// extract the data from the response
String accessToken = response.getAccessToken();
String refreshToken = response.getRefreshToken();
String grantedScope = response.getScope();
Long expiresIn = response.getExpiresIn();

這對我有用...

RESTClient := TRestClient.Create('https://test-api.service.hmrc.gov.uk/oauth/authorize');
RESTRequest := TRESTRequest.Create(RESTClient);
RESTResponse := TRESTResponse.Create(RESTClient);
OAuth2 := TOAuth2Authenticator.Create(RESTClient);

with RESTClient do
  begin
    Authenticator := OAuth2;
  end;

with RESTRequest do
  begin
    Client := RESTClient;
    Response := RESTResponse;
  end;

with OAuth2 do
  begin
    AccessTokenEndpoint := 'https://test-api.service.hmrc.gov.uk/oauth/token';
    AccessTokenParamName := 'access_token';
    AuthCode := <your authorisation code>;
    AuthorizationEndpoint := 'https://test-api.service.hmrc.gov.uk/oauth/authorize';
    ClientID := <your clientid>;
    ClientSecret := <your clientsecret>;
    RedirectionEndpoint := 'https://www.example.com/redirect';
    ResponseType := TOAuth2ResponseType(rtTOKEN);
    TokenType := TOAuth2TokenType(ttNONE);
    ChangeAuthCodeToAccesToken;
end;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM