GithubHelp home page GithubHelp logo

mauriciovigolo / keycloak-angular Goto Github PK

View Code? Open in Web Editor NEW
709.0 32.0 270.0 5.56 MB

Easy Keycloak setup for Angular applications.

License: MIT License

TypeScript 94.82% JavaScript 2.24% HTML 2.78% CSS 0.16%
angular keycloak-js keycloak-adapter keycloak

keycloak-angular's People

Contributors

0xhexe avatar 3lexw avatar aelkz avatar arekgotfryd avatar bcmedeiros avatar chrisvieweg avatar dependabot[bot] avatar fireblue45 avatar frankiepo avatar frederikprijck avatar gmolaire avatar jamesrweb avatar janloebel avatar jann-cc avatar jeddai avatar jmparra avatar jonkoops avatar konradtoenz avatar luchsamapparat avatar marcinmajkowski avatar mauriciovigolo avatar mawi137 avatar nbittich avatar osafi avatar sii-ggrebert avatar tdesjardins avatar twobiers avatar xhmikosr avatar youssef-aouichaoui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

keycloak-angular's Issues

Dropdown buttons do not work when you configure keycloak-angular

Drop down buttons and others component not working when configure keycloak-angular.

HTML example:

        <ul class="right hide-on-small-and-down">
          <li><a class="dropdown-button" href="#!" data-activates="dropdown1" data-beloworigin="true"><i class="material-icons left">account_circle</i>User</a>
            <ul id="dropdown1" class="dropdown-content">
              <li><a href="#!" class="cyan-text text-lighten-1"><i class="material-icons left">visibility</i>Ver perfil</a></li>
              <li><a href="#!" class="cyan-text text-lighten-1"><i class="material-icons left">exit_to_app</i>Salir</a></li>
            </ul>
          </li>
          <li><a href="#"><i class="material-icons">help_outline</i></a></li>
        </ul>

the configuration is correctly keycloak-angular but components stop working.
If I commet in app.module.ts

  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: initializer,
      multi: true,
      deps: [KeycloakService]
    }
  ],

the components work again, like the drop-down menu.

Any idea what is happening??

bearer interceptor being created before keycloak.init

Hello again,

I have just upgraded to 1.2.1, to get the new changes, hoping to fix the #4 issue, but now I'm facing a new one. This time I'm not sure where the problem is.

The KeycloakBearerInterceptor is constructed before my initialization code (keycloak.init()), where I define the bearerExcludedUrls option.

In the constructor we have this:

var excludedUrls = this.keycloak.getBearerExcludedUrls();
this.excludedUrlsRegex = excludedUrls.map(function (urlPattern) { return new RegExp(urlPattern, 'gi'); });

So the excludedUrlsRegex variable is set before my initialization function is called, and afterwards, during an intercept, the original, empty, excludedUrlsRegex is used.

Just to have something working, I have moved those two lines to the beginning of the intercept method, so it uses the latest this.keycloak.getBearerExcludedUrls().

Now... I'm kinda new to Angular2+, so maybe I have done something wrong on my side. What do you think? Is it possible to make my initialization code run before the construction of the interceptor?

Silent refresh for implicit flow

It would be also nice to expand the updateToken() function to also support the implicit flow. Currently it works only with a standard flow. It is recommended to use implicit flow with public clients such as and Angular SPA. Using implicit flow prevents keeping refresh token in a public application.

Silent refresh is usually implemented by the hidden iframe trick as is done in this library (https://manfredsteyer.github.io/angular-oauth2-oidc/angular-oauth2-oidc/docs/additional-documentation/refreshing-a-token-(silent-refresh).html). Auth0 also has an implementation for this and their code is also MIT licensed. (https://auth0.github.io/auth0.js/global.html#renewAuth)

Is it compatible with angular 5??

I'm guiding myselft through the example for implementing my usecase but I'm getting the same error again and again

Syntax error: Unexpected token <

I went through the code so many times that I really don't see nothing worng so, I want to ask if could be problem of using angular 5 instead of angular 4. Because just importing the KeycloakAngularModule gives me this error, only with that the app crushes

Is it possible to use a string in this form?

`const str = JSON.stringify( {
"realm": "test",
"auth-server-url": "http://localhost:8080/auth",
"ssl-required": "external",
"resource": "test",
"public-client": true,
"confidential-port": 0
});

await keycloak.init({
config: str ,
initOptions: {
onLoad: 'login-required', // redirects to the login page
checkLoginIframe: false
},
bearerExcludedUrls: [
'/assets',
'/clients/public'
],
});
resolve();
} catch (error) {}`

I get an error "GET http://localhost:4200/%7B%22realm%22:%22test%22,%22auth-server-url%22:%22http://localhost:8080/auth%22,%22ssl-required%22:%22external%22,%22resource%22:%22test%22,%22public-client%22:true,%22confidential-port%22:0%7D 404 (Not Found)" and "ERROR An error happened during Keycloak initialization."

kind of like config allows : "config?: string | KeycloakConfig;"

Add support for Keycloak authorization endpoints

Are there any plans to support the authorization endpoints of Keycloak. If we activate Policy Enforcement on an API Backend we need to convert the Access Bearer Token to a Requesting Party Token (RPT) in order to get authorized.

With keycloak there are two options:

Support changing Authorization Http Header name

Hi,
In our organization the token is expected to be in a different header than the standard 'Authorization'. Having support for changing the Http Header name as well would be helpful (similar to #45 ).

I have implemented this already and can submit the PR for consideration if this feature request is acceptable

Thanks

KeycloakService.addTokenToHeader needs to complete the observable

The keycloak service creates an observable when calling KeycloakService.addTokenToHeader, but does not call observer.complete() to message the subscribers that it's finished.

This changes the behavior of the angular httpClient methods (get, post, etc.)

As a workaround, we currently have to add a .take(1) (e.g. httpClient.get('protected/url')) to every http operation that is protected by keycloak. URLs that aren't protected work as expected.

I would propose a fix by adding observer.complete(); after this line.

observer.next(headers);

Question

Hey there!

I got a question: I am working on a web app with Docker + Angular2 + Java Backend + Keycloak. The library works fine! But I cannot figure out how to do the following:

I have a landing page, that should be unprotected, like: mydomain.de/home. Every visiter should land there if not logged in. If logged in, users should instead be redirected to mydomain.de/main. By logging out, back to mydomain.de/home. So the most natural thing there is. But when I initialize the app with keycloak (like described), I always end up in the keycloak login.

I know how to use AuthGuards and Router redirects in Angular, but I feel stuck, as I am already trying for hours.

Please help if you can.

Best,
Benjamin

Running tests locally produce errors

When I run the library's test locally, I get the following errors:

image

I guess I'm missing something but I can't find any information in the contribution file.

How to integrate or put keycloak.json?

Aloha,
I'm new to keycloak and i want to integrate this adapter to my angular 5.2.0 app.
I get GET http://localhost:4200/keycloak.json 404 and I can't found where i should my keycloak.json
What did I wrong?

Support for impersonate API

Hello @mauriciovigolo ,

IHAC that needed a NPM module to integrate with angular apps. So I've started designing my own keycloak module last year and we had some improvements in terms of using the impersonate-user API.

With this feature, we can be able to create a feature that can be used to simulate other keycloak users.
There is an excellent article about this feature: https://blog.softwaremill.com/who-am-i-keycloak-impersonation-api-bfe7acaf051a

I had designed a feature based on the following method signature:

Promise<boolean> KeycloakService.impersonate('7901ed55-af33-47f1-24a9-e197ra667afc')

Let me know if we can work a PR.

Add support for Angular 6

Environment:

  • keycloak-angular 1.3.0
  • Angular 6.0.0
  • RxJs 6.1.0

Description:
RxJs 6, included in Angular 6, has a few breaking changes one of which is a change in import paths.
When importing keycloak in an Angular 6 project, the following compile errors are thrown:

ERROR in node_modules/keycloak-angular/src/services/keycloak.service.d.ts(2,10): error TS2305: Module '"/code/node_modules/rxjs/Observable"' has no exported member 'Observable'.
node_modules/rxjs/Observable.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/Observable'.

The error can be patched with npm install rxjs-compat during the migration period.

This Issue is a request to support rxjs v6 without needing to install the rxjs-compat module.

Bearer in lowercase in authorization header

Hi,

In keycloak.service.ts our team discovered that the lowercase "bearer" in the authorisation header causes issues with Spring Web. I appreciate this is a fussy thing to point out, and can be fixed on the back-end, but the stricter standard "Bearer" tends to be used throughout in the RFC:
https://tools.ietf.org/html/rfc6750#section-2.1
https://tools.ietf.org/html/rfc6750#section-6.1.1

This is the line concerned:
https://github.com/mauriciovigolo/keycloak-angular/blob/master/src/services/keycloak.service.ts#L328

I couldn't find any other discussion related to this in the issue tracker. Could this be taken into consideration, to change "bearer" to "Bearer"?

Many thanks

Lack of id in KeycloakProfile object

Hello, first of all - your library is really great, thanks for your effort :)
To the point though:
I'm invoking loadUserProfile() so I can process KeycloakProfile but the result doesn't have id set - it's undefined all the time for me. All the other fields like email, firstname, lastname and even additional attributes set on my keycloak server are found - the only missing is id. By id I mean id set by keycloak itself eg: fb069cbd-689c-4108-8a0b-e03196eea53f. Do you know how can I get that id filled in KeycloakProfile returned from loadUserProfile()?

Cache the token

Is there a way to cache the Bearer in order to avoid another authentification after each page refresh ?

Support for multiple environments (external configuration keycloak.json i.e env. promotion)

Hello @mauriciovigolo ,

IHAC that needed a NPM module to integrate with angular apps. So I've started designing my own keycloak module last year and we had some improvements in terms of environment promotion using CI (jenkins).

With this feature, we can be able to externalize the keycloak configurations and easy integrate with a pre-built jenkins job to grab all configurations needed for a specific enviroment. Today we are working with local (development), test, pre-production and production.

The initial params are:
realm, auth-server-url, welcome-url, client-id, and so on..

// for example, allow the following:
$ ng build --env=prod

So, instead of publishing my project on github, I thought of sharing with you some ideas and contribute to this project.

Question about refreshToken concurrency

I have a question about the current implementation of this library.

Imagine the following situation:

  • The angular application starts an Http request (request A) using the HttpClient
  • Request A will be intercepted by the interceptor
  • Taken that the token is invalid, a new call will be made to refresh the token before its being added to the header
  • Before the token refresh is finished (the call to keycloak is still ongoing) a new Http request (request B) is made using the HttpClient
  • Request B will be intercepted by the interceptor
  • The token is not refreshed yet, so it's still expired and another call will be made to keycloak to refresh the token.
  • We now have a concurrency issue.

This is incorrect behavior. However, if I understand the source code correct, this is how the library currently works.

Are you interested to fix this? Coz I have a fix for this which I can contribute if u want, but it might require a few refactors in ur keycloak service.

If you are interested, maybe we can have a chat offline (skype, hangouts, gitter) .

interceptor keycloack does not work

I have a problem with the interceptor, it does not add the Authorization Bearer header, it adds it well for keycloack requests exepmle: http: // awl-si-cap-keycloack3: 8080 / auth / realms / realm / account
but not for my queries coming out of my application, example : getUser

Any suggestion. Thank you

Support For Keycloak 4.0 Beta

Howdy Howdy, this is probably more of a timing question. What does your timeline for releasing 4.0.X support? Is this different than the timing for the Angular 6 support work?


Given that i am a user who is working with the Keycloak 4.0.X Beta,
When i declare a version number OR Git repo / branch in package.json
Then i should be able to use keycloak-js 4.0.x beta AND Keycloak 4.0.X server

Make keycloak-js a peer dependency

Why is there a single hard-coded version of keycloak-js dependency? Would it be possible to make it a peer dependency so everyone can use whatever version they have on the server?

Or do new versions of keycloak-js work properly with older versions of Keycloak server?

Docs for PWA/mobile apps

We should think about adding an extension in the documentation on how to use keycloak-angular with PWA and Mobile applications. Since Keycloak have different behavior with such scenarios, it will be good to have a proper documentation for overall guidance.

Wrong typeof in definition

I think the config definition has an error:

The Keycloak init option has a param checkLoginIframeInterval with type boolean (https://github.com/mauriciovigolo/keycloak-angular/blob/master/src/interfaces/keycloak-init-options.ts#L53).

According to the original source code (https://github.com/keycloak/keycloak/search?utf8=%E2%9C%93&q=checkLoginIframeInterval&type=) has the same error. Use two type of checkLoginIframeInterval: boolean and number, I think this param needs to be a number type.

promises

hi, back-ender trying front end here.

is there any particular reason why this library returns promises everywhere, as opposed to the angular-preferred observable reactive flow?

it seems to me a lib specifically created for angular should also adopt the preferred async paradigm. trying to mix both is giving me headaches, as i'm not exactly familiar with javascript, and just recently started getting the hang of angular the typescript way.

I could be wrong ofc, could you elaborate?

Use direct access grant

i get token by direct access grant ,how to connect it with keycloak-angular,i am really confused

Add function to return the instance.tokenParsed

Thank you for your module!

I'd like access to the data contained in the Keycloak instance.tokenParsed. I can get at it via the KeycloakService.getKeycloakInstance function, but it'd be tidier if I could access it directly.

Right now I'm specifically after tokenParsed.email and tokenParsed.name, but the other fields could be useful in the future.

Would this something you'd be willing to add and/or would you like a pull request for this functionality? Is there a better way to access this information?

Cannot figure out how to get onAuthSuccess to fire?

Hi,
I need to log login and logout events so I'm using onAuthSuccess & onAuthLogout.

I cannot get onAuthSuccess to fire using keycloak.getKeycloakInstance().onAuthSuccess = ...

This approach works for onAuthLogout when I call clearToken().

I'm setting it like this:

keycloak.init(...).then(() => {
   // setting here
});

If I try to set before keycloak.init() the keycloak instance is not set.

I couldn't see any way to pass the callbacks into keycloak.init() as config options.

Any advice appreciated.

keycloak.init config that depends on another APP_INITIALIZER

Hello,
I have been trying to figure this out on my own for a while now.

I already have an APP_INITIALIZER that uses a service to fetch a config object from a .json file in the root of my project.
I want to use the config information loaded as part of the config for keycloak but I cannot get it to work.
I had an idea to run the keycloak.init inside the config service, and it works and allows me to login and see my app but then the request for the user info does not work, and when I check the console network tab I can see that the access headers are no longer present.
If I just go back to having two APP_INITILIZER's everything works and including the call to get the user details.

Has anyone got more experience than me with this issue?

Use userinfo endpoint for getting user info rather than the account client

After logging into an app using this plugin I can see that a request is made to the Keycloak account client to get information about the user, at /auth/realms/realm-name/account. I'd expect to get that information from the userinfo endpoint at http://localhost:28080/auth/realms/realm-name/protocol/openid-connect/userinfo instead. It looks like the information available at the two endpoints is pretty much the same, but there would be a few advantages to using the userinfo endpoint:

  • It's part of the OpenID connect spec, which might mean it's less likely to ever change.
  • It doesn't require any special setup, unlike the current way of doing things which requires the scope mappings for the client to be set up correctly.
  • It makes fewer assumptions about the Keycloak setup, for instance it's possible for a Keycloak server not to have the account client, or for users not to have the view-profile permission, in which case the current system won't work. This tripped me up as I had some users that were created manually and not given a sensible set of permissions. I've no idea if there's any legitimate reason to set up Keycloak in this way though.

onload: 'check-sso' not working without excludedUrls

Hi,

I found your library today and I wanted to thank you for the great work.

However, I encountered one problem that stops me from completing my work.

Short intro:
The main page has only two buttons: Login and Register. This page should be presented to the user first and only after either Login or Register has been pressed the browser should redirect to Keycloak to complete the flow.

1st try: I implement this using the help from tutorial page. The user was redirected immediately to the Keycloak, before the main page was shown. This is not the expected behavior.

2nd try: I changed keycloak config to look like this:
initOptions: { onLoad: 'check-sso', checkLoginIframe: false }. Nothing changed, the behavior is still the same as the 1st time.

3rd try: Now the keycloak config looks like this:
initOptions: { onLoad: 'check-sso', checkLoginIframe: false }, bearerExcludedUrls: [ '/' ]. Now, it shows main page and after clicking on one of the buttons it is redirected to keycloak. But, now, there is a problem: the authorization header won't be sent to any url. So if I try to send some data via HttpClient to, for example, '/get' or '/get/data' the authorization header will be NOT sent with the request.

Do you have any idea what could be the cause? Why is it necessary to give bearerExcludedUrls to avoid being redirected immediately to the keycloak?

Thank you!

UserService#getUserRoles is not merging the clientId roles

Issue type: Bug
Description:
The getUserRoles method from UserService is not merging the clientId roles and the realm roles when allRoles parameter is true, instead it is replacing the clientId roles with the realm roles.

Line: 190 from keycloak.service.ts

if (allRoles && this.instance.realmAccess) {
      roles = this.instance.realmAccess['roles'] || [];
}

Error building 1.2.0

I'm using Angular 4.4.6
and Angular-cli 1.4.9

during compilation time I have this error.

ERROR in Error: Metadata version mismatch for module /frontend/node_modules/keycloak-angular/index.d.ts, found version 4, expected 3, resolving symbol AppModule in /frontend/src/app/app.module.ts, resolving symbol AppModule in /frontend/src/app/app.module.ts

Issue with login using Google Chrome after closing and reopening

I'm using the onLoad: 'check-sso' and checkLoginIframe: true properties in configuration.

First time accessing the page the and calling login() I get redirected to keycloak login page.

Closing the Google Chrome and reopening seconds later user is not logged in, but calling login() shows quickly in browser url like http://#error=login_required&state=0f6d5811-c76a-4995-9e0a-142c90fa3ebd and get back to the application not logged in (neither redirected to login page).
Checking the keycloak cookies there is one KEYCLOAK_SESSION not expired. If I delete this cookie I can login on the application again.

In Firefox it's working (when reopen the browser after close get logged in).

Is possible to force keycloak to redirect to login page or clear this old session?

ERROR An error happened during Keycloak initialization

I'm trying to use

try {
  await keycloak.init({
    config: {
      url: 'https://xxxx.com/auth',
      realm: 'xxxxx',
      clientId: 'account',
      credentials: {
        secret: 'xxxxxx-980a-4588-a846-xxxxxxx'
      }
    },
    initOptions: {
      onLoad: 'login-required',
      checkLoginIframe: false
    },
    bearerExcludedUrls: [
      '/assets'
    ]
  });
  resolve();
} catch (error) {
  reject(error);
}

in the browser see this error:

ERROR An error happened during Keycloak initialization.         core.js:1448
defaultErrorLogger                    core.js:1448
ErrorHandler.prototype.handleError    core.js:1509
_callAndReportToErrorHandler/</<      core.js:5682:54
ZoneDelegate.prototype.invoke         zone.js:388
Zone.prototype.run                    zone.js:138
NgZone.prototype.runOutsideAngular    core.js:4697:47
_callAndReportToErrorHandler/<        core.js:5682
ZoneDelegate.prototype.invoke         zone.js:388
onInvoke                              core.js:4749
ZoneDelegate.prototype.invoke         zone.js:387
Zone.prototype.run                    zone.js:138
scheduleResolveOrReject/<             zone.js:858
ZoneDelegate.prototype.invokeTask     zone.js:421
onInvokeTask                          core.js:4740
ZoneDelegate.prototype.invokeTask     zone.js:420
Zone.prototype.runTask                zone.js:188
drainMicroTaskQueue                   zone.js:595
ZoneTask.invokeTask                   zone.js:500
invokeTask                            zone.js:1517
globalZoneAwareCallback               zone.js:1543

also:

Pedido de origen cruzado bloqueado: La política de mismo origen no permite leer el recurso remoto en https://xxxxx.com/auth/realms/xxxx/protocol/openid-connect/token. (Razón: encabezado CORS 'Access-Control-Allow-Origin' faltante).

this causes that the web does not load.

Error: KeycloakAngularModule is not an NgModule

Hi,

First of all tx for publising this lib! Very useful.
I get following error while compiling my app.
As a workaround I copied the keycloak module declarations and providers to my app module.
That seems to work fine.
I inspected your code, the keycloak module has the @NgModule decorator. So I guess something went wrong with the publishing of the lib?

ERROR in Error: KeycloakAngularModule is not an NgModule
    at _getNgModuleMetadata (C:\Users\Jasper\git\fmsb-ccare\node_modules\@angular\compiler-cli\src\ngtools_impl.js:140:15)
    at _extractLazyRoutesFromStaticModule (C:\Users\Jasper\git\fmsb-ccare\node_modules\@angular\compiler-cli\src\ngtools_impl.js:109:26)
    at C:\Users\Jasper\git\fmsb-ccare\node_modules\@angular\compiler-cli\src\ngtools_impl.js:129:27
    at Array.reduce (native)
    at _extractLazyRoutesFromStaticModule (C:\Users\Jasper\git\fmsb-ccare\node_modules\@angular\compiler-cli\src\ngtools_impl.js:128:10)
    at Object.listLazyRoutesOfModule (C:\Users\Jasper\git\fmsb-ccare\node_modules\@angular\compiler-cli\src\ngtools_impl.js:53:22)
    at Function.NgTools_InternalApi_NG_2.listLazyRoutes (C:\Users\Jasper\git\fmsb-ccare\node_modules\@angular\compiler-cli\src\ngtools_api.js:91:39)
    at AotPlugin._getLazyRoutesFromNgtools (C:\Users\Jasper\git\fmsb-ccare\node_modules\@ngtools\webpack\src\plugin.js:207:44)
    at _donePromise.Promise.resolve.then.then.then.then.then (C:\Users\Jasper\git\fmsb-ccare\node_modules\@ngtools\webpack\src\plugin.js:443:24)
    at process._tickCallback (internal/process/next_tick.js:109:7)
webpack: Failed to compile.

Authorization header not excluded sometimes

Hi,
Thanks for creating this excellent module.
I'm new to Angular so apologies if this is not an issue and just me being an idiot.

I'm having a problem excluding the Authorization header in my requests.
(preflight fails when Authorization header is included so I need it removed).

I've modified the given keycloak-heroes example to replicate my problem.
I've added a span with on click event in the home component which calls HeroesService which makes a POST request to the URL I want excluded.
I've also updated app-init.js with my url/realm/clientId and added the URL I want excluded.

Problem is the Authorization header is being included sometimes.
First time I click the element - no Authorization header - second time Authorization header - third time no header etc..

I tried latest v1.2.3 and also tried various regex with the excluded URL but no luck.

If I remove keycloak from the providers in app.modules.ts the code works fine - as a test just in case it's my lack of Angular causing the issue.

Here's the changes I made so you can see what I'm talking about.

home.component.html:

I just added a span before the final div:

<span (click)="test()">TEST</span>

home.component.ts:

  test() {
    this.heroesService.graphQl('some query').subscribe((r) => { console.log(r); });
  }

heroes.service.ts:

  graphQl(query): any {
    const headers = new HttpHeaders({
      'X-COMPANY-API-Key' : 'xxx',
      'Content-Type' : 'application/json'
    });
    const options = { headers: headers };
    return this.http.post('https://api.COMPANY.com/graphql', query, options);
  }

app-init.ts:

  config: {
    url: 'https://login.COMPANY.com/auth/',
    realm: 'COMPANY-REALM',
    clientId: 'COMPANY-CLIENTID'
  },
  initOptions: {
    onLoad: 'login-required',
    checkLoginIframe: false
  },
  bearerExcludedUrls: [
    'https://api.COMPANY.com/graphql'
  ]

Access Tokens for Service Account

Hello,
Thanks for all of your work on this project.

I have not been able to figure out how to use the credentials in the init to secure an access token for my service account.

I have set up the application and tested it with a user. That works great! I get redirected to the login page and back to the app with an access token. However, when I try setting

const keycloakConfig: KeycloakConfig = { url: 'http://keycloak:8180/auth/', realm: 'survey', clientId: 'surveyUi', credentials: { secret: 'abcdefg123456' }, };
and
try { await keycloak.init({ config: environment.keycloak, initOptions: { onLoad: 'check-sso', checkLoginIframe: false }, bearerExcludedUrls: [] }); resolve(); } catch (error) { reject(error); } }); };

I still get redirected, but to an error page.

Is there a way to have it POST to
URL: http://keycloak:8180/auth/realms/survey/protocol/openid-connect/token
HEADERS: "Authorization: Basic 1a2b3c4d.a0ejfaslkjasdfd"
"Content-Type: application/x-www-form-urlencoded"
BODY: grant_type=client_credentials

Thank you
Matthew

account: Response for preflight has invalid HTTP status code 404.

I'm getting the following error when trying to login to the application.

meukeyloack/auth/realms/meurealm/account Failed to load resource: the server responded with a status of 404 (Not Found)
localhost/:1 Failed to load https://meukeyloack/auth/realms/meurealm/account: Response for preflight has invalid HTTP status code 404.

INIT:

import { KeycloakService } from 'keycloak-angular';

export function initializer(keycloak: KeycloakService): () => Promise {
return (): Promise => {
return new Promise(async (resolve, reject) => {
try {
await keycloak.init({
config: {
url: 'https://meukeyloack/auth',
realm: 'meurealm',
clientId: 'frontline2'
},
initOptions: {
onLoad: 'login-required',
checkLoginIframe: false,
},
bearerExcludedUrls: [
'/teste'
],
});
resolve();
} catch (error) {
reject(error);
}
});
};
}

Package
"dependencies": {
"@angular/animations": "^5.2.0",
"@angular/common": "^5.2.0",
"@angular/compiler": "^5.2.0",
"@angular/core": "^5.2.0",
"@angular/forms": "^5.2.0",
"@angular/http": "^5.2.0",
"@angular/platform-browser": "^5.2.0",
"@angular/platform-browser-dynamic": "^5.2.0",
"@angular/router": "^5.2.0",
"bootstrap": "^4.0.0",
"core-js": "^2.4.1",
"jquery": "^3.3.1",
"keycloak-angular": "^1.2.5",
"mydatepicker": "^2.6.3",
"popper.js": "^1.14.1",
"rxjs": "^5.5.6",
"zone.js": "^0.8.19"
},

Promise never gets called

When using the HttpClient Observable.toPromise() the promise is never called.

Workaround: Do not use toPromise(), but subscribe on the Observable instead.

Dealing with expired token

How does this library deal with expired Keycloak token? Does it automatically redirect user to the login screen again?

Profiles is a mandatory?

Is the following configuration mandatory?

When requesting the method to get the User's Profile, the client app should have the scope and access to the account view-profile role. To do it, access Clients arrow_right My-app arrow_right Scope. Select the account app in Client Roles and assign the view-profile role.

I do not intend to work with the account setup page, but without that I'm having trouble using the library.

New versioning proposal

We are working on the next release and found some issues regarding what's the best way to version the keycloak-angular library, considering breaking changes in Angular and Keycloak versions.

The new proposal is presented in:

Please if someone sees any problem regarding this new versioning proposal, help us sharing your thoughts. 💭 😄

--- EDIT ---

In Summary

keycloak-angular Angular Keycloak SSO-RH
4.x.x 4 (keycloak latest version) / 4 -
4.x.x-k3 4 3 7
5.x.x 5 (keycloak latest version) / 4 -
5.x.x-k3 5 3 7
6.x.x 6 (keycloak latest version) / 4 -
6.x.x-k3 6 3 7
  • keycloak-angular X.X.X: will be compatible with the latest version of keycloak, at the moment of this writing is keycloak 4 or the future release of SSO-RH based on keycloak 4.
  • keycloak-angular X.X.X-k3: will be compatible with keycloak 3 and SSO-RH 7.

Error: bearerExcludedUrls ignored

Hello there,

found a little bug. My bearerExcludedUrls option was being ignored, and the problem was in the KeycloakBearerInterceptor.

Had to change from

var addHeader = excludedUrls.find(function (urlPattern) {
    return /urlPattern/gi.test(urlRequest);
});

to

var addHeader = excludedUrls.find(function (urlPattern) {
    return new RegExp(urlPattern, 'gi').test(urlRequest);
});

Before, the code was always comparing with the pattern 'urlPattern', not the variable urlPattern... which returned always false....

Want me to do a PR or something?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.