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

时间:2018-10-02 09:10:40

标签: java c# apache http-request-parameters

I need to interact with an HMRC (UK Inland revenue) REST API. They've given me example code in Java can anyone help me to translate it into C#? I'm assuming I have to add the Client ID, Client Secret, Re-Direct Uri & Authorisation code to an HttpClient or HttpRequest but I'm stuck. Thanks in advance. Jim.

Here is the Java example :

// 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();

1 个答案:

答案 0 :(得分:0)

这对我有用...

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;