IdentityServer3 - ScopeSecretValidator when using reference token - identityserver3

After receiving the access token (reference access token) my api middleware make a call to the instropection end point to get the jwt token. Unfortunate I'm getting a json response with an error message unauthortize.
2016-08-24 13:33:39.505 -04:00 [Debug] Start scope validation
2016-08-24 13:33:39.505 -04:00 [Debug] Start parsing Basic Authentication secret
2016-08-24 13:33:39.505 -04:00 [Debug] Parser found secret: "BasicAuthenticationSecretParser"
2016-08-24 13:33:39.505 -04:00 [Information] Secret id found: "webapp123.hybric.flow"
2016-08-24 13:33:39.507 -04:00 [Information] No scope with that name found. aborting
2016-08-24 13:33:39.507 -04:00 [Warning] Scope unauthorized to call introspection endpoint. aborting.
look like we are searching for the scopes requested by the client application using the client application id passed to the instropection endpoint.
Question:
Is his correct?
Can the Id3 remember the scopes requested by the client?
Can I call the instrospection endpint using the api ClientId? - I don;t want to use the client id of the client application that requested the reference token.
Code bellow:
var scope = (await _scopes.FindScopesAsync(new[] { parsedSecret.Id })).FirstOrDefault();

ntrospection endpoint is for validation of token and not to get Jwt. To call Introspection end point you need to pass "Scope" and "Scope secret" in the request for authentication not client id.
If you send the reference token to instrospection endpoint with valid scope name and secret you will get the claims in the response.
public async Task ValidateValidReferenceTokenUsingIntrospectionEndPoint()
{
var tokenResponse = await GetTokenResponseForClientCredentialsFlow(IdsModel.AccessTokenType.Reference);
var introspectionClient = new IntrospectionClient(
IntrospectionEndpoint,
"Api1", // scope name, scope secret
"Api1Secret");
var response = await introspectionClient.SendAsync(new IntrospectionRequest
{
Token = tokenResponse.AccessToken
});
var jsonResult = JsonConvert.DeserializeObject<Dictionary<string, object>>(response.Raw);
response.IsActive.Should().Be(true);
response.IsError.Should().Be(false);
jsonResult.Should().Contain("iss", ValidIssuer);
jsonResult.Should().Contain("aud", ValidAudience);
jsonResult.Should().Contain("client_id", "referenceTokenClient");
jsonResult.Should().Contain("client_claim1", "claim1value");
jsonResult.Should().Contain("active", true);
}

Related

Getting `The OAuth client was not found.` and `invalid client` error when trying to get access token for google cloud logging services in Dart

I'm following through this link: https://developers.google.com/identity/protocols/oauth2/service-account#httprest_1 in order to have my flutter app log to a log bucket in a google cloud project. Currently getting a
{
"error": "invalid_client",
"error_description": "The OAuth client was not found."
}
when I run the code below to get the access token in dart:
var jsonFile =
await File(jsonPath).readAsString();
var map = jsonDecode(jsonFile);
final jwt = JWT(
{
'iss': map['client_email'],
'sub': map['client_email'],
'aud': map['token_uri'],
'iat': (DateTime.now().millisecondsSinceEpoch / 1000).floor(),
'exp':
(DateTime.now().add(Duration(hours: 1)).millisecondsSinceEpoch / 1000)
.floor(),
},
issuer: map['private_key_id'],
);
final token = jwt.sign(SecretKey(map['private_key']));
print(token);
final accessToken = await http.post(
Uri.parse(map['token_uri']),
headers: {
HttpHeaders.contentTypeHeader: 'application/x-www-form-urlencoded',
},
body: {
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion': token,
},
);
The JSON file is the credentials of a service account with logging admin role in the GCP project.
Invalid client means that the client id or the client secret that you are using are not valid.
As per the official documentation,
When attempting to get an access or refresh token, you will get an
"Invalid client" error if you provide an incorrect OAuth 2.0 Client
Secret. Make sure the client_secret value you're using in access and
refresh token calls is the one for the OAuth 2.0 Client ID being used,
as found in your GCP Credentials page.
Also refer to this SO link Github link for more information.

Hashicorp Vault: 400 Bad Request Accept header is missing

I have enabled jwt auth on my dev vault instance
vault auth enable jwt
Success! Enabled jwt auth method at: jwt/
However, when I try to configure the jwks_url for the jwt auth I get the following error
➜ vault write auth/jwt/config jwks_url="<jwks_url>"
Error writing data to auth/jwt/config: Error making API request.
URL: PUT http://127.0.0.1:8200/v1/auth/jwt/config
Code: 400. Errors:
* error checking jwks URL: fetching keys oidc: get keys failed: 400 Bad Request Accept header is missing
Any idea what might I be doing wrong?

JWT token exchange via named credentials as per user

I am trying to generate a JSON Web Token(JWT) via named credentials as per user.
I want to use this named creds for authentincation purpose. So that using them after salesforce providing JSON web token, in exchange my local auth server will provide a token.
Below are the settings I have added while creating the named credentials as per user.
Label : TestJWTCredential
Name : TestJWTCredential
URL : -> external-endpoint <-
In Authentication Part
Certificate : MulesoftJWT
Identity Type : Per User
Authentication Protocol : JWT Token Exchange
Token Endpoint Url : http://localhost:8091/api/provider/token
Scope : refresh_token full
Issuer : -> my-username <-
Per User Subject : $userId
Audience : http://localhost:8091/api/provider/token
Token Valid for : 1 Hours
JWT Signing Certificate : MulesoftJWT
Ref :- https://help.salesforce.com/articleView?err=1&id=sf.named_credentials_about.htm&type=5#language-combobox
"http://localhost:8091/api/provider/token" This is the url of my authorization server which is a mule application deployed on my local.
Also while calling this named creds from developer console, it gives this error
System.CalloutException: Unable to complete the JWT token exchange.
Below is the APEX code,
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:TestJWTCredential/services/oauth2/userinfo');
req.setMethod('GET');
req.setHeader('Authorization', 'Bearer'+ UserInfo.getSessionId());
Http http = new Http();
System.debug('REQUEST :::: ' + req);
HTTPResponse resp = http.send(req);
System.debug('RESPONSE :::: ' + resp.getBody());
Can any body help me how to do it.
I was just viewing some Salesforce videos on this topic. In the "Deep Dive into Salesforce Connected App - Part 3" video, at the 23:56 mark, the Salesforce presenter had to delete the "scope" value to get it to work. https://youtu.be/wN8d4vwSA-E?t=1436

VK Api - Application authorization failed: refresh service token

When backend server call /method/secure.checkToken Api, it return a error message.
{
"error_code":28,
"error_msg":"Application authorization failed: refresh service token"....
}
What's mean about error_code 28?
is it mean my service token error?
This means that your application's access key is invalid
https://vk.com/dev/errors
This April VK changed access to the API. Now all requests must be signed with an application access key.

Robot Framework api test with OAUTH2 Authorization Request Header

I am trying to use the RequestsLibrary on an api thats using the OAUTH2 authentication.
Authentication is via OAUTH2 with credentials being supplied to the /v1/authtoken endpoint.
Subsequent calls to the APÍ need to have the token included as a ‘bearer’ in the ‘Authorization’ header of the http requests.
So below is the test case. The error I am getting is:
401 != 200
The credentials work ok in jmeter and a list of accounts is returned. However, I am not able to get the RF script work. Any help will be appreciated.
In the script,
Log to Console ${accessToken} returns the access token: 8ETFXTZOWQLrgsMj7c_KuCEeypdj-eO1r...
Log to Console ${token} returns: Bearer 8ETFXTZOWQLrgsMj7c_KuCEeypdj-eO1r...
*** Test Cases ***
Get authToken
Create Session hook http://xxxx.azurewebsites.net verify=${True}
${data}= Create Dictionary grant_type=client_credentials client_id=yyy-zzzz client_secret=xxxxxxxxxxxxxxx
${headers}= Create Dictionary Content-Type=application/x-www-form-urlencoded
${resp}= post request hook /v1/authtoken data=${data} headers=${headers}
Should Be Equal As Strings ${resp.status_code} 200
Dictionary Should Contain Value ${resp.json()} bearer
${accessToken}= evaluate $resp.json().get("access_token")
Log to Console ${accessToken}
${Bearer}= Set Variable Bearer
${token}= catenate Bearer ${accessToken}
Log to Console ${token}
${headers}= Create Dictionary Authorization=${token}
${resp1}= get request hook /v1/integration/accounts headers=${headers}
Should Be Equal As Strings ${resp1.status_code} 200
#Log to Console ${resp1.json()}
I am using OAuth 2.0 authentication as well for my salesforce automation.
My first answer would be to skip client based authentication and switch to username/password based authentication
Get authToken by Password Authentication
RequestsLibrary.Create Session hook https://<url>/services/oauth2 verify=${True}
${data}= Create Dictionary grant_type=password client_id=1abc client_secret=2abc username=test#test.com password=keypass
${headers}= Create Dictionary Content-Type=application/x-www-form-urlencoded
${resp}= RequestsLibrary.Post Request hook /token data=${data} headers=${headers}
Should Be Equal As Strings ${resp.status_code} 200
${accessToken}= evaluate $resp.json().get("access_token")
Log to Console ${accessToken}
If you are using client based or web based authentication, there will be a login screen that will be used by the user to enter their username/password to authorise the app to send requests on its behalf. Have a look at these pages for more information as they primarily discuss about using either refresh tokens or skipping the user prompt altogether.
Why does Google OAuth2 re-ask user for permission when i send them to auth url again
https://salesforce.stackexchange.com/questions/785/authenticate-3rd-party-application-with-oauth2
I have added the new answer for this question.
RequestsLibrary.Create Session OA2 <Your Server URL> verify=${True}
${data}= Create Dictionary Token_Name=TestTokenname grant_type=<grant type> client_Id=<your Id> Client_Secret=<Your client secret> scope=<your scpe>
${headers}= Create Dictionary Content-Type=application/x-www-form-urlencoded
${resp}= RequestsLibrary.Post Request OA2 identity/connect/token data=${data} headers=${headers}
BuiltIn.Log To Console ${resp}
BuiltIn.Log To Console ${resp.status_code}
Should Be Equal As Strings ${resp.status_code} 200
Dictionary Should Contain Value ${resp.json()} Testtokenname
${accessToken}= evaluate $resp.json().get("access_token")
BuiltIn.Log to Console ${accessToken}
${token}= catenate Bearer ${accessToken}
BuiltIn.Log to Console ${token}
${headers1}= Create Dictionary Authorization=${token}
RequestsLibrary.Create Session GT <Your Server URL> verify=${True}
${resp}= RequestsLibrary.Get Request GT <Your API URL> headers=${headers1}
Should Be Equal As Strings ${resp.status_code} 200