Identity Server 4 Scopes found on current principal: "" - api

I attempting to use Identity Server 4 to authenticate users before granting access to a API. I am using a Implicit configuration as the front end is a Ember JS app. I have been able to Login, display the consent screen and then navigate to the redirectUri. However as soon as the Bearer Token is sent to the API I get back a 403.
I was able to find in the logs right before the 403 is returned it states there are not any scopes specified for the current principle. However I have yet to find anyone else reporting the same issue so I am not sure what I am doing wrong.
Any help would be appreciated.
API LOG
2017-03-27 15:24:35.358 -05:00 [Information] Request starting HTTP/1.1 GET http://localhost:55026/incentives/api/categories application/json
2017-03-27 15:24:36.035 -05:00 [Information] Successfully validated the token.
2017-03-27 15:24:36.046 -05:00 [Information] HttpContext.User merged via AutomaticAuthentication from authenticationScheme: "Bearer".
2017-03-27 15:24:36.048 -05:00 [Information] AuthenticationScheme: "Bearer" was successfully authenticated.
2017-03-27 15:24:36.051 -05:00 [Information] Scopes found on current principal: ""
2017-03-27 15:24:36.053 -05:00 [Warning] Scope validation failed. Return 403
2017-03-27 15:24:36.059 -05:00 [Debug] Connection id ""0HL3L9SNQEILQ"" completed keep alive response.
2017-03-27 15:24:36.060 -05:00 [Information] Request finished in 702.0523ms 403
new Client
{
ClientName = "IncentivesClient",
ClientId = "IncentivesClient",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RedirectUris = new List<string>
{
"http://localhost:4200/authorized"
},
PostLogoutRedirectUris = new List<string>
{
"http://localhost:4200/unauthorized"
},
AllowedCorsOrigins = new List<string>
{
"http://localhost:4200"
},
AllowedScopes = new List<string>
{
StandardScopes.OpenId,
StandardScopes.Email,
StandardScopes.Profile,
"incentiveRecords",
"incentiverecordsscope",
}
}
This is the API settings
IdentityServerAuthenticationOptions identityServerValidationOptions = new IdentityServerAuthenticationOptions
{
Authority = "https://localhost:44357",
RequireHttpsMetadata = true,
AllowedScopes = new List<string> { "incentiveRecords" },
ApiSecret = "incentiveRecordsSecret",
ApiName = "incentiveRecords",
AutomaticAuthenticate = true,
SupportedTokens = SupportedTokens.Both,
AuthenticationScheme = "Bearer",
SaveToken = true,
ValidateScope = true,
// TokenRetriever = _tokenRetriever,
// required if you want to return a 403 and not a 401 for forbidden responses
AutomaticChallenge = true,
};

The example that I had found for implementing your own torii provider for OATH2 had instructed to include 'id_token' and 'token' in the response params which made sense considering they are the response type being utilized in my Implicit configuration. To add to the confusion both the id_token and token were obtaining values successfully after the promise. It did bother me that they were identical and when I decoded them the audience was set to the client instead of including the resource server. So the super simple answer was to change the 'token' response param to 'access_token'. Now I am able to obtain the correct token from the promise and move on to utilizing it within the Auth header. Hope this helps someone else out there.

Related

Authenticate a cognito user using expo AuthSession API

I am using this example code
I am able to get a response from authorize endpoint.
request: {"clientId": "<retracted>", "clientSecret": undefined, "codeChallenge": "t6xISsEiAwOIwQxk0Ty1JNo2Kqa53mECL9a7YahLv_A", "codeChallengeMethod": "S256", "codeVerifier": "<retracted>", "extraParams": {}, "prompt": undefined, "redirectUri": "exp://192.168.0.22:19000", "responseType": "code", "scopes": undefined, "state": "o7FeO9ANoa", "url": "https://<retracted>"//oauth2/authorize?code_challenge=t6xISsEiAwOIwQxk0Ty1JNo2Kqa53mECL9a7YahLv_A&code_challenge_method=S256&redirect_uri=exp%3A%2F%2F192.168.0.22%3A19000&client_id=<retracted>"f&response_type=code&state=o7FeO9ANoa", "usePKCE": true}
LOG response: {"authentication": null, "error": null, "errorCode": null, "params": {"code": "<retracted>"", "state": "o7FeO9ANoa"}, "type": "success", "url": "exp://192.168.0.22:19000?code=<retracted>"&state=o7FeO9ANoa"}
const exchangeFn = async (exchangeTokenReq) => {
try {
const exchangeTokenResponse = await exchangeCodeAsync(
exchangeTokenReq,
discoveryDocument
);
setAuthTokens(exchangeTokenResponse);
} catch (error) {
console.error(error);
}
};
while exchangeFn is being invoked i am getting an error "ERROR [Error: Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method). The authorization server MAY return an HTTP 401 (Unauthorized) status code to indicate which HTTP authentication schemes are supported. If the client attempted to authenticate via the "Authorization" request header field, the authorization server MUST respond with an HTTP 401 (Unauthorized) status code and include the "WWW-Authenticate" response header field matching the authentication scheme used by the client.]"
Here is the application flow enter image description here
As per Oauth 2.0 while Exchanging an authorization code grant with PKCE for tokens we need to add Authorization header.
The authorization header string is Basic Base64Encode(client_id:client_secret). The following example is an authorization header for app client djc98u3jiedmi283eu928 with client secret abcdef01234567890, using the Base64-encoded version of the string djc98u3jiedmi283eu928:abcdef01234567890
The example code does not include this. That is the issue. we have to get the App client secret from aws cognito and add it to exchangeTokenReq.
const clientId = '<your-client-id-here>';
const userPoolUrl =
'https://<your-user-pool-domain>.auth.<your-region>.amazoncognito.com';
const redirectUri = 'your-redirect-uri';
const clientSecret = 'app-client-secret';
exchangeFn({
clientId,
code: response.params.code,
redirectUri,
clientSecret,
extraParams: {
code_verifier: request.codeVerifier,
},
});

Google Identity Services : How to refresh access_token for Google API after one hour?

I have implemented the new Google Identity Services to get an access_token to call the Youtube API.
I try to use this on an Angular app.
this.tokenClient = google.accounts.oauth2.initTokenClient({
client_id: googleApiClientId,
scope: 'https://www.googleapis.com/auth/youtube.readonly',
callback: (tokenResponse) => {
this.accessToken = tokenResponse.access_token;
},
});
When I call this.tokenClient.requestAccessToken(), I can get an access token and use the Youtube API, that works.
But after one hour, this token expires. I have this error : "Request had invalid authentication credentials."
How can I get the newly refreshed access_token transparently for the user ?
There are two authorization flows for the Google Identity Services (GIS) library:
The implicit flow, which is client-side only and uses .requestAccessToken()
The authorization code flow, which requires a backend (server-side) as well and uses .requestCode()
With the implicit flow (which is what you are using), there are no refresh tokens. It is up to the client to detect tokens aging out and to re-run the token request flow. Here is some sample code from google's examples for how to handle this:
// initialize the client
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: 'YOUR_CLIENT_ID',
scope: 'https://www.googleapis.com/auth/calendar.readonly',
prompt: 'consent',
callback: '', // defined at request time in await/promise scope.
});
// handler for when token expires
async function getToken(err) {
if (err.result.error.code == 401 || (err.result.error.code == 403) &&
(err.result.error.status == "PERMISSION_DENIED")) {
// The access token is missing, invalid, or expired, prompt for user consent to obtain one.
await new Promise((resolve, reject) => {
try {
// Settle this promise in the response callback for requestAccessToken()
tokenClient.callback = (resp) => {
if (resp.error !== undefined) {
reject(resp);
}
// GIS has automatically updated gapi.client with the newly issued access token.
console.log('gapi.client access token: ' + JSON.stringify(gapi.client.getToken()));
resolve(resp);
};
tokenClient.requestAccessToken();
} catch (err) {
console.log(err)
}
});
} else {
// Errors unrelated to authorization: server errors, exceeding quota, bad requests, and so on.
throw new Error(err);
}
}
// make the request
function showEvents() {
// Try to fetch a list of Calendar events. If a valid access token is needed,
// prompt to obtain one and then retry the original request.
gapi.client.calendar.events.list({ 'calendarId': 'primary' })
.then(calendarAPIResponse => console.log(JSON.stringify(calendarAPIResponse)))
.catch(err => getToken(err)) // for authorization errors obtain an access token
.then(retry => gapi.client.calendar.events.list({ 'calendarId': 'primary' }))
.then(calendarAPIResponse => console.log(JSON.stringify(calendarAPIResponse)))
.catch(err => console.log(err)); // cancelled by user, timeout, etc.
}
Unfortunately GIS doesn't handle any of the token refreshing for you the way that GAPI did, so you will probably want to wrap your access in some common retry logic.
The important bits are that the status code will be a 401 or 403 and the status will be PERMISSION_DENIED.
You can see the details of this example here, toggle to the async/await tab to see the full code.
To refresh the access token in a transparent way for the end-user you have to use the Refresh Token, This token will also come in the response to your call.
With this token, you can do a POST call to the URL: https://www.googleapis.com/oauth2/v4/token with the following request body
client_id: <YOUR_CLIENT_ID>
client_secret: <YOUR_CLIENT_SECRET>
refresh_token: <REFRESH_TOKEN_FOR_THE_USER>
grant_type: refresh_token
refresh token never expires so you can use it any number of times. The response will be a JSON like this:
{
"access_token": "your refreshed access token",
"expires_in": 3599,
"scope": "Set of scope which you have given",
"token_type": "Bearer"
}
#victor-navarro's answer is correct, but I think the URL is wrong.
I made a POST call to https://oauth2.googleapis.com/token with a body like this and it worked for me:
client_id: <YOUR_CLIENT_ID>
client_secret: <YOUR_CLIENT_SECRET>
refresh_token: <REFRESH_TOKEN_FOR_THE_USER>
grant_type: refresh_token

JWT validation with external authority doesn't work. ASP .NET Core 3.0

I am trying to authorize my requests using external service with IdentityServer4. I use following code
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = Configuration["IdentityUrl"];
options.RequireHttpsMetadata = false;
options.Audience = "myapi";
});
I got my token using token client
var tokenResponse = await tokenClient.RequestPasswordTokenAsync(
new PasswordTokenRequest
{
ClientId = clientId,
ClientSecret = clientSecret,
GrantType = GrantTypes.Password,
Address = discoveryDocument.TokenEndpoint,
UserName = user.UserName,
Password = user.PasswordHash,
});
It works and gives me token, but then when I try to authorize any request by including this token into authorization header it gives me 401 with no explanation. I don't see anything in output of either idenity server application or my client application.
This is what I do in postman to test authorization
Any ideas on what is wrong and how to debug it?
Try to see what the logs says?
Or try to set this one to true in the AddJwtBearer options and then look at the response from the API to see if it contains some additional details about the failure.
options.IncludeErrorDetails = true;
It it works you should see an additional WWW-authenticate header, like this one:
HTTP/1.1 401 Unauthorized
Date: Sun, 02 Aug 2020 11:19:06 GMT
WWW-Authenticate: Bearer error="invalid_token", error_description="The signature is invalid"

Redirect_URI error when using GoogleAuth.grantOfflineAccess to authenticate on server

I'm trying to use the authorization flow outlined at https://developers.google.com/identity/sign-in/web/server-side-flow.
I've created the credentials as indicated... with no Authorized redirect URIs specified as the doc indicates: "The Authorized redirect URI field does not require a value. Redirect URIs are not used with JavaScript APIs."
The code initiating the authorization is:
Client button and callback:
<script>
$('#signinButton').click(function() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.grantOfflineAccess().then(signInCallback);
});
function signInCallback(authResult) {
console.log('sending to server');
if (authResult['code']) {
// Send the code to the server
$.ajax({
type: 'POST',
url: 'CheckAuth',
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
},
processData: false,
data: authResult['code']
});
} else {
// There was an error.
}
}
</script>
Server side (CheckAuth method to create credentials from auth code, which it receives correctly via the javascript callback):
private Credential authorize() throws Exception {
// load client secrets
InputStream is = new FileInputStream(clientSecretsPath_);
InputStreamReader isr = new InputStreamReader(is);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, isr);
String redirect_URI = "";
GoogleTokenResponse tokenResponse =
new GoogleAuthorizationCodeTokenRequest(
httpTransport, JSON_FACTORY,
"https://www.googleapis.com/oauth2/v4/token",
clientSecrets.getDetails().getClientId(),
clientSecrets.getDetails().getClientSecret(),
token_,
redirect_URI)
.execute();
String accessToken = tokenResponse.getAccessToken();
// Use access token to call API
GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
return credential;
}
The flow works correctly, up until the point my server attempts to exchange the authorization code for the token response (GoogleAuthorizationCodeTokenRequest.execute() )... the auth server returns:
400 Bad Request
{
"error" : "invalid_request",
"error_description" : "Missing parameter: redirect_uri"
}
Given the error, I looked in debug at the auth instance in javascript and noted what it indicated was the redirect_uri. I then updated my google credentials and specified that URI in the Authorized redirect URIs (it's the URL that accessed the javascript, as the auth server correctly returns to the specified javascript callback). With the updated credentials and the URI specified in the instantiation of GoogleAuthorizationCodeTokenRequest (String redirect_URI = "http://example.com:8080/JavascriptLocation";), the error then becomes:
400 Bad Request
{
"error" : "redirect_uri_mismatch",
"error_description" : "Bad Request"
}
I've tracked all the way through to the actual HttpRequest to the auth server (www.googleapis.com/oauth2/v4/token) and cannot tell what redirect_uri it is looking for.
Does anyone know what the value of redirect_uri should be in this case (when using grantOfflineAccess())? I'm happy to post more of the code, if that is at all helpful... just didn't want to flood the page. Thanks.
Found a reference to "postmessage" right after posting the question... using it as the redirect_URI on the server side seems to generate a successful response from the auth server. So... setting redirect_URI="postmessage" in the code below appears to work in this situation.
GoogleTokenResponse tokenResponse =
new GoogleAuthorizationCodeTokenRequest(
httpTransport, JSON_FACTORY,
"https://www.googleapis.com/oauth2/v4/token",
clientSecrets.getDetails().getClientId(),
clientSecrets.getDetails().getClientSecret(),
token_,
redirect_URI)
.execute();

How to get id_token from TokenEndpoint of IdentityServer4 through authorization_code flow?

I would like to get "access_token" and "id_token" from Token endpoint through Authorization Code flow. But, I am getting "invalid_grant" error while calling the token endpoint with following parameters on postman.
POST /connect/token HTTP/1.1
Host: localhost:2000
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: a8a29659-0ea3-e7dc-3bd6-6e6630a7370d
client_id=client
&client_secret=client
&grant_type=authorization_code
&username=admin
&password=admin
&scope=openid+profile
Client Configuration:
new Client
{
ClientId = "client",
ClientSecrets =
{
new Secret("client".Sha256())
},
AllowedGrantTypes = new List<string> { OidcConstants.GrantTypes.AuthorizationCode },
AllowedScopes = {
StandardScopes.OpenId.Name,
StandardScopes.Profile.Name,
}
}
What is wrong in my client configuration section? and, How do i make a successful post request to Token Endpoint?
The authorization code grant type requires a code parameter to be sent during the token request (see RFC6749 section 4.1.3).
This code is issued by the authorization server after the resource owner authorized the client (see RFC6749 section 4.1.2).