angular-oauth2-oidc.cognito

阅读时长 30 分钟读完

Support for OAuth 2 and OpenId Connect (OIDC) in Angular.

angular-oauth2-oidc

Support for OAuth 2 and OpenId Connect (OIDC) in Angular.

Credits

Resources

Tested Environment

Successfully tested with the Angular 2 and 4 and its Router, PathLocationStrategy as well as HashLocationStrategy and CommonJS-Bundling via webpack. At server side we've used IdentityServer (.NET/ .NET Core) and Redhat's Keycloak (Java).

New Features in Version 2

  • Token Refresh for Implicit Flow by implementing "silent refresh"
  • Validating the signature of the received id_token
  • Providing Events via the observable events.
  • The event token_expires can be used togehter with a silent refresh to automatically refresh a token when/ before it expires (see also property timeoutFactor).

Additional Features

  • Logging in via OAuth2 and OpenId Connect (OIDC) Implicit Flow (where user is redirected to Identity Provider)
  • "Logging in" via Password Flow (where user enters his/her password into the client)
  • Token Refresh for Password Flow by using a Refresh Token
  • Automatically refreshing a token when/ some time before it expires
  • Querying Userinfo Endpoint
  • Querying Discovery Document to ease configuration
  • Validating claims of the id_token regarding the specs
  • Hook for further custom validations
  • Single-Sign-Out by redirecting to the auth-server's logout-endpoint

Breaking Changes in Version 2

  • The property oidc defaults to true.
  • If you are just using oauth2, you have to set oidc to false. Otherwise, the validation of the user profile will fail!
  • By default, sessionStorage is used. To use localStorage call method setStorage
  • Demands using https as OIDC and OAuth2 relay on it. This rule can be relaxed using the property requireHttps, e. g. for local testing.
  • Demands that every url provided by the discovery document starts with the issuer's url. This can be relaxed by using the property strictDiscoveryDocumentValidation.

Sample-Auth-Server

You can use the OIDC-Sample-Server mentioned in the samples for Testing. It assumes, that your Web-App runns on http://localhost:8080.

Username/Password: max/geheim

clientIds:

  • spa-demo (implicit flow)
  • demo-resource-owner (resource owner password flow)

redirectUris:

  • localhost:[8080-8089|4200-4202]
  • localhost:[8080-8089|4200-4202]/index.html
  • localhost:[8080-8089|4200-4202]/silent-refresh.html

Setup Provider for OAuthService

-- -------------------- ---- -------
------ - ----------- - ---- ----------------------
-----

-----------
  -------- - 
    -----
    -----------
    ---------------------
  --
  ------------- -
    -------------
    --------------
    -----
  --
  ---------- -
    ------------ 
  -
--
------ ----- --------- -
-

Using Implicit Flow

This section shows how to use the implicit flow, which is redirecting the user to the auth-server for the login.

Configure Library for Implicit Flow (using discovery document)

To configure the library you just have to set some properties on startup. For this, the following sample uses the constructor of the AppComponent which is called before routing kicks in.

-- -------------------- ---- -------
------------ --- --
------ ----- ------------ -

  ------------------- ------------- ------------- -
        
        -- --- -- --- --- -- -------- --- ---- -- ----- -----
        ----------------------------- - ---------------------- - --------------

        -- --- ----- --- --- --- -- --------- ---- ---- -- -- --- -----------
        -------------------------- - -----------

        -- --- --- ----- --- --- ----------- --- ------ ------ -------
        -- --- ----- ----- --- ------- -- ----- --- --- -- - ---------------- ---
        ----------------------- - ------- ------- ----- ---------

        -- --- ---- -- --- ----------- ---- --- -- -- --------- ------ --- -----
        ------------------------ - ------------------------------------------------------------
        
        -- ---- --------- -------- --- ---- --- -- ----- --- ----
        ------------------------------------------------- -- -

            -- ---- ------ ---- ----- -- ----- --- -------- ------ --- --- ----
            -- --- ----------- --------- --- ---- ---- -- --- -------
            -- -- ------ ---- --- ---- --- --- ----- ----
            -----------------------------      

        ---

  -

-

Configure Library for Implicit Flow (without discovery document)

When you don't have a discovery document, you have to configure more properties manually:

-- -------------------- ---- -------
------------ --- --
------ ----- ------------ -

  ------------------- ------------- ------------- -
        
        -- ---------
        -------------------------- - ------------------------------------------------------------------------------ --------------

        -- --- -- --- --- -- -------- --- ---- -- ----- -----
        ----------------------------- - ---------------------- - --------------

        -- --- ----- --- -------- --- ---- ---- -- -- --- -----------
        -------------------------- - -----------

        -- --- --- ----- --- --- ----------- --- ------ ------ -------
        ----------------------- - ------- ------- ----- ---------

        -- --- ---------- -- --- -------------- -- ------- -------------- -- --- ------- -------
        -- ------- -- ------------
        ---------------------------------------------

        -- -- ---- ------ --------------- --- --- --- --- ---- ------------- --------------- ----
        --------------------------- - -------------------------------------------------------------------------------

        -- ---- ------ ---- ----- -- ----- --- -------- ------ --- --- ----
        -- --- ----------- --------- --- ---- ---- -- --- -------
        -- -- ------ ---- --- ---- --- --- ----- ----
        -----------------------------      


  -

-

Home-Component (for login)

-- -------------------- ---- -------
------ - --------- - ---- ----------------
------ - ------------ - ---- ----------------------

------------
    ------------ --------------- 
--
------ ----- ------------- -
    
    ------------------- ------------- ------------- -
    -
    
    ------ ------- -
        -------------------------------------
    -
    
    ------ -------- -
        ---------------------------
    -
    
    ------ --- ------ -
        --- ------ - --------------------------------------
        -- --------- ------ -----
        ------ ------------------ 
    -
    
-
-- -------------------- ---- -------
--- --------------
    -----
-----
--- -------------
    ------ --------
-----

------- ---------- ------------ ------------------
    -----
---------
------- ---------- ------------ -------------------
    ------
---------

-----
    ----------------- --- ------- ----------
------

Validate id_token

You can hook in an implementation of the interface TokenValidator to validate the signature of the received id_token and its at_hash property. This packages provides two implementations:

  • JwksValidationHandler
  • NullValidationHandler

The former one validates the signature against public keys received via the discovery document (property jwks) and the later one skips the validation on client side.

In cases where no ValidationHandler is defined, you receive a warning on the console. This means that the library wants you to explicitly decide on this.

Calling a Web API with OAuth-Token

Pass this Header to the used method of the Http-Service within an Instance of the class Headers:

Refreshing a Token when using Implicit Flow

To refresh your tokens when using implicit flow you can use a silent refresh. This is a well-known solution that compensates the fact that implicit flow does not allow for issuing a refresh token. It uses a hidden iframe to get another token from the auth-server. When the user is there still logged in (by using a cookie) it will respond without user interaction and provide new tokens.

To use this approach, setup a redirect uri for the silent refresh:

Please keep in mind that this uri has to be configured at the auth-server too.

This file is loaded into the hidden iframe after getting new tokens. Its only task is to send the received tokens to the main application:

Please make sure that this file is copied to your output directory by your build task. When using the CLI you can define it as an asset for this. For this, you have to add the following line to the file .angular-cli.json:

To perform a silent refresh, just call the following method:

When there is an error in the iframe that prevents the communication with the main application, silentRefresh will give you a timeout. To configure the timespan for this, you can set the property siletRefreshTimeout (msec). The default value is 20.000 (20 seconds).

Automatically refreshing a token when/ before it expires

To automatically refresh a token when/ some time before it expires, you can make use of the event token_expires:

By default, this event is fired after 75% of the token's life time is over. You can adjust this factor by setting the property timeoutFactor to a value between 0 and 1. For instance, 0.5 means, that the event is fired after half of the life time is over and 0.33 triggers the event after a third.

Callback after successful login

There is a callback onTokenReceived, that is called after a successful login. In this case, the lib received the access_token as well as the id_token, if it was requested. If there is an id_token, the lib validated it.

-- -------------------- ---- -------
----------------------------
    ---------------- ------- -- -
        --
        -- ------ ---- --- ------- -- -------------
        -- ----- --- ---- -- ---- --- ---
        -- 
        --------------------- -----
        -----------------------
    -
---

Preserving State like the requested URL

When calling initImplicitFlow, you can pass an optional state which could be the requested url:

After login succeeded, you can read this state:

Custom Query Parameter

You can set the property customQueryParams to a hash with custom parameter that are transmitted when starting implicit flow.

Routing with the HashStrategy

If you are leveraging the LocationStrategy which the Router is using by default, you can skip this section.

When using the HashStrategy for Routing, the Router will override the received hash fragment with the tokens when it performs it initial navigation. This prevents the library from reading them. To avoid this, disable initial navigation when setting up the routes for your root module:

After tryLogin did its job, you can manually perform the initial navigation:

Another solution is the use a redirect uri that already contains the initial route. In this case the router will not override it. An example for such a redirect uri is

Events

Using Password-Flow

This section shows how to use the password flow, which demands the user to directly enter his or her password into the client.

Configure Library for Password Flow (using discovery document)

To configure the library you just have to set some properties on startup. For this, the following sample uses the constructor of the AppComponent which is called before routing kicks in.

Please not, that this configuation is quite similar to the one for the implcit flow.

-- -------------------- ---- -------
------------ --- --
------ ----- ------------ -

  ------------------- ------------- ------------- -
      
        -- --- ----- --- -------- --- ---- ---- -- -- --- -----------
        -------------------------- - ----------------------

        -- --- --- ----- --- --- ----------- --- ------ ------ -------
        -- --- ----------- ---- ---- ---- ------- - ------- ----- ---- ------- ---- --- ----- -------------- -- ---------
        ----------------------- - ------- ------- ----- ------- ----------------

        -- --- ---------- -- --- -------------- -- ------- -------------- -- --- ------- -------
        -- ------- -- ------------
        ---------------------------------------------

        -- --- - ----- ------
        -- ------ ---- ---- --- ----------- ---- ---- ------ --- ------ -- -------- - ------ ------- --------
        -- --- -------- ---------- ----- ---- --- -------- ---- --- ---- -- ---- ------- --- ----- - ------ ------
        -- ---- --- ---- ----- --- - --- ---- ---- -- --- -------- ------ --- --- -------- -- ------ -----------------
        -- ----- ---- - ----- ------- -- -- ---- -- ----- -- -------
        ----------------------------------- - ---------

        -- ---- --------- -------- --- ---- --- -- ----- --- ----
        --- --- - ---------------------------------------------------------------------------------------------
        ---------------------------------------------------- -- -
            -- -- ---- ---- --- ---- ----
        ---

  -

-

Configure Library for Password Flow (without discovery document)

In cases where you don't have an OIDC based discovery document you have to configure some more properties manually:

-- -------------------- ---- -------
------------ --- --
------ ----- ------------ -

  ------------------- ------------- ------------- -
      
        -- ---------
        ------------------------------- - -------------------------------------------------------------------------- 

        -- --- ---- ---- ---- --------
        -- ---- ------- -- --------- -- ---- --- -------- ---- ----- --- ------ ----
        -- ---- ------ ---- --- ------- -- ----- --- -- -------- ---- -- --- --- -------- ----
        -- -- --- ----- ---- ---- --- -- ----- ---- ----- --- ---- --- -- --- ----- ------ --- --- ---- ---- ----
        ---------------------------------- - -----------------------------------------------------------------------------

        -- --- ----- --- -------- --- ---- ---- -- -- --- -----------
        -------------------------- - ----------------------

        -- --- --- ----- --- --- ----------- --- ------ ------ -------
        ----------------------- - ------- ------- ----- ------- ----------------

        -- --- - ----- ------
        -- ------ ---- ---- --- ----------- ---- ---- ------ --- ------ -- -------- - ------ ------- --------
        -- --- -------- ---------- ----- ---- --- -------- ---- --- ---- -- ---- ------- --- ----- - ------ ------
        -- ---- --- ---- ----- --- - --- ---- ---- -- --- -------- ------ --- --- -------- -- ------ -----------------
        -- ----- ---- - ----- ------- -- -- ---- -- ----- -- -------
        ----------------------------------- - ---------

  -

-

Fetching an Access Token by providing the current user's credentials

-- -------------------- ---- -------
---------------------------------------------------- --------------------- -- -
          
      -- ------- ---- ----- --- ----
      ------ ------------------------------------

---------- -- -

      -- ----- --- ------ ---- ----
      --- ------ - --------------------------------------
      -- -------- --------------------------- ------------------- 
  
--

There is also a short form for fetching the token and loading the user profile:

Refreshing the current Access Token

Using the password flow you MIGHT get a refresh token (which isn't the case with the implicit flow by design!). You can use this token later to get a new access token, e. g. after it expired.

HomePage

https://github.com/manfredsteyer/angular-oauth2-oidc#readme

Repository

git+https://github.com/manfredsteyer/angular-oauth2-oidc.git

来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/6005606781e8991b448de8a4

纠错
反馈