Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to initialize keycloak with locale in i18n Angular app? #72

Closed
kashpatel opened this issue Jun 1, 2018 · 7 comments
Closed

How to initialize keycloak with locale in i18n Angular app? #72

kashpatel opened this issue Jun 1, 2018 · 7 comments

Comments

@kashpatel
Copy link

##Question or Feature Request

I know this might not be the best place for this question but just wondering if someone has encountered this problem? Since I could not find any solution online.

We use keycloak [https://www.keycloak.org/] server for user authentication in our Angular 6 app. We also use this wrapper library https://github.com/mauriciovigolo/keycloak-angular to interact with the underneath JavaScript keycloak Adapter and initialization.

Keycloak is the first thing in the app that gets initialized (from provided configuration) via Angular's APP_INITIALIZER provider.

Since we use Angular with internationalization and ahead of time compilation, we have deployed our apps like this:

https://my-site/en
https://my-site/fr

I want to render login page in respective locale when navigated. If navigated to my-site/fr keycloak login page should render in french and so on. But there is no way to provide locale in keyclaok config while app initialization.

PS: Keycloak realm is already configured to allow internationalization and user can change language from login page. I know keycloak adapter's login method takes "locale" param but I can only access that after app has been initialized.

Has anyone encountered this problem?

Thank you

@mauriciovigolo
Copy link
Owner

mauriciovigolo commented Jun 6, 2018

@kashpatel, one option could be initialize the KeycloakService but not redirect to the login page when calling the init method. This is similar to the keycloak-events example. Just a note, the example is not finished but you can take a look on how the app is dealing with the login workflow.

Then you have two options, depending on your use case:

  1. Instantly redirect to the login page, prior showing any page. In this case, calling the login method from KeycloakService would redirect the user to the login page. If in the login there is a locale, maybe it would handle it.
  2. Show a home page, for example, and then the user needs to access a secure content, the app should call the login method for authentication, similiar to number 1.

After login the keycloak will redirect to the origin url (/en, /fr, .. ).

If this suggestion doesn't not helps you, please let me know then we may think for another options.

@kashpatel
Copy link
Author

kashpatel commented Jun 8, 2018

Hey @mauriciovigolo,

Thank you for getting back to me and sorry for late reply. I tried doing exactly you told but now I got the following error.

https://localhost/auth/realms/realm/account 401 (Unauthorized)
ERROR Error: Uncaught (in promise): The user profile could not be loaded.

So, I followed your previous comment from this issue: #37 and added 'view-profile' role in to myapp's account but still no luck.

Here is the snapshot of code I am using:

keycloak.keycloakEvents$.subscribe(event => {
    if (!keycloak.isLoggedIn) {
       keycloak.getKeycloakInstance().login({ locale: 'fr' });
    }
});
 await keycloak.init({
      config: keyCloakConfig,
      initOptions: {
          onLoad: 'check-sso',
         checkLoginIframe: false
 } });

Thanks a lot for this amazing library and have a great weekend.

@mauriciovigolo
Copy link
Owner

Hi @kashpatel, do you have an example to share, so I think it would be easier to help you.
I could also try to implement an example with internationalization, but I still have some issues to deal before.
Thanks!!

@kashpatel
Copy link
Author

Hi @mauriciovigolo,

I will get on it as soon as I get time. Have been busy lately.

Thanks

@kashpatel
Copy link
Author

kashpatel commented Jun 15, 2018

Hey @mauriciovigolo,

Here is how I accomplished redirecting to login page based on site's @LOCALE_ID.

export function Initializer(
    keycloakService: KeycloakService,
    authService: AuthService
): () => Promise<any> {
    return (): Promise<any> => {
        return new Promise(async (resolve, reject) => {
            try {
                /** this is one time subscription only, if we do not unsubscribe app would go in infinite redirect loop **/
           
                const subscription = keycloakService.keycloakEvents$.subscribe(
                    (event: KeycloakEvent) => {
                        if (
                            event.type === KeycloakEventType.OnReady &&
                            !event.args.authenticated
                        ) {
                            keycloakService
                                .getKeycloakInstance()
                                .login(<KeycloakLoginOptions>{
                                    locale: authService.getLocale()
                                })
                                .success(() => {
                                    resolve();
                                    subscription.unsubscribe();
                                });
                        } else {
                            resolve();
                            subscription.unsubscribe();
                        }
                    }
                );
                await keycloakService.init({
                    config: authService.getKeyCloakConfig()                 
                });
            } catch (error) {
                reject(error);
            }
        });
    };
}

None of this would work if you use 'login-required' because keycloak-js does the internal redirect.
See here:

initOptions: {
     onLoad: 'login-required'
}

Hope that helps someone!

@mauriciovigolo
Copy link
Owner

Thanks @kashpatel, nice work! To help others I will also create a new example with this scenario.

@almahdi-chihaoui
Copy link

almahdi-chihaoui commented Feb 12, 2019

Hi,
I am having this same issue with Keycloak where i try to initialize it with locale from i18n, but in our application, we are using React. I tried to use login() after init and i had the redirection loop issue.
I know this is not the same context since I am using React, is there any way i can use your code to solve this issue.
Here is what i am using:

const kc = Keycloak(keycloakConfig); kc.init(); kc.login({ locale: ['fr'], }).success((authenticated) => { if (authenticated) { ReactDOM.render( <App kcRole={kc.tokenParsed.realm_access.roles} />, document.getElementById('App'), ); } });

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants