Authorize Attribute to handle valid user in Docker - docker

I am running my .net core 5 application, namely Authentication Server and API Gateway, in Docker in Linux container. And controller class in the API GateWay contains an [Authorize] attributes to validate the user. Despite the user is valid (eg register and log in successfully), API Gate is unable allow the user to access the API. And here a part of my log that is complaining:
Failed to validate the token.Microsoft.IdentityModel.Tokens.SecurityTokenSignatureKeyNotFoundException: IDX10501: Signature validation failed. Unable to match key:
kid: '6B7ACC520305BFDB4F7252DAEB2177CC091FAAE1'.
Exceptions caught:''.
Am I right to say that, is it due to the cookies generated by Identity Service 4; idsrv.session and .netcore related cookies failed to be shared.
This is because based on my observation when my micro-services are running in IIS. The Authentication Server, shall generates two mentioned cookies when user logs in successfully. And the mentioned cookies are "shared" among the rest of the micro-services, partly because they are in the same localhost but different port number.
When my application are migrated to Docker; the Authentication Server is able to generate the related cookies, the rest of the contains failed to get the cookies.
And as the result, which I'm guessing, that is the result that API Gateway is unable to authorise a valid user.
Hence, I am wondering is my understanding of Authorization is correct and how should I fix the issue with a valid user.

https://stackoverflow.com/a/58877655/3312570
The error code IDX10501 points to incorrect bearer token middleware.
Try adding cookies. Use the below code. My guess, it won't help.
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();

Related

se.curity.identityserver.util.AllowedFrameOriginUtils

I was trying out the curity configuration for an authentication service and a token service for OAuth and OpenID Connect locally. After all the configuration, when I was trying to test it with OAuth Assistant, I get an error:
Bad request
The request could not be processed
In the terminal, I can see these two INFO logs for particular
se.curity.identityserver.util.AllowedFrameOriginUtils - Requested origin is not allowed: 'http://localhost:...'
se.curity.identityserver.controllers.authorize.AuthorizeOAuthRequestModelProvider - Could not establish the redirect uri for request and client www. If this error occurs *after* being redirected to the authentication service and back, then this error has probably occurred because the original session cookie has been lost. Ensure that the cookie named 'sessionid' was sent to the authentication service. If not, check that the user's browser is not withholding it (for example by the cookie jar becoming full) and that a reverse proxy is not interfering with it.
There is no issue with sessionid. Anyone know how to fix this issue?

Newly deployed cloud run app inaccessible, despite having requisite permissions (403)

Following this quickstart guide (Python version), I was able to quickly create and deploy a Python Flask app to a project owned by my organization. However, toward the end the guide instructs "Visit your deployed container by opening the service URL in a web browser", and but this is the step I can't get to work.
Curiously, in the logs
(https://console.cloud.google.com/logs/) the 'textPayload' data element for the request is "The request was not authenticated. Either...", which seems unusual, as I'd expect an unauthenticated request to return 401, not 403. In any case, it does not list my org email address in the request, suggesting my identity for some reason isn't being supplied. Any way to fix this so I can access the URL using a user with appropriate permissions?
Note: I can access the URL by manually running "curl -H 'Authorization: Bearer <my token>'"
Cloud Run URLs aren't directly accessible if the service only allows authenticated invocations because passing the URL on your browser will not generate the credential for you. You will have to pass auth credentials on your request and the easiest way to invoke the service is to use a tool like curl which is exactly what you noted.
You have two options to authenticate your end users which are the following:
Integrate Google Sign-In.
Implement Identity Platform or Firebase Authentication.
In either of the above choices, you need a public web or mobile app that handles the sign-in flow and then makes authenticated API calls to a Cloud Run (fully managed) service.
For more information on authenticating end users, check out the official documentation.
To complement what Mr. Donnald Cucharo said, you can also use Identity Aware Proxy (IAP) to expose your application in a secure way.

How does keycloak determine which signature algorithm to use?

I'm writing an application that uses keycloak as its user authentication service. I have normal users, who log in to keycloak from the frontend (web browsers), and service users, who log in from the backend (PHP on IIS). However, when I log in from the backend, keycloak uses HS256 as its signature algorithm for the access token, and thus rejects it for further communication because RS256 is set in the realm and client settings. To get around this issue, I would like to "pretend to be the frontend" to get RS256 signed access tokens for my service users.
For security reasons, I cannot give the HS256 key to the application server, as it's symmetrical and too many people can access the server's code.
I am currently debugging the issue using the same user/pw/client id/grant type both on the frontend and the backend, so that cannot be the issue.
So far I have tried these with no luck:
copying the user agent
copying every single HTTP header (Host, Accept, Content-Type, User-Agent, Accept-Encoding, Connection, even Content-Length is the same as the form data is the same)
double checking if the keycloak login is successful or not - it is, it's just that it uses the wrong signature algorithm
So how does keycloak determine which algorithm to sign tokens with? If it's different from version to version, where should I look in keycloak's code for the answer?
EDIT: clarification of the flow of login and reasons why backend handles it.
If a user logs in, this is what happens:
client --[login data]--> keycloak server
keycloak server --[access and refresh token with direct token granting]--> client
client --[access token]--> app server
(app server validates access token)
app server --[data]--> client
But in some occasions the fifth step's data is the list of users that exist in my realm. The problem with this is that keycloak requires one to have the view-users role to list users, which only exists in the master realm, so I cannot use the logged in user's token to retrieve it.
For this case, I created a special service user in the master realm that has the view-users role, and gets the data like this:
client --[asks for list of users]--> app server
app server --[login data of service user]--> keycloak server
keycloak server --[access token with direct granting]-->app server
app server --[access token]--> keycloak server's get user list API endpoint
(app server filters detailed user data to just a list of usernames)
app server --[list of users]--> client
This makes the the list of usernames effectively public, but all other data remains hidden from the clients - and for security/privacy reasons, I want to keep it this way, so I can't just put the service user's login data in a JS variable on the frontend.
In the latter list, step 4 is the one that fails, as step 3 returns a HS256 signed access token. In the former list, step 2 correctly returns an RS256 signed access token.
Thank you for the clarification. If I may, I will answer your question maybe differently than expected. While you focus on the token signature algorithm, I think there are either mistakes within your OAuth2 flows regarding their usage, or you are facing some misunderstanding.
The fact that both the backend and frontend use "Direct Access Granting" which refers to the OAuth2 flow Resources Owner Credentials Grant is either a false claim or is a mistake in your architecture.
As stated by Keycloak's own documentation (but also slightly differently in official OAuth.2 references):
Resource Owner Password Credentials Grant (Direct Access Grants) ... is used by REST clients that want to obtain a token on behalf of a
user. It is one HTTP POST request that contains the credentials of the
user as well as the id of the client and the client’s secret (if it is
a confidential client). The user’s credentials are sent within form
parameters. The HTTP response contains identity, access, and refresh
tokens.
As far as I can see the application(s) and use case(s) you've described do NOT need this flow.
My proposal
Instead what I'd have seen in your case for flow (1) is Authorization Code flow ...
assuming that "Client" refers to normal users in Browser (redirected to Keycloak auth. from your front app)
and assuming you do not actually need the id and access tokens back in your client, unless you have a valid reasonable reason. As the flows allowing that are considered legacy/deprecated and no more recommended. In this case, we would be speaking of Implicit Flow (and Password Grant flow is also discouraged now).
So I think that the presented exchange (first sequence with points 1 to 5 in your post) is invalid at some point.
For the second flow (backend -> list users), I'd propose two modifications:
Allow users to poll the front end application for the list of users and in turn the front-end will ask the backend to return it. The backend having a service account to a client with view-roles will be able to get the required data:
Client (logged) --> Request list.users to FRONTEND app --> Get list.users from BACKEND app
(<--> Keycloak Server)
<----------------------------------------- Return data.
Use Client Credentials Grant (flow) for Backend <> Keycloak exchanges for this use case. The app will have a service account to which you can assign specific scopes+roles. It will not work on-behalf of any user (even though you could retrieve the original requester another way!) but will do its work in a perfectly safe manner and kept simple. You can even define a specific Client for these exchanges that would be bearer-only.
After all if you go that way you don't have to worry about tokens signature or anything like that. This is handled automatically according to the scheme, flow and parties involved. I believe that by incorrectly making use of the flows you end up having to deal with tricky token issues. According to me that is the root cause and it will be more helpful than focusing on the signature problem. What do you think?
Did I miss something or am I completely wrong...?
You tell me.

'Provided Authorization Grant is invalid' error while trying to login a dockerized application using wso2

I have dockerized our Angular application which have been using WSO2 as API manager . After doing the configurations, i was able to run the application successfully and able to hit all existing api's. The only issue arises when i tried to use oath2/token api for performing login operation of our customer . Even though, the same code was used to perform authentication earlier(before dockerization) without any issues,now i am getting error as
{
"error": "invalid_grant",
"error_description": "Provided Authorization Grant is invalid"
}
Token generation api for login :
https://<myapplicationurl>:9443/oauth2/token
Errors am getting in docker console while trying to login using username 'devtest7#mailinator.com' :
Things to note :
WSO2 AM version is 2.1.0 , WSO2 IS version is 5.3.0
Arguments(headers & parameters) for the request is the same as that
used earlier(except the username and password).
I am able to create a new users and the corresponding user is listed
in Carbondb users list.
The issue exists while trying to login using existing user as well as
newly created users.
I have recently generated new ssl certificate for the application.
Able to login using super admin only . Login using newly created email and username is not working.
I tried solutions seen on stackoverflow which doesn't fixed my issues. Can any one please help?
There is a line in the above logs saying that SP tenant is not equal to user tenant and SP is not SaaS. Are the SP and users are from different tenants? Normally users cannot access SP across different tenants.
If you want to make the SP accessible across different tenants then you need to enable SaaS application option in the SP. Check this doc to learn more about SaaS application https://docs.wso2.com/display/IS530/Adding+and+Configuring+a+Service+Provider
Thanks for everyone who commented and tried to figure out the solution for the issue i mentioned. I got the resolution for the issue . As i tried multiple times to login by doing permutations and combinations in configurations, authentication was blocked for me. As a reason, i couldn't login and generate access token . I was able to resolve it by changing a flag in identity.xml file inside IS .
Changed the UserOperationEventListener enabling from 'true' to 'false' .
Before:
<EventListener enable="true" name="org.wso2.carbon.identity.governance.listener.IdentityMgtEventListener" orderId="95" type="org.wso2.carbon.user.core.listener.UserOperationEventListener"/>
After:
<EventListener enable="false" name="org.wso2.carbon.identity.governance.listener.IdentityMgtEventListener" orderId="95" type="org.wso2.carbon.user.core.listener.UserOperationEventListener"/>
This change allowed me to block the invalid authentication check. We are anyway adding that check from our code side.
According to the logs, it says
Non-SaaS service Provider's tenant domain is not same as user tenant
domain; carbon.super != mailinator.com
From the logs, the SP's is in the carbon.super tenant. But it considers the user as in the tenant mailinator.com.
When we specify the username for password grant with email as username, we have to use the full username with the tenant domain. (devtest7#mailinator.com#carbon.super).

Is there an OpenID Connect grant type or mechanism for an app to poll for the auth-code when redirect_uri doesn't apply?

If you have an on-device application (e.g. desktop program, mobile device app) you can use OpenID Connect with some caveats:
Using Resource Owner Credentials (grant_type: password) is the simplest, but might not be possible if the authentication server operator won't let you use that grant-type because of trust reasons (i.e. they don't want you collecting the user's username+password yourself) - or if they have a dynamic or custom authentication UI that would be hard to replicate in a native app.
With the interactive flows (implicit, hybrid) the authentication sever's authentication page is shown in an in-app web-view. Most users will have no idea that the application can snoop on the authentication page and capture their username and password, especially on mobile devices - but this way the application code can easily capture the authorization code and/or access token, and automatically dismiss the web-view without any additional user interaction. (I'm surprised I haven't heard of more cases of users' details being captured by malicious apps this way.)
...so the advice is to always open the authentication page using the system's web-browser, but on the Windows desktop there is no good, standard way for the system web-browser to return the server response to the application code, though there are a number of approaches currently in use:
The authentication success page instructs the user to copy and paste a blob of text (containing the authorization code or access_token response) back into the desktop application.
Show the page in an app-hosted web-view, as per the notes above.
If the authentication process always only needs a username and password (for example) the application could still capture the user's username and password with its own UI and then make its own HTTP requests to make it seem like a user's web-browser session, and get the authorization code and/or access_token that way.
On Windows only:
Have a small utility program authHelper.exe that when invoked forwards its command-line arguments to a named-pipe in the user's session.
The main client-application will register authHelper.exe as a temporary URI scheme handler in the per-user HKCU\Software\Classes key, e.g. my-application: such that the contents of any my-application: URI are passed as arguments into authHelper.exe.
The URI passed to the system web-browser to open the authentication page has the redirect_uri parameter set to my-application:, so after the user authenticates in the browser, the browser will request the custom URI scheme which is handled by Windows, which invokes authHelper.exe "access_token=..." which then sends the data down the named-pipe to the running application.
If the user doesn't have permission to write to their own HKCU\Software\Classes key, or if they're using a version of Windows that doesn't support custom URI scheme handlers with EXE registrations then this doesn't work.
Windows UWP applications can also use the Web Authentication Broker.
I was wondering if a different approach could be used: why can't the application simply poll the authentication server for the status of the authentication attempt? Or does this approach already exist, and if so, what is the name of the flow or grant?
Here's the flow I'm proposing:
When the user wants to authenticate, the application opens the system web-browser as before, but with another parameter for a one-time-use opaque ID provided by the application.
As soon as the system browser is open, the application makes requests every 500ms or so (i.e. a polling loop) to the authentication server using its own HTTP client that asks for the status of the active authentication attempt associated with the same opaque ID as before.
The initial few responses from the authentication server to the application will presumably be status: pending, but eventually after the user successfully authenticates within a timeout window then the application's poll request would indicate a successful attempt and also contains the access_token or authorization code as is applicable. If the user failed to authenticate (e.g. 3 incorrect attempts) or left the window open long enough causing a timeout then the poll response would indicate failure.
Does this already exist and does it have a name? Are there any potential security risks or vulnerabilities with this approach?
It exists and has a name, "OAuth 2.0 Device Flow for Browserless and Input Constrained Devices", but is not yet fully standardized, see: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-device-flow
Google also implemented this flow avant-la-lettre in a vendor-specific way:
https://developers.google.com/identity/protocols/OAuth2ForDevices

Resources