@axa-fr/vanilla-oidc

中文文档
6.25.6发布于 2023/07/24MITTypeScriptESM + CJS近 30 天下载 1989

OpenID Connect & OAuth authentication using native javascript only, compatible with angular, react, vue, svelte, next, etc.

原始使用文档
文档目录7 节
  1. About
  2. Getting Started
  3. Configuration
  4. Run The Demo
  5. How It Works
  6. Hash route
  7. Service Worker Support

@axa-fr/vanilla-oidc

Continuous Integration Quality Gate Reliability Security Code Corevage Twitter

Try the demo at https://icy-glacier-004ab4303.2.azurestaticapps.net/

About

@axa-fr/vanilla-oidc is a pure OIDC client library agnostic to any framework. It is used by @axa-fr/react-oidc and can be used by any framework.

It is a real alternative to existing oidc-client libraries.

  • Secure :
    • With the use of Service Worker, your tokens (refresh_token and access_token) are not accessible to the JavaScript client code (big protection against XSRF attacks)
    • OIDC using client side Code Credential Grant with PKCE only
  • Lightweight
  • Simple :
    • refresh_token and access_token are auto refreshed in background
    • with the use of the Service Worker, you do not need to inject the access_token in every fetch, you have only to configure OidcTrustedDomains.js file
  • No cookies problem : You can disable silent signin (that internally use an iframe). For your information, your OIDC server should be in the same domain of your website in order to be able to send OIDC server cookies from your website via an internal IFRAME, else, you may encounter COOKIES problem.
  • Multiple Authentication :
    • You can authenticate many times to the same provider with different scope (for example you can acquire a new 'payment' scope for a payment)
    • You can authenticate to multiple different providers inside the same SPA (single page application) website
  • Flexible :
    • Work with Service Worker (more secure) and without for older browser (less secure)

The service worker catch access_token and refresh_token that will never be accessible to the client.

Getting Started

npm install @axa-fr/vanilla-oidc --save

# If you have a "public" folder, the 2 files will be created :
# ./public/OidcServiceWorker.js <-- will be updated at each "npm install"
# ./public/OidcTrustedDomains.js <-- won't be updated if already exist

If you need a very secure mode where refresh_token and access_token will be hide behind a service worker that will proxify requests. The only file you should edit is "OidcTrustedDomains.js".

// OidcTrustedDomains.js

// Add bellow trusted domains, access tokens will automatically injected to be send to
// trusted domain can also be a path like https://www.myapi.com/users,
// then all subroute like https://www.myapi.com/useers/1 will be authorized to send access_token to.

// Domains used by OIDC server must be also declared here
const trustedDomains = {
  default: ["https://demo.duendesoftware.com", "https://www.myapi.com/users"],
};

The code of the demo :

import { VanillaOidc } from '@axa-fr/vanilla-oidc'

export const configuration = {
    client_id: 'interactive.public.short',
    redirect_uri: window.location.origin + '/#/authentication/callback',
    silent_redirect_uri: window.location.origin + '/#/authentication/silent-callback',
    scope: 'openid profile email api offline_access',
    authority: 'https://demo.duendesoftware.com',
    service_worker_relative_url:'/OidcServiceWorker.js',
    service_worker_only: false,
};

const href = window.location.href;
const vanillaOidc = VanillaOidc.getOrCreate(() => fetch)(configuration);

console.log(href);

vanillaOidc.tryKeepExistingSessionAsync().then(() => {
    if(href.includes(configuration.redirect_uri)){
        vanillaOidc.loginCallbackAsync().then(()=>{
            window.location.href = "/";
        });
        document.body.innerHTML = `<div>
            <h1>@axa-fr/vanilla-oidc demo</h1>
            <h2>Loading</h2>
        </div>`;
        return
    }

    let tokens = vanillaOidc.tokens;

    if(tokens){

        // @ts-ignore
        window.logout = () =>  vanillaOidc.logoutAsync();
        document.body.innerHTML = `<div>
            <h1>@axa-fr/vanilla-oidc demo</h1>
            <button onclick="window.logout()">Logout</button>
            <h2>Authenticated</h2>
            <pre>${JSON.stringify(tokens,null,'\t')}</pre>
        </div>`
        
    }
    else {
        // @ts-ignore
        window.login= () =>  vanillaOidc.loginAsync("/");
        document.body.innerHTML = `<div>
            <h1>@axa-fr/vanilla-oidc demo</h1>
            <button onclick="window.login()">Login</button>
        </div>`
    }
})


Configuration

const configuration: {
    client_id: PropTypes.string.isRequired, // oidc client id
    redirect_uri: PropTypes.string.isRequired, // oidc redirect url
    silent_redirect_uri: PropTypes.string, // Optional activate silent-signin that use cookies between OIDC server and client javascript to restore sessions
    silent_login_uri: PropTypes.string, // Optional, route that trigger the signin
    silent_login_timeout: PropTypes.number, // Optional default is 12000 milliseconds
    scope: PropTypes.string.isRequired, // oidc scope (you need to set "offline_access")
    authority: PropTypes.string.isRequired,
    storage: Storage, // Default sessionStorage, you can set localStorage but it is less secure to XSS attacks
    authority_configuration: PropTypes.shape({
      // Optional for providers that does not implement OIDC server auto discovery via a .wellknowurl
      authorization_endpoint: PropTypes.string,
      token_endpoint: PropTypes.string,
      userinfo_endpoint: PropTypes.string,
      end_session_endpoint: PropTypes.string,
      revocation_endpoint: PropTypes.string,
      check_session_iframe: PropTypes.string,
      issuer: PropTypes.string,
    }),
    refresh_time_before_tokens_expiration_in_second: PropTypes.number, // default is 120 seconds
    service_worker_relative_url: PropTypes.string,
    service_worker_only: PropTypes.boolean, // default false
    service_worker_convert_all_requests_to_cors: PropTypes.boolean, // force all requests that servie worker upgrades to have 'cors' mode. This allows setting authentication token on requests initialted by html parsing(e.g. img tags, download links etc).
    extras: StringMap | undefined, // ex: {'prompt': 'consent', 'access_type': 'offline'} list of key/value that are send to the oidc server (more info: https://github.com/openid/AppAuth-JS)
    token_request_extras: StringMap | undefined, // ex: {'prompt': 'consent', 'access_type': 'offline'} list of key/value that are send to the oidc server during token request (more info: https://github.com/openid/AppAuth-JS)
    withCustomHistory: PropTypes.function, // Override history modification, return instance with replaceState(url, stateHistory) implemented (like History.replaceState())
    authority_time_cache_wellknowurl_in_second: 60 * 60, // Time to cache in second of openid wellknowurl, default is 1 hour
    authority_timeout_wellknowurl_in_millisecond: 10000, // Timeout in millisecond of openid wellknowurl, default is 10 seconds, then error is throwed
    monitor_session: PropTypes.boolean, // Add OpenId monitor session, default is false (more information https://openid.net/specs/openid-connect-session-1_0.html), if you need to set it to true consider https://infi.nl/nieuws/spa-necromancy/
    onLogoutFromAnotherTab: Function, // Optional, can be set to override the default behavior, this function is triggered when user with the same subject is logged out from another tab when session_monitor is active
    onLogoutFromSameTab: Function, // Optional, can be set to override the default behavior, this function is triggered when user is logged out from same tab when session_monitor is active
    token_renew_mode: PropTypes.string, // Optional, update tokens base on the selected token(s) lifetime: "access_token_or_id_token_invalid" (default), "access_token_invalid" , "id_token_invalid"
    logout_tokens_to_invalidate : Array<string> // Optional tokens to invalidate during logout, default: ['access_token', 'refresh_token']
  };

Run The Demo

git clone https://github.com/AxaGuilDEv/react-oidc.git
cd react-oidc/packages/vanilla-demo
npm install
npm start
# then navigate to http://localhost:3000

How It Works

This component is a pure vanilla JS OIDC client library agnostic to any framework. It is a real alternative to existing oidc-client libraries.

More information about OIDC

Hash route

vanilla-oidc work also with hash route.

export const configurationIdentityServerWithHash = {
  client_id: "interactive.public.short",
  redirect_uri: window.location.origin + "#authentication-callback",
  silent_redirect_uri:
    window.location.origin + "#authentication-silent-callback",
  scope: "openid profile email api offline_access",
  authority: "https://demo.duendesoftware.com",
  refresh_time_before_tokens_expiration_in_second: 70,
  service_worker_relative_url: "/OidcServiceWorker.js",
  service_worker_only: false,
};

Service Worker Support

  • Firefox : tested on Firefox 98.0.2
  • Chrome/Edge : tested on version upper to 90
  • Opera : tested on version upper to 80
  • Safari : tested on Safari/605.1.15

版本与发布记录

@axa-fr/vanilla-oidc 共发布 317 个版本,首次发布于 2019/03/08;过去 12 个月发布了 0 个版本。

版本发布日期距今
6.25.6latest2023/07/243 年前
6.25.52023/07/243 年前
6.25.42023/07/243 年前
6.25.4-alpha.9672023/07/243 年前
6.25.4-alpha9522023/07/233 年前
6.25.3-alpha9502023/07/233 年前

关于 @axa-fr/vanilla-oidc 的常见问题

@axa-fr/vanilla-oidc 是什么?

OpenID Connect & OAuth authentication using native javascript only, compatible with angular, react, vue, svelte, next, etc.

如何安装 @axa-fr/vanilla-oidc?

在项目目录运行 npm install @axa-fr/vanilla-oidc,或使用 pnpm add / yarn add / bun add。

@axa-fr/vanilla-oidc 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@axa-fr/vanilla-oidc 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@axa-fr/vanilla-oidc 可以商用吗?

@axa-fr/vanilla-oidc 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@axa-fr/vanilla-oidc 的下载量有多少?

根据 npm 官方下载统计,@axa-fr/vanilla-oidc 在 2026/10/08 – 2026/11/06 这 30 天内被下载 1,989 次,日均约 66 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@axa-fr/vanilla-oidc 还在维护吗?

最新版本 6.25.6 发布于 2023/07/24(3 年前);至今共发布 317 个版本,其中过去 12 个月发布了 0 个;首次发布于 2019/03/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。