Search code examples
sharepoint-onlineazure-cloud-servicessharepoint-apps

Token request failed at TokenHelper.GetAccessToken() when using OAuth2S2SClient


I created a SharePoint provider hosted app and it was working fine when I published and added to the site. I created a CName and registered in using appregnew page, deployed the cloud service project, installed and added the app. I am getting the same error on the page I have authentication [SharePointContextFilter]. the page without authentication [SharePointContextFilter] is working fine.

Below is the detailed error:

Error occured. Token request failed. Inner:System.Net.WebException: The remote server returned an error: (400) Bad Request. at System.Net.HttpWebRequest.GetResponse() at Microsoft.IdentityModel.S2S.Protocols.OAuth2.OAuth2WebRequest.GetResponse() at Microsoft.IdentityModel.S2S.Protocols.OAuth2.OAuth2S2SClient.Issue(String securityTokenServiceUrl, OAuth2AccessTokenRequest oauth2Request) Stacktace: at Microsoft.IdentityModel.S2S.Protocols.OAuth2.OAuth2S2SClient.Issue(String securityTokenServiceUrl, OAuth2AccessTokenRequest oauth2Request) at PasswordResetAppWeb.TokenHelper.GetAccessToken(String refreshToken, String targetPrincipalName, String targetHost, String targetRealm) at PasswordResetAppWeb.SharePointAcsContext.RenewAccessTokenIfNeeded(Tuple2& accessToken, Func1 tokenRenewalHandler) at PasswordResetAppWeb.SharePointAcsContext.GetAccessTokenString(Tuple2& accessToken, Func1 tokenRenewalHandler) at PasswordResetAppWeb.Controllers.PasswordProfilesController.Index() Stacktace:Microsoft.IdentityModel.Extensions

Any idea what I am doing wrong?

I used the Cname URL for both registering the app using appregnew.aspx and I also used the Cname URL when I packaged the app. What am I doing wrong here?

Any suggestions would be great.. Thanks in advance!!


Solution

  • I got it. I didn't copy the client secret id properly to the web.config. It had a space in it and that caused the issue.

    So steps are correct to add alias names to sharepoint apps hosted in cloud service:

    register app with new CName, change the clientID, Client Secret in webconfig and deploy, package the app using Cname and clientID and install and add the app. Make sure your client ID and client secret is copied correctly.

    Edit 7/31/2022: I got the exact same error again and this time I fixed it by enabling TLS 1.2.

            // Get token
            OAuth2S2SClient client = new OAuth2S2SClient();
            OAuth2AccessTokenResponse oauth2Response;
            const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
            const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
            ServicePointManager.SecurityProtocol = Tls12;
            try
            {
                oauth2Response =
                    client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
            }