【问题标题】:How do I exchange a OAuth 2.0 authorization code for an access token?如何用 OAuth 2.0 授权码交换访问令牌?
【发布时间】:2018-10-02 09:10:39
【问题描述】:

我需要与 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();

【问题讨论】:

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


    【解决方案1】:

    这对我有用...

    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;
    

    【讨论】:

      猜你喜欢
      • 2018-09-30
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 1970-01-01
      • 2020-08-05
      • 2018-04-11
      • 2011-08-05
      相关资源
      最近更新 更多