I'm trying to achieve "Service Integration Authentication" following the steps here docusign docs and it's doing fine until Requesting the Access Token, where you send the jwt token (which is well formed)
I'm always getting "invalid_grant", and according to that doc, is because some of the claims are invalid. Is there another cause for that error?
All the claims looks good
C#:
//request access token
var client3 = new RestClient("https://" + _host);
var request3 = new RestRequest("/oauth/token", Method.POST);
request3.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request3.AddParameter("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
var headers = new[]
{
new Claim("alg", "RS256"),
new Claim("typ", "JWT"),
}.ToList();
var claims = new[] {
new Claim("iss", _integrationKey), //<-- integration key
new Claim("sub", OAuthGrant.Sub), //<-- returned from /oauth/userinfo (OK)
new Claim("iat", ToUnixTime(DateTime.Now).ToString(), ClaimValueTypes.Integer64),
new Claim("exp", ToUnixTime(DateTime.Now.AddHours(1)).ToString(), ClaimValueTypes.Integer64),
new Claim("aud", _host), //<-- "account-d.docusign.com"
new Claim("scope", "signature"),
}.ToList();
//build jwt from private key. token decodes just fine from https://jwt.io/
var jwtToken = CreateToken(claims, headers, "private-key.pem", Server.MapPath("/"));
request3.AddParameter("assertion", jwtToken);
System.Diagnostics.Debug.WriteLine("jwtToken:" + jwtToken);
var response = client3.Execute<OAuthToken>(request3);
System.Diagnostics.Debug.WriteLine("response content:" + response.Content); //<-- getting "invalid_grant"
return response.Data;
The jwt token was validated using https://jwt.io/ and decodes just fine.
Is docusign demo sandbox
Thanks in advance
daniel
My assumption is the library which you are using is generating wrong assertion for you. You can check DS SDK as well - ConfigureJwtAuthorizationFlow method in DS SDK, it will help you in generating the Assertion in correct way as expected by DS APIs.
Related
Please let me know if this is not possible...but in an effort to refactor my personal API I decided to start calling the Twitch endpoints through my API so data can be combined. To do this I direct the user to the auth page and get a bearer token back. I then pass that token to my API in the header. For some reason I get a 401 if I try to use that token at all from my API. I have no idea why as I can't view a reason in the response. The token works from postman.
Here is an example of a request I make in my API:
public async Task<bool> ValidateToken()
{
var response = await client.GetAsync("https://id.twitch.tv/oauth2/validate");
return response.StatusCode == HttpStatusCode.OK;
}
The HttpClient is created as follows before the validation method is called:
public TwitchService(IHeaderDictionary headers)
{
StringValues token;
StringValues clientId;
var hasToken = headers.TryGetValue("Authorization", out token);
var hasClientId = headers.TryGetValue("Client-id", out clientId);
client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "application/json");
if (hasToken)
{
var authToken = token.ToString().Replace("Bearer", "");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
}
if (hasClientId)
{
client.DefaultRequestHeaders.Add("Client-ID", clientId.ToString());
}
}
It turns out that the auth header is removed by the HttpClient and this is by design. The following link gives a good explanation about it: Authorization header is lost on redirect
I have an mvc 5 application with an web api 2. (.NET 4.6)
I implemented the oauth2 configuration next to the authentication for my mvc app (app.UseCookieAuthentication) :
OAuthAuthorizationServerOptions OAuthServerOptions = new
OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth/token"),
Provider = new AspNetIdentityOAuthAuthorizationServerProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(1000),
};
app.UseOAuthBearerTokens(OAuthServerOptions);
My apis are protected with the Authorize Attribute (global filter).
I use the client credentials grant
I followed these two articles (that are the same)
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api
https://mitchelsellers.com/blogs/2017/05/10/adding-webapi-oauth-authentication-to-an-existing-project
I'm able to get a token for my user, but when I want to use the token to access my Api, I get a 403 forbidden error
HttpClient client = new HttpClient();
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("grant_type", "client_credentials");
parameters.Add("client_id", "4rclFahG7gho8erzbsmTbw==");
parameters.Add("client_secret", "IBSqiYb0kT/lzV0gpQsPxkUDI9ztu0dhHWDe4VQDzKGYm2pl+75sMVfEsoGo4FAxFm0qZUFcDrVMrfqYhn2bzw==");
var content = new FormUrlEncodedContent(parameters);
try
{
HttpResponseMessage result = client.PostAsync("http://localhost:49594/oauth/token", content).Result;
string jsonResult = result.Content.ReadAsStringAsync().Result;
var resultObject = JsonConvert.DeserializeObject<TokenResult>(jsonResult);
var accessToken = resultObject.access_token;
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
result = client.GetAsync("http://localhost:49594/api/v1/echo?id=myt
estvalue").Result;
// RESULT is 403 - Forbidden
I tested with postman as well, and the result is the same.
did anyone experienced the same problem ?
do you know what I' missing ?
Update :
It's working if I deploy my application on a server (azure app services) but still not on my machine
I found the reason of my issue !
I'm using stuntman (https://rimdev.io/stuntman/) for my dev and I forgot to configure it for oauth ...
This line was missing :
StuntmanOptions.AllowBearerTokenPassthrough = true;
I'm trying to get an AppOnly access token for use in the Authorization Bearer header of my request to a REST endpoint in Project Online (SharePoint). Following is a snippet of the code that I was using to retrieve the access token.
private OAuth2AccessTokenResponse GetAccessTokenResponse()
{
var realm = TokenHelper.GetRealmFromTargetUrl([[our_site_url]]);
var resource = $"00000003-0000-0ff1-ce00-000000000000/[[our_site_authority]]#{realm}";
var formattedClientId = $"{ClientId}#{realm}";
var oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(
formattedClientId,
ClientSecret,
resource);
oauth2Request.Resource = resource;
try
{
var client = new OAuth2S2SClient();
var stsUrl = TokenHelper.AcsMetadataParser.GetStsUrl(realm);
var response = client.Issue(stsUrl, oauth2Request) as OAuth2AccessTokenResponse;
var accessToken = response.AccessToken;
}
catch (WebException wex)
{
using (var sr = new StreamReader(wex.Response.GetResponseStream()))
{
var responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
}
I keep getting 403 Forbidden as the response from the server, even if I include site collection admin credentials with my request. Does anyone out there have any ideas?
After creating a support ticket with Microsoft to figure this out we eventually decided to move away from using app permissions for console application authorization.
Our workaround was to create SharePointOnlineCredentials object using a service account, and then get the Auth cookie from the credentials object to pass with our WebRequest. This solution came from scripts found here: https://github.com/OfficeDev/Project-REST-Basic-Operations
I always get Bad Request 400 from IdentityServer3. I am trying for 3 days now but no luck :( Anyone could please tell me what am I doing wrong?
I am trying to access IdentityServer3 hosted by another vendor that I have no control. The vendor has asked us to implement Implement OAuth2 authentication with Bearer token. The vendor provided us with the Client ID, Client Secret and the URL to be used is http://www.xxxxxx.com/identity/connect/token
The vendor told us to use to request bearer token and use it in the request headers Authorization: Bearer
I can successfully obtain the bearer token from vendor. But when I call the
GET /api/profiles/myemailaddress#gmail.com I get Bad Request 400
Here is what I have done:
TokenClient client = new TokenClient("http://www.xxxxxx.com/identity/connect/token", "myclientid", "myclientsecret", AuthenticationStyle.PostValues);
var response = await client.RequestResourceOwnerPasswordAsync("myemailaddress#gmail.com", "mypassword", "profile"); // successfully gives me the token
i got the access token, now i want to use the token to request user profile:
var clienthttp = new HttpClient();
clienthttp.BaseAddress = new Uri("http://www.xxxxxx.com");
clienthttp.SetBearerToken(response.AccessToken);
var json = await clienthttp.GetStringAsync("http://www.xxxxxx.com/api/profiles/myemailaddress#gmail.com"); // error Bad Request 400
Additional Info:
"scopes_supported":["profile","offline_access"],
"claims_supported":[]
Thank you.
The vendor was expecting additional value in the header. Since my request was missing that additional value, they returned Bad Request. I had to modify my code to find the exact reason of bad request.
Here is the updated code, might be useful for someone:
var client = new HttpClient();
client.BaseAddress = new Uri("http://www.xxxxx.com");
client.SetBearerToken(response.AccessToken);
var callApiResponse = client.GetAsync("api/profiles/myemailaddress#gmail.com").Result;
string tokenresponse = callApiResponse.StatusCode.ToString();
string clientresult = callApiResponse.Content.ReadAsStringAsync().Result;
tokenresponse: "Bad Request 400"
clientresult: "Missing CompanyID in the header"
Then I knew that they also expect companyid in the header so I added it. then all was good.
client.DefaultRequestHeaders.Add("CompID", "xxxxxx");
I had a similar error (Response status code does not indicate success: 400 (Bad Request)) for different resource not identity server. i manage to resolve that using FormUrlEncodedContent
Refer below code
using (HttpClient client = new HttpClient())
{
string baseUrl = "https://*******.com/****"
Dictionary<string, string> jsonValues = new Dictionary<string, string>();
jsonValues.Add("username", "******");
jsonValues.Add("password", "******");
var contenta = new FormUrlEncodedContent(jsonValues);
var response = await client.PostAsync(baseUrl, contenta);
using (HttpContent content = response.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
Console.WriteLine(data);
}
}
}
I am building an OAuth service provider using DotNetOpenAuth, and to test it I have modified the sample wcf consumer to simply call a plain http endpoint. The token request works fine, but when I request access to a protected resource, I get the following protocol execption:
The following required parameters were missing from the DotNetOpenAuth.OAuth.Messages.AuthorizedTokenRequest message: oauth_verifier
When I look at the log output on my service provider I see this:
Error while performing basic validation of AuthorizedTokenRequest with these message parts:
oauth_token: pgzjBIs0pKCeDIcaIinyrV5Jhi0=
oauth_consumer_key: sampleconsumer
oauth_nonce: TM0Rc8kg
oauth_signature_method: HMAC-SHA1
oauth_signature: zmpxK5c69n1VzTEEcrnnd4e+qYI=
oauth_version: 1.0
oauth_timestamp: 1305067751
Notice the oauth_version: 1.0, even though I have specified ProtocolVersion.V10a when I create the consumer.
If I specify ProtocolVersion.V10 on both sides I get this exception:
Expected message DotNetOpenAuth.OAuth.Messages.AccessProtectedResourceRequest but received DotNetOpenAuth.OAuth.Messages.AuthorizedTokenRequest instead.
Here is the consumer code to get the token (this is straight from the sample code):
WebConsumer consumer = this.CreateConsumer();
UriBuilder callback = new UriBuilder(Request.Url);
callback.Query = null;
string[] scopes = (from item in this.scopeList.Items.OfType<ListItem>()
where item.Selected
select item.Value).ToArray();
string scope = string.Join("|", scopes);
var requestParams = new Dictionary<string, string> { { "scope", scope } };
var response = consumer.PrepareRequestUserAuthorization(callback.Uri, requestParams, null);
consumer.Channel.Send(response);
Here is my consumer code that is failing:
var accessToken = Session["WcfAccessToken"] as string;
var consumer = CreateConsumer();
var serviceEndpoint = new MessageReceivingEndpoint("https://mymachine/test/getUserName", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest);
var httpRequest = consumer.PrepareAuthorizedRequest(serviceEndpoint, accessToken);
var httpResponse = httpRequest.GetResponse();
In my service provider I call serviceProvider.ReadProtectedResourceAuthorization(); and it fails with the exception I mentioned above.
Any ideas what I am doing wrong?
This was a silly mistake on my part, I was returning the wrong TokenType, from my IServiceProviderTokenManager. The correct logic is shown in the service provider sample, and looks something like this:
if (tokenObject.State == TokenAuthorizationState.AccessToken)
return TokenType.AccessToken;
return TokenType.RequestToken;