Keycloak Capacitor Adapter - Auth Redirect Problem - ionic-framework

We are using Ionic Vue (5.4.0 - Vue3) with Capacitor and Keycloak as the Auth Provider. We have implemented the https://www.npmjs.com/package/keycloak-ionic Package which provides the Capacitor Adapter. We have set up the required deeplinks for both platforms and they are working. The app should authenticate the user in the system browser (capacitor-native adapter), save the tokens and reuse these tokens on the next appstart. It's working on android. On iOS the first startup is working but if i restart (terminating and starting again) i only see a blank screen. It's not redirecting into the secured content or showing the keycloak login page. I found out that the Safari Browser with the keycloak login is opened in the background. If i close this browser tab and start the app it's working by redirecting me to the keycloak login page.
May the browser with the opened keycloak instance be the problem?
I also tried the same with inappbrowster (capacitor adapter). The first start is working there also. If i restart the app the custom tab is opening the redirect url page without redirecting me to the secured content or to the keycloak login page.
Code Sample:
App.addListener('appUrlOpen', function (data: any) {
const slug = data.url.split('/kc1').pop()
// We only push to the route if there is a slug present
if (slug) {
router.push({ name: 'Overview' })
}
})
// init authentication
const initKeycloak = async () => {
const cachedKeycloak = new CacheUtil('keycloak')
const cachedKeycloakAccessToken = await cachedKeycloak.get('accessToken')
const cachedKeycloakRefreshToken = await cachedKeycloak.get('refreshToken')
const initOptions = { url: process.env.VUE_APP_AUTH_URL + '/auth', realm: 'mp', clientId: 'mobile', checkLoginIframe: false, onLoad: 'login-required', token: cachedKeycloakAccessToken, refreshToken: cachedKeycloakRefreshToken }
const keycloak = KeycloakIonic(initOptions)
keycloak.init({
adapter: 'capacitor-native',
pkceMethod:'S256',
onLoad: initOptions.onLoad as any,
redirectUri: process.env.VUE_APP_REDIRECT_URI
}).then((auth: any) => {
// auth and create app
if (!auth) {
console.log(auth)
} else {
const app = createApp(VueApp)
.use(IonicVue)
.use(router)
.use(store)
router.isReady().then(() => {
app.mount('#app')
})
}
}).catch((e: Error) => {
console.log('auth failed: ', e)
})
keycloak.onAuthSuccess = () => {
console.log('authenticated!')
// save tokens to device storage
cachedKeycloak.set('accessToken', keycloak.token)
cachedKeycloak.set('refreshToken', keycloak.refreshToken)
}
}
initKeycloak()

Related

Can't login by Goggle accounts connect or by Google auth API in Cypress 10x

Current behavior
I've tried to connect to Google account when my tested application redirects to Google accounts connect for let the end-user send emails by the application but I'm not able to do it not by Google Auth API according to your guidelines:
https://docs.cypress.io/guides/end-to-end-testing/google-authentication#Custom-Command-for-Google-Authentication
and not by cy.origin() from the UI.
In the first attempt by the API it's ignore of these authentication and popup the dialog to connect by google account as usually even all the credentials and token are valid and return 200 ok.
In the second attempt by cy.origin() it's keep to load the page after the redirect and always reach to timeout and yell about to increase the timeout even the page seems like it was fully loaded after a few seconds.
I've tried to increase the timeout to 90 seconds and use wait() before and after the redirect and look for some hidden iframes and tried every versa of google domain but nothing help.
it always return errors over there.
all the examples are below.
This is the error when trying to use cy.origin()::
Timed out after waiting 30000ms for your remote page to load on origin(s):
- https://google.com
A cross-origin request for https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fmail.google.com&include_granted_scopes=true&state=%7B%22redirectUri%22%3A%22https%3A%2F%2Fmyappurl.com%2Fapp%2Fpipeline%2F9some-token-here-b96b599154ac%3Ftab%3Doverview%22%2C%22clientToken%22%3A%mytokenishere-1234567890%22%7D&prompt=consent&response_type=code&client_id=1234567890-aehhht36f7a01d38bmsvvpjrh915i86v.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fmyredreictedappurl.com%2FusersManagerSrvGoogleLogin was detected.
A command that triggers cross-origin navigation must be immediately followed by a cy.origin() command:
cy.origin('https://google.com', () => {
<commands targeting https://accounts.google.com go here>
})
If the cross-origin request was an intermediary state, you can try increasing the pageLoadTimeout value in Users/myname/repos/myreponame/cypress.config.ts to wait longer.
Browsers will not fire the load event until all stylesheets and scripts are done downloading.
When this load event occurs, Cypress will continue running commands.[Learn more](https://on.cypress.io/origin)
Desired behavior
No response
Test code to reproduce
commands.ts
Cypress.Commands.add('loginByGoogleApi', () => {
cy.log('Logging in to Google')
cy.request({
method: 'POST',
url: 'https://www.googleapis.com/oauth2/v4/token',
body: {
grant_type: 'refresh_token',
client_id: Cypress.env('googleClientId'),
client_secret: Cypress.env('googleClientSecret'),
refresh_token: Cypress.env('googleRefreshToken'),
},
}).then(({ body }) => {
const { access_token, id_token } = body
cy.request({
method: 'GET',
url: 'https://www.googleapis.com/oauth2/v3/userinfo',
headers: { Authorization: `Bearer ${access_token}` },
}).then(({ body }) => {
cy.log(body)
const userItem = {
token: id_token,
user: {
googleId: body.sub,
email: body.email,
givenName: body.given_name,
familyName: body.family_name,
imageUrl: body.picture,
},
}
window.localStorage.setItem('googleCypress', JSON.stringify(userItem))
cy.visit('/')
})
})
})
test-file.cy.ts
it.only('Send email to a user - is shown in the activity', () => {
cy.loginByGoogleApi();
cy.get(loc.sideNavBar.buyersPipeline).should('be.visible').click();
cy.get(loc.pipelineBuyer.nameColumn)
.eq(4)
.should('be.visible')
.click({ force: true });
cy.get(loc.buyerDetails.basicCard).should('be.visible');
cy.get(loc.buyerDetails.timelineSendEmailIcon)
.should('be.visible')
.click();
cy.get('div[role="dialog"]').find('button.MuiButton-root').should('be.visible').click();
})
})
By cy.origin() by the UI:
test-file.cy.ts
it.only('Send email to a user - is shown in the activity', () => {
// cy.loginByGoogleApi();
cy.get(loc.sideNavBar.buyersPipeline).should('be.visible').click();
cy.get(loc.pipelineBuyer.nameColumn)
.eq(4)
.should('be.visible')
.click({ force: true });
cy.get(loc.buyerDetails.basicCard).should('be.visible');
cy.get(loc.buyerDetails.timelineSendEmailIcon)
.should('be.visible')
.click();
cy.get('div[role="dialog"]').find('button.MuiButton-root').should('be.visible').click();
cy.wait(5000);
cy.origin('https://accounts.google.com', () => {
cy.wait(5000);
expect(window.origin).contains('google.com')
cy.get('input[type="email"]', {timeout: 60000}).should('be.visible', {timeout: 60000}).type('111');
})
});
````
### Cypress Version
10.7.0
### Node version
v14.19.1
### Operating System
macOS Montery 12.3.1

Integration AspNet.Security.OpenId.Providers Steam authorization with reactive.js?

I have a ASP.Net Core 2.2 Web API which uses Steam login for authentication using this package.
My authentication looks like this:
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.LoginPath = "/Api/Login";
options.LogoutPath = "/Api/Logout";
})
.AddSteam(opt => { opt.CallbackPath = "/Home/SteamCallback"; opt.ApplicationKey = "XXXX"; });
I'm using this API with my react app and I want to login so I added this in my react project to login
Via Steam
And /api/login redirects user back to react's homepage:
[HttpGet("/api/login")]
public IActionResult Login(string provider="Steam")
{
return Challenge(new AuthenticationProperties { RedirectUri = "http://localhost:3000/" }, provider);
}
I know it's so stupid to try authorize like that but i dont have any idea how.
Also they say using JWT is not safe in here so I had to use cookies but could not handle how to pass logged data to react and fetch data successfully.

Firebase Facebook authentication : Malformed or expired auth credential

I'm working on a react native ios app using facebook authentication and firebase.
I created my facebook app, copied the secret keys to my firebase facebook auth mode, but when i'm trying to sign in with facebook credential using firebase I'm getting this error : The supplied auth credential is malformed or has expired.
I had a look at this issue : FB login - Firebase.Auth() Error: The supplied auth credential is malformed or has expired which is the quite similar to mine, but the answer didn't help me because my keys are the same in my facebook app configuration than in my firebase facebook auth mode.
Here is the code i'm using when the facebook auth button is pressed :
facebookLogin = () => {
LoginManager.logInWithPermissions(['public_profile', 'email'])
.then(
(result) => {
if (result.isCancelled) {
Alert.alert('Whoops!', 'You cancelled the sign in.');
} else {
AccessToken.getCurrentAccessToken()
.then((data) => {
const credential = firebase.auth.FacebookAuthProvider.credential(data.accessToken);
console.log(credential);
firebase.auth().signInWithCredential(credential)
.then(() => this.props.navigation.replace('Home'))
.catch((error) => {
console.log(error.message);
this.setState({ errorMessage: error.message })
});
});
}
},
(error) => {
Alert.alert('Sign in error', error);
},
);
};
I hope you guys can help me, maybe I mistook when I configured my facebook app.
Thank you in advance.
turns out Facebook Graph API is not supported by firebase yet check this out
the reason why Graph API is not supported

How to use Amazon Cognito Logout endpoint?

I am using AWS Cognito in my application.
While doing logout i am calling the Logout Endpoint.
But after doing logout, I am still able to generate the id-tokens using the old refresh token.
It means my logout endpoint is not working any more. I am saving the tokens in my local storage, And while doing the logout i am clearing the store manually.
My Question is: How to properly use the logout mechanism of AWS
Cognito?
I'm not sure which framework you are using, but I'm using Angular. Unfortunately there are different ways of using AWS Cognito and the documentation is not clear. Here is my implementation of the Authentication Service (using Angular):
- Note 1 - With using this sign in method - once you redirect the user to the logout url - the localhost refreshes automatically and the token gets deleted.
- Note 2 - You can also do it manually by calling: this.userPool.getCurrentUser().signOut()
import { Injectable } from '#angular/core'
import { CognitoUserPool, ICognitoUserPoolData, CognitoUser } from 'amazon-cognito-identity-js'
import { CognitoAuth } from 'amazon-cognito-auth-js'
import { Router } from '#angular/router'
const COGNITO_CONFIGS: ICognitoUserPoolData = {
UserPoolId: '{INSERT YOUR USER POOL ID}',
ClientId: '{INSERT YOUR CLIENT ID}',
}
#Injectable()
export class CognitoService {
userPool: CognitoUserPool
constructor(
private router: Router
) {
this.createAuth()
}
createAuth(): void {
// Configuration for Auth instance.
const authData = {
UserPoolId: COGNITO_CONFIGS.UserPoolId,
ClientId: COGNITO_CONFIGS.ClientId,
RedirectUriSignIn : '{INSERT YOUR COGNITO REDIRECT URI}',
RedirectUriSignOut : '{INSERT YOUR COGNITO SIGNOUT URI}',
AppWebDomain : '{INSERT YOUR AMAZON COGNITO DOMAIN}',
TokenScopesArray: ['email']
}
const auth: CognitoAuth = new CognitoAuth(authData)
// Callbacks, you must declare, but can be empty.
auth.userhandler = {
onSuccess: function(result) {
},
onFailure: function(err) {
}
}
// Provide the url and parseCognitoWebResponse handles parsing it for us.
const curUrl = window.location.href
auth.parseCognitoWebResponse(curUrl)
}
/**
* Check's if the user is authenticated - used by the Guard.
*/
authenticated(): CognitoUser | null {
this.userPool = new CognitoUserPool(COGNITO_CONFIGS)
// behind the scene getCurrentUser looks for the user on the local storage.
return this.userPool.getCurrentUser()
}
logout(): void {
this.router.navigate(['/logout'])
}
}

Move to another hbs in ember after the authentication is done

I have an app in which I have include a fb login.I am using ember-simple-auth for authorization and session manganement.I am able to authenticate the user and move to my "feed" hbs .The problem is when I open the app on another tab it is rendering the login page.How do I implement where if the user is authenticated it directly move to "feed" hbs.Similary to facebook,instagram where user login for the first time and after that they are redirect to feed page until they logout.
autheticator.js
const { RSVP } = Ember;
const { service } = Ember.inject;
export default Torii.extend({
torii: service('torii'),
authenticate() {
return new RSVP.Promise((resolve, reject) => {
this._super(...arguments).then((data) => {
console.log(data.accessToken)
raw({
url: 'http://example.com/api/socialsignup/',
type: 'POST',
dataType: 'json',
data: { 'access_token':'CAAQBoaAUyfoBAEs04M','provider':'facebook'}
}).then((response) => {
console.log(response)
resolve({
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
access_token: response.access_token,
// jscs:enable requireCamelCaseOrUpperCaseIdentifiers
provider: data.provider
});
}, reject);
}, reject);
});
}
});
router.js
import Ember from 'ember';
import config from './config/environment';
var Router = Ember.Router.extend({
location: config.locationType
});
Router.map(function() {
this.route('index',{path:'/'});
this.route("aboutus",{path:'/aboutus'});
this.route('feed',{path:'/feed'});
});
export default Router;
You need to use the application-route-mixin.js in the route that will be the first shown after login and authenticated-route-mixin.js for all the routes that need to be logged to see them. Check this example for further information.