python-keycloak package with KeycloakOpenID : logout does not work - client

I have a keycloak docker container (pulled image jboss/keycloak ) and a Django 2.2 web container. For integration of django with keycloak social-auth-app-django was used. Login works fine. Now trying to implement logout using python-keycloak following instructions described here:
https://github.com/marcospereirampj/python-keycloak :
from keycloak import KeycloakOpenID
keycloak_openid = KeycloakOpenID(server_url="http://<my IP>:8080/auth/",
client_id="<client_id>",
realm_name="<my realm name>",
client_secret_key="<my secret>",
verify=True)
config_well_know = keycloak_openid.well_know()
token = keycloak_openid.token("<username>", "<password>")
print(token) # all tokens returned ok
userinfo = keycloak_openid.userinfo(token['access_token'])
print ("userinfo:", userinfo) # userinfo returned ok
keycloak_openid.logout(token['refresh_token'])
in the container log:
Some clients have been not been logged out for user <username> in <my realm name> realm: <client_id>
No logout happens, still can browse the site.
What's missing? Thanks
UPDATE
Maybe I understood the problem. The token I get from keycloak_openid.token() call is not the token that was generated for me at the moment of login. The only token that can be fed to keycloak_openid.logout() call for it to work is that original token ('refresh_token' key value of the token dict, to be specific). Calling keycloak_openid.refresh_token() also issues a new token which is rejected as logout credential. But the originally issued refresh_token does not seem to be stored anywhere - sessions, cookies or keycloak db. (Note: I did find access_token, it's in the django DB in social_auth_usersocialauth table, but I need refresh_token). However, it's dumped to the console output at the moment of login, so if I copy it and call keycloak_openid.logout() with it, it does logout from keycoak. The question is where can I find that original refresh_token?

I used to experience the same issue. What helped was
Going to admin page and location your user in the realm
open your browser's developer console and monitor the networks
Go to sessions tab on keycloak and click log out
Observe which end point is being called and mimic that in your python backend, with proper header in the request.
Hope this helps!

I understand that this question is outdated, but I managed to logout by this:
Add the following variables to settings.py:
SOCIAL_AUTH_KEYCLOAK_LOGOUT_URL = 'https://your-keycloak/auth/realms/your-realm/openid-connect/logout'
SOCIAL_AUTH_KEYCLOAK_EXTRA_DATA=[("refresh_token","refresh_token")]
Now it will save the refresh token in extra_data.
Add into urlpatterns list in urls.py:
url(r'^logout/$', views.logout, name='logout'),
Add the logout view with communication code to views.py:
from django.contrib.auth import logout as auth_logout
import requests
def logout(request):
if request.user.is_authenticated:
user = request.user
if user.social_auth.filter(provider='keycloak'):
social = user.social_auth.get(provider='keycloak')
access_token=social.extra_data['access_token']
refresh_token=social.extra_data['refresh_token']
#logger.debug(access_token) # you can view the tokens
#logger.debug(refresh_token)
logout_request_data={"client_id": settings.SOCIAL_AUTH_KEYCLOAK_KEY, "refresh_token": refresh_token, "client_secret": settings.SOCIAL_AUTH_KEYCLOAK_SECRET}
headers={"Authorization" : "Bearer "+access_token,"Content-Type" : "application/x-www-form-urlencoded"}
result=requests.post(settings.SOCIAL_AUTH_KEYCLOAK_LOGOUT_URL,data=logout_request_data,headers=headers)
auth_logout(request)
return redirect('/')
result code will be 204 on success.

Related

Google Identity for server-side web app - redirect URI mismatch

I'm attempting to set up the Code Model for Google authentication, so that my user can oauth with Google and my app can retrieve their Calendar data. I'm stuck on step 5 here, where I'm supposed to exchange the authorization code for refresh and access tokens. I'm using nestjs in the backend and React in the frontend.
What I've done already that's working:
User clicks a button on my web app's page
Client sets up google.accounts.oauth2.initCodeClient with the /calendar scope, in ux_mode: popup
User is shown the Google popup and can auth thru that
Client receives a response from Google containing the authorization code
Client makes a POST call to my backend to send it just that authorization code
In step 5, the client makes the POST call to localhost:4000/auth/google-test. In the backend, I'm using the googleapis package and have:
export const oauth2Client = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
'http://localhost:4000/' // <- note, I'm not sure if this is corect
);
And in the relevant controller route, I'm doing:
#Post('google-test')
public async googleTest(#Body() bodyReceived: any): Promise<any> {
let { code } = bodyReceived
let { tokens } = await oauth2Client.getToken(code)
oauth2Client.setCredentials(tokens);
console.log('Tokens: ' + tokens);
return
The error I'm getting is related to oauth2Client.getToken(code), and the error is a redirect_uri_mismatch. In GCP for the credentials for this app, I've added all of these as "Authorized redirect URIs":
http://localhost:3000/home
http://localhost:4000/auth/google-test
http://localhost:4000
What am I doing wrong?
It took a bit more Googling, but turns out that the right answer is to have my server make the token call with the redirect uri as "postmessage".
This SO question gives a bit more context. A somewhat unbelievable message, but it seems to work for my app.
It is evidently that what is happening is that the redirect URI does not match with the one in the GCP. This usually happens because backend tools such as Nestjs may be appending a trailing '/' to the URL and it may be interpreted as being part of the redirect_uri value.
You can try by temoving any trailing '/' via this following method oauthurl.replace(/\/$/, '')
Moreover, you can pass the generated auth URL to a meta tag. And check the html header to confirm what is the URL value.

Error using google API and OAUTH2 in Python to get user info

My web app is successfully going through google's recommended flow to get credentials to query Google Drive API. This works fine. However, when I try to use the same credentials already obtained to get the user's email and name, I get an error.
Here I retrieve credentials and query Google Drive API. This works perfectly fine
def analyze():
credentials = getCredentials()
drive_service = googleapiclient.discovery.build('drive', 'v3', credentials=credentials)
theFiles = drive_service.files().list(pageSize=1000,q="trashed=false", fields="files(id,name,modifiedTime, size)").execute() #THIS WORKS
Right after that, I try to use the SAME CREDENTIALS to get user info, but now it doesn't work
oauth2_client = googleapiclient.discovery.build('oauth2','v2',credentials=credentials)
user_info= oauth2_client.userinfo().get().execute() #THIS FAILS
givenName = user_info['given_name']
Error: https://www.googleapis.com/oauth2/v2/userinfo?alt=json returned "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.">
SOME OTHER IMPORTANT FUNCTIONS:
def getCredentials():
*Loads credentials from the session.*
sc = session['credentials']
credentials = google.oauth2.credentials.Credentials(token=sc.get('token'),
client_id=sc.get('client_id'),
refresh_token=sc.get('refresh_token'),
token_uri=sc.get('token_uri'),
client_secret=sc.get('client_secret'),
scopes=sc.get('scopes'))
the credentials are obtained in the callback page:
#app.route('/OAcallback')
def OAcallback():
flow =google_auth_oauthlib.flow.Flow.from_client_secrets_file('client_id.json', scopes=['https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/userinfo.profile'])
flow.redirect_uri = return_uri
authorization_response = request.url
flow.fetch_token(authorization_response=authorization_response)
credentials = flow.credentials
* Store the credentials in the session.*
credentials_to_dict(credentials)
Please help me understand why my credentials are not working when trying to get user info. What should I change?
Thanks in advance!!!
You are only requesting the profile scope. To also request the email address add the scope email.
Change this part of your code from:
scopes=['https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/userinfo.profile']
to:
scopes=['https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/userinfo.profile' 'email']

Google Oauth Error: redirect_uri_mismatch

I'm trying to use google Oauth 2 to authenticate with google calendar API for a web server running on AWS EC2.
When I generated the credentials I selected 'OAuth Client ID' and then 'Web Application'. For the Authorised redirect URIs I have entered:
http://ec2-XX-XX-XX-XXX.eu-west-1.compute.amazonaws.com
(I've blanked out the IP of my EC2 instance). I have checked this is the correct URL that I want the callback to go to.
The link that is generated in the server logs is of the form:
https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=XXXXXXXXXXXX-XXXXXXXXXXXXXX.apps.googleusercontent.com&redirect_uri=http://localhost:47258/Callback&response_type=code&scope=https://www.googleapis.com/auth/calendar.readonly
When I follow the link I get the error
'Error: redirect_uri_mismatch'.
I've read this SO question and have checked that I am using HTTP and there is no trialing '/'
I suspect that the URL generated should not have 'localhost' in it but I've reset the client_secret.json several times and each time I restart tomcat with the new client secret I still get a link with localhost but just over a different port.
Locally, I had selected Credentials type of 'other' previously and was not given an option for the Authorised redirect URI. I did try this for the EC2 instance but this won't give me the control I want over the redirect URI and sends the redirect over localhost.
Google throws redirect_uri_mismatch when the uri (including ports) supplied with the request doesn't match the one registered with the application.
Make sure you registered the Authorised redirect URIs and Authorised JavaScript origins on the web console correctly.
This is a sample configuration that works for me.
In case you are seeing this error while making API call from your server to get tokens.
Short Answer 👇 - What solved my problem
use string postmessage in place of actual redirectUri that you configured on cloud console.
Here is my initilization of OAuth2 client that worked for me.
// import {Auth, google} from 'googleapis`;
const clientID = process.env.GOOGLE_OAUTH_CLIENT_ID;
const clientSecret = process.env.GOOGLE_OAUTH_CLIENT_SECRET;
oauthClient = new google.auth.OAuth2(clientID,clientSecret,'postmessage');
My Case
On the frontend, I am using react to prompt the user for login with google with the authentication-code flow. On success, this returns code in the payload that needs to be posted to the google API server to get token - Access Token, Refresh Token, ID Token etc.
I am using googleapis package on my server. Here is how I am retrieving user info from google
// import {Auth, google} from 'googleapis`;
const clientID = process.env.GOOGLE_OAUTH_CLIENT_ID;
const clientSecret = process.env.GOOGLE_OAUTH_CLIENT_SECRET;
oauthClient = new google.auth.OAuth2(clientID,clientSecret,'postmessage');
/*
get tokens from google to make api calls on behalf of user.
#param: code -> code posted to backend from the frontend after the user successfully grant access from consent screen
*/
const handleGoogleAuth = (code: string) => {
oauthClient.getToken(code, async (err, tokens: Auth.Credentials) {
if (err) throw new Error()
// get user information
const tokenInfo = await oauthClient.verifyIdToken({
idToken: tokens.id_token
});
const {email, given_name, family_name, email} = tokenInfo.getPayload();
// do whatever you want to do with user informaton
}
}
When creating a Oath client ID, DO NOT select web application, Select "Other". This way, the Redirect URI is not required.

Issue token to logged in user via spring

I have a Spring (3.2) based web app that a user can log into. The site will also provide an API secured via OAuth 2.0. My question then, is how do I go about generating a token for a logged in user?
The underlying idea here is that there will be a mobile app that opens up a web frame to the login page, which will eventually redirect to a url schema with an oauth token that the app will catch and then use for the api calls. Looking at the code for TokenEndpoint, I see that it defers token creation to a list of TokenGranter types. Should I be creating my own TokenGranter extended class, or am I looking at this all wrong?
I ended up writing a controller like this:
OAuthClientRequest request = OAuthClientRequest
.authorizationLocation(csOauthAuthorizeUrl)
.setClientId(csClientId)
.setRedirectURI(
UrlLocator.getBaseUrlBuilder().addSubpath(AUTH_CODE_HANDLER_URL).asUnEscapedString())
.setResponseType("code")
.buildQueryMessage();
UrlUtils.temporarilyRedirect(httpResponse, request.getLocationUri());
return null;
Then handling the code returned. My big problem here was that I had the /oauth/authorize endpoint set to use client credentials. Once I realized that tokens were being issued for the client ID instead of the user, it started to make sense.
So you want to use the Authorization Flow of OAuth. Spring has already support that, if you have configured the spring-security-oauth correctly, you just have to redirect the user/your mobile apps to /oauth/authorize?client_id=xxx&response_type=code this will redirect user to authorization page, if user has not login yet, it will redirect the user to login page then to the authorization page.
After the user completed the authorization process, it will redirect the user to an already registered redirect_url parameter with the authorization_code 'yourapp.com/callback?code=xxxx'.
Your application should exchange this authorization_code with the real token access to /oauth/token?grant_type=authorization_code&code=xxxx&client_id=xxxx&client_secret=xxxx
After that you will receive the token access that can be used to access the resource server.

Why doesn't the login session "stick" when login in using "ionic serve" window but works when I point the browser to the www folder?

I am using Ionic to build a login system on top of Codeigniter/Ion_Auth/codeigniter-restclient and when I try to login from "ionic server" the login works but the next api request to the logged_in() method returns false.
The same thing works properly when I point the browser to the www folder.
So here is the problem step by step:
run ionic serve
you see the login form (http://localhost:8100/#/app/login)
enter email and pass
the rest api returns "login successful"
$state.go('app.profile') works and redirects to http://localhost:8100/#/app/profile
REST get api/logged_in returns false and I redirect to the login page
If I do the same in a regular browser, step 1 becomes: open browser and go to http://localhost:8888/App/www/#/app/login, at step 6 REST get api/logged_in returns true and I don't get redirected to the login page, I stay on the profile page.
The code is the same. So my guess is that maybe ion_auth doesn't get the cookies it wants or the session is reseted. I am not sure at this point what the problem is. This is my first Ionic/App project so I might be missing something about the proper way to authenticate from a mobile app using code that works in browsers
Thank you
UPDATE:
It seems that when using the 'ionic server' window every request to the API triggers a new session. The new session is stored in the database and ion_auth tests the logged_in against that last one, which doesn't contain the login details.
you were taking about REST api and cookies and sessions. Cookies and sessions don't go with REST philosophy. Here is why.
Let me tell you how we accomplish this problem in our project. Basic way of knowing which user is requesting and if it has the access rights is by the 'Authorization' header value. You can use Basic Authentication, Barer or any other.
We generally prefer token based authorisation system. When a login is successful, server sends a token. In ionic app, we save it using a factory called SessionService. So whenever user logs in, token is stored and is used for every request. But token would be lost if user closes the app. So we can store it in local storage. User can then be directly redirected to dashboard until user logs out.
app.factory("SessionService", function($window){
var user={};
if ($window.localStorage['user']!=undefined){
user=JSON.parse($window.localStorage['user']);
console.log(user);
}
return{
isLoggedIn:function(){
return !isEmpty(user);
},
logout:function(){
console.log("logout")
user={};
$window.localStorage.clear();
},
setUser:function(data){
user=data;
$window.localStorage['user']= JSON.stringify(user);
},
getUser:function(){
return user;
}
}
})
Now in every web request, you can call SessionService.getUser().token when setting value Authorization header.
UPDATE:
Despite using cookies is not recommended, you can use it in your application easily.
If you are sending request with CORS, angular doesn't sends cookies with request.
One of the way address this issue is to send withCredentials: true with every request:
$http({withCredentials: true, ...}).get(...)
Read further about this here.
Hope this helps!

Resources