Identityserver 4 introspection showing token status as active after sign-out - identityserver4

After I logout from identity server, I tried to access introspect using postman but I am getting status as active but after 5min only getting active status as false
https://localhost:5000/connect/introspect
I also tried to access API using the same token but I am getting unauthorize error (401) as expected. Please note that in API I have added the setting ClockSkew = TimeSpan.FromSeconds(0),
How to set introspect to return the correct result after token expires without adding the extra sync time.

Related

Getting access tokens from Postman: Tokens issued for the 'Single-Page Application' client-type may only be redeemed via cross-origin requests

We recently made a switch from Implicit Grant Flow to Authorization Code Flow with PKCE for our application, and now we're having some trouble getting access tokens from Azure AD from Postman. The app is registered in Azure AD and we're basically using the Postman procedure described here: https://developer.mypurecloud.com/api/rest/postman/index.html#enable_authorization. Calling the https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize endpoint works ok, but it hits an error when calling https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token:
"Error: Cound not complete OAuth 2.0 token request: "AADSTS9002327: Tokens issued for the 'Single-Page Application' client-type may only be redeemed via cross-origin requests.\r\nTrace ID: 8253f622-3425-4d0a-817c-281f86097300\r\nCorrelation ID: 9d84460f-ec02-4ace-af03-14d948e3d4ad\r\nTimestamp: 2020-04-15 14:02:03Z"
This is the access token request:
How can we get access tokens from Azure AD using Postman with this authorization flow?
Apparently this is a problem as the documentation is confusing.
Over the Azure Active Directory App Registration. Make sure you add the redirect url over the "Mobile and desktop applications" category.
When you read the documentation looks like you need to add the Redirect URL under the Single Page Apps. It even shows confirmation message saying "Your Redirect URI is eligible for the Authorization Code Flow with PKCE." but is not true.
This error can occur when the "Origin" header is missing from the request (see: GitHub comment).
Try adding the header:
Origin: http://localhost
If you're experiencing this failure whilst trying to authenticate using Postman, ensure that you have a platform authentication for Web.
Go to Azure AD > App Registrations > {your app reg} > Authentication > Add a platform. Redirect URI should be https://oauth.pstmn.io/v1/callback when using the browser.
For me I was trying update the MSAL v1 implementation to v2 implementation where I got this issue. After doing migration from web to SPA in the Azure where it clearly takes about the same fixed my issues.
https://learn.microsoft.com/en-us/answers/questions/315313/azure-app-registration-causing-the-following-error.html
https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-browser#implicit-flow-vs-authorization-code-flow-with-pkce
To get an refresh_token you have to add "offline_access" to the scope.
The documentation of the response to the access token request says:
An OAuth 2.0 refresh token. The app can use this token acquire additional access tokens after the current access token expires. Refresh_tokens are long-lived, and can be used to retain access to resources for extended periods of time. For more detail on refreshing an access token, refer to the section below.
Note: Only provided if offline_access scope was requested.
Documentation
I was able to resolve this by doing the following:
Within the Azure Portal:
Navigate to the App Registration that you are using for your protected API.
Next, navigate to the Authentication blade within the Manage menu.
Within your Single-page application platform, add the following Redirect URI, https://oauth.pstmn.io/v1/callback.
Save these changes within the Azure Portal.
Next, within Postman's New Token Configuration:
Manually set the Callback URL to the same URI specified above (i.e. https://oauth.pstmn.io/v1/callback).
Once the above are done, clear your cookies from within Postman, and re-attempt retrieval of the token.
Follow these steps:
In your registered app, add platform for mobile and desktop application like below image:
Get your code which will be redirected to https://login.live.com/oauth20_desktop.srf?code=<code>.
If you are using Postman to get token so cross origin issue chances can be there. So try below php code to get token:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://login.microsoftonline.com/{tenenat-id}/oauth2/v2.0/token");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"grant_type=authorization_code&code={auth-code}&client_id={client-id}&scope=https%3A%2F%2Fmanagement.azure.com%2F.default&redirect_uri=https://login.live.com/oauth20_desktop.srf");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
var_dump($server_output);
1.You should first get the code in the browser,Enter the following request information in the browser address bar:
2.Then enter the obtained code and other request information in postman, you will get the access token
3.Please check: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow

Keycloak delete user give me an 401 Unauthorized error

I am trying to delete a user from a realm using keycloak admin client api.
I am following an example from here:
https://gist.github.com/thomasdarimont/43689aefb37540624e35
Here is what my code looks like:
Keycloak kc = KeycloakBuilder.builder().serverUrl("https://localhost:8445/auth")
.realm("sensorcloud-auth").username("admin").password("admin").clientId("admin-cli")
.clientSecret("b6b4f0ec-9936-46a2-9f40-69c207e2e0f2")
.resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build()).build();
kc.realm("sensorcloud-auth").users().get("a3fdac49-f7eb-4be7-a81f-b48b09a6694c").remove();
I can login to keycloak admin console using username admin and password admin, and I am pretty sure there is no typo with other parameters, but every time when I try to delete the user with that userId, I will be given a 401 Unauthorized error. Can someone help me figure out what is going on?
Not sure which version of keycloak admin client api you are using, with current API there is no remove operation.
It should be kc.realm(realmName).users().delete(id) . You can check the REST API for Delete User
We kept getting HTTP 401 status code responses when the hostname stamped on the iss field of the bearer's/user's access token had a different case i.e. lowercase vs. uppercase than the url used to post an HTTP request to keycloak's token endpoint.
While creating Keycloak instance, Realm should be master realm.
After creating instance with Master Realm, you can delete the user by using your code.

Redirect When Access Token Expired OAuth2

Im using OAuth2 to secure my API, but i wouldn't use refresh token to get my new access token, im just want redirect to some pages when the access token is expired
Header Response Capture
I guess redirecting is easy, If your application is a server App then send the response back to browser with status 302 and LOCATION=redirect_URI?error_code=&error_desc=. You can build the error page to be JSP or even servlet which simply reads the error_code and error_description and displays it in friendly manner. Make sure that the error page is not protected by the filter which checks the token

$http & JSESSIONID with Glassfish

I have a backend using Java which produces JSON for the services, which client will need to login/be authenticated using cookies based (JSESSIONID in Java).
I manage to receive JSESSIONID from server, however concecutive $http.get from client does not include previous generated JSESSIONID which I supposed to be automated handle by $http ?
The case:
Step 1
When I tested my login page using $http.post using valid user id and password, I can get an expected result from my server, I can get a generated JSESSIONID from the server, i.e.:
set-cookie:JSESSIONID=0a624257d0f704840bf6d8c8cc31; Path=/tmh-web; HttpOnly
(pls refer to screenshot in Response Header)
after call Login & been auhthenticated screenshot
Step 2
After been authenticated, when tried to call another URL service which requires authentication, I got an error: "403 Forbidden"
And I suspected this is because $http does not send the JSessionID it has received on Step 1.
(pls refer to screenshot in Request Header, there is no JSessionID has been sent back to server)
call next service which requires authentication
Has anyone experienced this problem with Java as the backend server ?
Use / for path attribute of the cookie.

How to stop Web API getting 401 when using OWIN Cookie authentication

I have a web app which is MVC 5 using OWIN cookie authentication. It also uses AngularJS from which web api calls are made. The Angular code is only invoked after the user has successfully logged in and been authenticated and everything works as you would expect.
However, can someone please explain what component (Chrome, OWIN, IIS, ...) is responsible for eventually issuing a 401 if the user has been idle for 20 or so minutes. In MVC this is not a problem because the redirect automatically re-authenticates but with web api my only option is to get the user to log back in again.
Ok so thats the first thing, who is responsible for timing the session out and giving the 401 (and can i alter it) but ALSO is there any way to get web api calls to keep the session alive so that even if the user is idle the api calls stop it timing out?
Specifically, I have implemented SignalR in a way that the signal to the client results in the client issuing an api call to refresh its data. I realise i could push the refresh but at the moment thats a bit tricky. So whats happening is the updates are occuring nicely but eventually this results in a 401 which i want to avoid.
below is an ideal flow
server logs in => creates cookie sets expiration time, passes it to client
client saves cookies & passes it with each request
server checks the cookies for validity including expiration time
if invalid or expired, server responds with 401
the cookie expiration time can be configured in the CookieAuthenticationOptions. See file ~/App_Start/Startup.Auth.cs
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
ExpireTimeSpan=TimeSpan.FromDays(365),
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
Set your ExpireTimeSpan to the desired TimeSpan.
For web api calls that fail authentication you could catch 401's and send back a response that tells the browser it's logged out - you could pop up a login dialog or redirect to login url.

Resources