keycloak init method gives authenticated false even when i login a with valid user - keycloak

Hello I am using keycloak with react , i used some keycloak code that i got from internet for keycloak and react integration . the problem is that when i use that code initially when i login in and get redirect from the keycloak login theme the authenticated is true which is okay . but as i refresh the page it is no longer true and become false.
here is the code:
keycloak
.init({ checkLoginIframe: false })
.then((authenticated) => {
console.log("authentication status",authenticated)
}).catch((err)=>{
console.log("error",err)
})
I want to make a http request on basis of token but for that i want to check if authentiacted is true or not.
the authenticated is true only first time when i am redirected from keycloak login page but as i refresh page its always false.i am using react for client side.

Related

Angular app integrated with key cloak is redirecting to login page ONLY ON page refresh

I have an Angular app, which is configured with key cloak Authentication. Once every 30minutes, the cookie/session set by key cloak gets expired . As per the default behavior, the app is redirecting to login page when the user refreshes the app manually.
But I wanted it some thing like whenever the token get expired , redirect the current session to key cloak login page. (this should happen automatically, i.e., even with out user manual refreshes the page.)
There is a keycloak API, that collects the user login-logout entries in it.
"http://localhost:8080/auth/admin/realms//events?dateFrom=2022-02-09&dateTo=2022-02-10&first=0&max=9999999&type=LOGIN&type=LOGIN_ERROR&type=LOGOUT&type=LOGOUT_ERROR"
when ever user is refreshing the Angular App on browser window, each of refresh action is considered as a login entries and this API response keep on increasing with log. How to prevent this and get the log only for Login & Logout entires.
Here is the configuration set in app.init.ts
import { KeycloakService } from 'keycloak-angular';
import {keycloakConfigs } from '../../assets/config/serverdetails.json';
export function initializeKeycloak(keycloak: KeycloakService): () => Promise<boolean> {
return () =>
keycloak.init({
config: {
url: keycloakConfigs.Url,
realm: keycloakConfigs.Realm,
clientId: keycloakConfigs.ClientId,
},
initOptions: {
onLoad: 'login-required',
checkLoginIframe: true,
checkLoginIframeInterval: 25
},
loadUserProfileAtStartUp: true
});
}

Maintain flask_login session in flutter

Soo...I have an app with flask backend and flutter frontend. It utilizes flask_login to manage users. Problem is - I don't know how to maintain session on client side. Flutter client gets response from server, but I don't see any token, or user_id inside.
So far, I've tried to parse responce, with no luck and I've used solution from How do I make an http request using cookies on flutter?
also, without success.
Server-side https://github.com/GreenBlackSky/COIN/blob/master/api_app/app/login_bp.py
Client-side https://github.com/GreenBlackSky/coin_web_client/blob/master/lib/session.dart
Maybe, using flask_login was not such a good idea after all..
Have you tried with the request_loader approach? You can log in from Flutter client using a url argument and the Authorization header. Quoting from the documentation,
For example, to support login from both a url argument and from Basic Auth using the Authorization header:
#login_manager.request_loader
def load_user_from_request(request):
# first, try to login using the api_key url arg
api_key = request.args.get('api_key')
if api_key:
user = User.query.filter_by(api_key=api_key).first()
if user:
return user
# next, try to login using Basic Auth
api_key = request.headers.get('Authorization')
if api_key:
api_key = api_key.replace('Basic ', '', 1)
try:
api_key = base64.b64decode(api_key)
except TypeError:
pass
user = User.query.filter_by(api_key=api_key).first()
if user:
return user
# finally, return None if both methods did not login the user
return None
If you don't want to use flask_login anymore, I would suggest flask_jwt_extended for your case. Note that authentication will be carried out using JWT tokens instead of sessions.
Basically, you would need to create three routes: one for creating access and refresh tokens when the user logged in, one for refreshing the expired access token with the refresh token and one for removing the tokens when the user logged out. Then you would protect your API endpoints with the #jwt_required decorators.
Please refer to the documentation for detailed implementation.

Keycloak - direct user link registration

I have set up a web application with Keycloak in my local machine. Since Im using Keycloak as SSO implementation, I want in my web app that whenever SIGNUP button is click, user is directed into the registration page, and not going through the LOGIN page.
This is the example URL directed to the registration form, however, it contains a tab_id that is generated randomly like a session id.
https://site.test/auth/realms/custom/login-actions/authenticate?client_id=test&tab_id=qIdW92Bvwmk
I read about this link
Yes, as long as you use the "registrations" instead of "auth" in the
end of login ( AuthorizationEndpoint ) URL
But my endpoint in https://site.test/auth/realms/custom/.well-known/openid-configuration cannot be modified.
You can change the button link to this format -
http://<domain.com>/auth/realms/<realm-name>/protocol/openid-connect/registrations?client_id=<client_id>&response_type=code&scope=openid email&redirect_uri=http://<domain.com>/<redirect-path>&kc_locale=<two-digit-lang-code>
The registration page is exposed via an openid-connect endpoint, accessible in the same way as the standard auth screen. To construct the correct URL you can simply replace openid-connect/auth in the URL with openid-connect/registrations from the .well-known auth endpoint.
authEndpoint.replace("openid-connect/auth","openid-connect/registrations");
Using this endpoint the user will be directed to the registration screen instead of the login screen.
It is not documented or exposed via .well-known/openid-configuration, but you can see it in the source code:
public static UriBuilder registrationsUrl(UriBuilder baseUriBuilder) {
UriBuilder uriBuilder = tokenServiceBaseUrl(baseUriBuilder);
return uriBuilder.path(OIDCLoginProtocolService.class, "registrations");
}
For Keycloak 17 this worked for me:
http://<mykeycloakdomain.com>/realms//protocol/openid-connect/registrations?client_id=<myclient_id>&response_type=code&scope=openid+email&redirect_uri=https%3A%2F%2Fmywebsiteurl.com&kc_locale=

Auth0 error after failed login attempt

I am using Auth0 to authenticate users by redirecting them to facebook.
But the problem I am facing is that if a user types in incorrect account credentials the first time and succeeds on the second attempt the redirect does not happen, instead it takes me to "Oops!, something went wrong" page with the following message:
"invalid_request: You probably pressed the back button or there is some issue with cookies, since we couldn't find your session. Try logging in again from the application and if the problem persist contact the administrator."
EDIT: I am using the below Auth0Lock code on the client side.
var lock = new Auth0Lock('<%= auth0.clientId %>', '<%= auth0.domain %>', {
//redirect mode
auth: {
redirectUrl: '<%= auth0.callback %>',
responseType: 'code',
params: {
scope: 'openid' // Learn about scopes: https://auth0.com/docs/scopes
}
},
autoclose: true,
theme: {
logo: 'https://xxxxxx/logo_orange.jpg'
},
languageDictionary: {
title: "test"
}
});
lock.on("unrecoverable_error",function(err) {
console.log(err);
});
lock.on("authorization_error",function(err) {
console.log(err);
});
Once I select Login with facebook I am redirected to facebook url that looks something like link
There if I enter the email/password incorrectly the first time the page refreshes and on the second try if I succeed,instead of taking me back to my app the auth0 generic error page => doc shows up with the error I mentioned at the top.On the server side passport seems to correctly authenticate the user.
PS: Chrome is taking me to a login page which has a login form on top and center but firefox just has login at the center of the page.For chrome if I use the top login form and has a failed login attempt on second successful attempt I am taken to my facebook page i.e no redirect happens.
There's at least one issue and that one is a Facebook problem. Their login page is showing two login forms:
The TOP form has an action equal to:
https://www.facebook.com/login.php?login_attempt=1&lwv=100
while the CENTER one has:
/login.php?login_attempt=1&next=https://www.facebook.com/v2.4/dialog/oauth?redirect_uri=https%3A%2F%2Flogin.eu.auth0.com%2Flogin%2Fcallback&state=[state]&response_type=code&client_id=[client_id]&ret=login&logger_id=1bf0be0d-4b64-43a6-b112-79a30100fa5b&lwv=100
This means that submitting the top form does not maintain enough information to be able to return back to your application. Now, there's still the issue of the Auth0 generic page being shown, but that one I'm unable to reproduce. If you think it's worthwhile, then do upload an HAR for review, even one where you strip all cookies might help.
Update:
Looked at the HAR, the second issue seems to be caused by an authentication request to Facebook that does not pass through Auth0. There's a request to your application, but that one does not complete an then there's this second request that will trigger the Auth0 error page.
Expected flow:
https://test.auth0.com/authorize
https://www.facebook.com/dialog/oauth
https://www.facebook.com/login.php (user authenticates here)
https://www.facebook.com/v2.8/dialog/oauth
https://test.auth0.com/login/callback
https://localhost:8080/callback
What's causing the error generic page, before your localhost request completes another request is issued:
https://www.facebook.com/v2.8/dialog/oauth
https://test.auth0.com/login/callback (generic error page shown here)
The error is caused because https://test.auth0.com/login/callback is called without first going through https://test.auth0.com/authorize to setup the authentication transaction state.
Given the request to your application localhost is marked as incomplete I would start looking in your code to see if there's any reason for that request to not complete.

Facebook OAuth 2.0 mechanism does not always redirect to redirect_uri when pressing cancel

I have an issue with the Facebook OAuth 2.0 mechanism. In principle all is working well, except for one thing: when a user is redirected to the page where he should authorize/permit the app but is clicking 'Cancel', about half of the time he is redirected to the page I specified in the redirect_uri (correct behaviour - so I redirect him to a page explaining why we need the permissions) and about half the time he is ending up on the FB homepage (wrong behaviour). I just can't figure out what I am doing wrong. This is roughly what I am doing:
window.fbAsyncInit = function()
{
FB.init({
appId : <appid>, // App ID
channelUrl : 'http://www.mydomain.com/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
// Additional initialization code here
FB.getLoginStatus(function(response)
{
//console.log('getLoginStatus response: ',response);
if (response.authResponse)
{
//user is already logged in and connected
top.location.href='http://apps.facebook.com/<appname>';
}
else
{
//app is not authorized or user is logged out
var redirectURL = 'http://www.facebook.com/dialog/oauth/?client_id='+client_id+'&scope='+scope+'&redirect_uri='+encodeURIComponent('http://apps.facebook.com/<appname>')+'&response_type=token';
top.location.href = redirectURL;
}
});
};
Any idea what I am doing wrong? As said in the opposite case, where the user does accept to authorize the app al works just fine. I am still working in sandbox mode and have not yet bought an SSL certificate which is why I am still referring everywhere to http instead of https.
Thanks!
P.S. This strange behaviour never happens when the user clicks 'Don\'t allow' when asking for optional permissions the following times the user accesses my app. For example, the user logs in for the first time and authorizes the app, but does not allow for the optional permissions. Facebook then redirects him to the redirect_uri and gives me an access_token, so I redirect the user to the app (so far so good). The next time when the user accesses the app, I detect that he has authorized the app, but that I don't have all the optional permissions I want, so I redirect him again to the OAuth 2.0 mechanism. This time the user AGAIN doesn't allow the optional permissions and Facebook ALWAYS redirects the user to the redirect_uri which is the expected behaviour.