npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@authok/authok-vue

v1.0.2

Published

Vue 的 Authok SDK, 基于 PKCE授权码流程

Downloads

5

Readme

@authok/authok-vue

Authok SDK for Vue 3 Applications using Authorization Code Grant Flow with PKCE.

⚠️ For integrating Authok with a Vue 2 application, please read the Vue 2 Tutorial.

Stage: Stable Release CircleCI codecov License

内容

文档

安装

使用 npm:

npm install @authok/authok-vue

使用 yarn:

yarn add @authok/authok-vue

快速开始

Authok 配置

Authok 管理后台 创建一个 单页面应用(SPA).

If you're using an existing application, verify that you have configured the following settings in your Single Page Application:

  • Click on the "Settings" tab of your application's page.
  • Ensure that "Token Endpoint Authentication Method" under "Application Properties" is set to "None"
  • Scroll down and click on the "Show Advanced Settings" link.
  • Under "Advanced Settings", click on the "OAuth" tab.
  • Ensure that "JsonWebToken Signature Algorithm" is set to RS256 and that "OIDC Conformant" is enabled.

Next, configure the following URLs for your application under the "Application URIs" section of the "Settings" page:

  • Allowed Callback URLs: http://localhost:3000
  • Allowed Logout URLs: http://localhost:3000
  • Allowed Web Origins: http://localhost:3000

These URLs should reflect the origins that your application is running on. Allowed Callback URLs may also include a path, depending on where you're handling the callback (see below).

Take note of the Client ID and Domain values under the "Basic Information" section. You'll need these values in the next step.

配置插件

Create an instance of the AuthOKPlugin by calling createAuthOK and pass it to Vue's app.use().

import { createAuthOK } from '@authok/authok-vue';

const app = createApp(App);

app.use(
  createAuthOK({
    domain: '<AUTHOK_DOMAIN>',
    client_id: '<AUTHOK_CLIENT_ID>',
    redirect_uri: '<MY_CALLBACK_URL>'
  })
);

app.mount('#app');

添加登录

In order to add login to your application you can use the loginWithRedirect function that is exposed on the return value of useAuthok, which you can access in your component's setup function.

<script>
  import { useAuthok } from '@authok/authok-vue';

  export default {
    setup() {
      const { loginWithRedirect } = useAuthok();

      return {
        login: () => {
          loginWithRedirect();
        }
      };
    }
  };
</script>

Once setup returns the correct method, you can call that method from your component's HTML.

<template>
  <div>
    <button @click="login">Log in</button>
  </div>
</template>
<template>
  <div>
    <button @click="login">Log in</button>
  </div>
</template>

<script>
  export default {
    methods: {
      login() {
        this.$authok.loginWithRedirect();
      }
    }
  };
</script>

显示用户信息

To display the user's information, you can use the reactive user property exposed by the return value of useAuthok, which you can access in your component's setup function.

<script>
  import { useAuthok } from '@authok/authok-vue';

  export default {
    setup() {
      const { loginWithRedirect, user } = useAuthok();

      return {
        login: () => {
          loginWithRedirect();
        },
        user
      };
    }
  };
</script>

Once setup returns the SDK's reactive property, you can access that property from your component's HTML.

<template>
  <div>
    <h2>User Profile</h2>
    <button @click="login">Log in</button>
    <pre>
        <code>{{ user }}</code>
      </pre>
  </div>
</template>

Note: Ensure the user is authenticated by implementing login in your application before accessing the user's profile.

<template>
  <div>
    <h2>User Profile</h2>
    <button @click="login">Log in</button>
    <pre>
      <code>{{ user }}</code>
    </pre>
  </div>
</template>

<script>
  export default {
    data: function () {
      return {
        user: this.$authok.user
      };
    },
    methods: {
      login() {
        this.$authok.loginWithRedirect();
      }
    }
  };
</script>

添加退登

Adding logout to your application you be done by using the logout function that is exposed on the return value of useAuthok, which you can access in your component's setup function.

<script>
  import { useAuthok } from '@authok/authok-vue';

  export default {
    setup() {
      const { logout } = useAuthok();

      return {
        logout: () => {
          logout({ returnTo: window.location.origin });
        }
      };
    }
  };
</script>

Once setup returns the correct method, you can call that method from your component's HTML.

<template>
  <div>
    <button @click="logout">Log out</button>
  </div>
</template>
<template>
  <div>
    <button @click="logout">Log out</button>
  </div>
</template>

<script>
  export default {
    methods: {
      logout() {
        this.$authok.logout({ returnTo: window.location.origin });
      }
    }
  };
</script>

调用 API

To call an API, configure the plugin by setting the audience to the API Identifier of the API in question:

import { createAuthOK } from '@authok/authok-vue';

const app = createApp(App);

app.use(
  createAuthOK({
    domain: '<AUTHOK_DOMAIN>',
    client_id: '<AUTHOK_CLIENT_ID>',
    redirect_uri: '<MY_CALLBACK_URL>',
    audience: '<AUTHOK_AUDIENCE>'
  })
);

app.mount('#app');

After configuring the plugin, you will need to retrieve an Access Token and set it on the Authorization header of your request.

Retrieving an Access Token can be done by using the getAccessTokenSilently function that is exposed on the return value of useAuthok, which you can access in your component's setup function.

<script>
  import { useAuthok } from '@authok/authok-vue';

  export default {
    setup() {
      const { getAccessTokenSilently } = useAuthok();

      return {
        doSomethingWithToken: async () => {
          const token = await getAccessTokenSilently();
          const response = await fetch('https://api.example.com/posts', {
            headers: {
              Authorization: `Bearer ${token}`
            }
          });
          const data = await response.json();
        }
      };
    }
  };
</script>
<script>
  export default {
    methods: {
      async doSomethingWithToken() {
        const token = await this.$authok.getAccessTokenSilently();
        const response = await fetch('https://api.example.com/posts', {
          headers: {
            Authorization: `Bearer ${token}`
          }
        });
        const data = await response.json();
      }
    }
  };
</script>

访问 ID Token 声明

To get access to the user's claims, you can use the reactive idTokenClaims property exposed by the return value of useAuthok, which you can access in your component's setup function.

<script>
  import { useAuthok } from '@authok/authok-vue';

  export default {
    setup() {
      const { loginWithRedirect, idTokenClaims } = useAuthok();

      return {
        login: () => {
          loginWithRedirect();
        },
        idTokenClaims
      };
    }
  };
</script>

Once setup returns the SDK's reactive property, you can access that property from your component's HTML.

<template>
  <div>
    <h2>ID Token Claims</h2>
    <button @click="login">Log in</button>
    <pre>
      <code>{{ idTokenClaims }}</code>
    </pre>
  </div>
</template>
<template>
  <div>
    <h2>ID Token Claims</h2>
    <button @click="login">Log in</button>
    <pre>
      <code>{{ idTokenClaims }}</code>
    </pre>
  </div>
</template>
<script>
  export default {
    data: function () {
      return {
        idTokenClaims: this.$authok.idTokenClaims
      };
    },
    methods: {
      login() {
        this.$authok.loginWithRedirect();
      }
    }
  };
</script>

错误处理

When using this SDK, it could be the case that it is unable to correctly handle the authentication flow for a variety of reasons (e.g. an expired session with Authok when trying to get a token silently). In these situations, calling the actual methods will result in an exception being thrown (e.g. login_required). On top of that, these errors are made available through the SDK's reactive error property:

<script>
  import { useAuthok } from '@authok/authok-vue';

  export default {
    setup() {
      const { error } = useAuthok();

      return {
        error
      };
    }
  };
</script>

Once setup returns the SDK's error property, you can access that property from your component's HTML.

<template>
  <div>
    <h2>Error Handling</h2>
    <pre>
      <code>{{ error?.error }}</code>
    </pre>
  </div>
</template>
<template>
  <div>
    <h2>Error Handling</h2>
    <pre>
      <code>{{ error?.error }}</code>
    </pre>
  </div>
</template>
<script>
  export default {
    data: function () {
      return {
        error: this.$authok.error
      };
    }
  };
</script>

保护路由

If you are using our authok-Vue SDK with Vue-Router, you can protect a route by using the Navigation Guard provided by the SDK.

⚠️ 注意: the order in which the Router and Authok Vue plugin are registered is important. You must register the Router before the Authok SDK or you might see unexpected behavior.

import { createApp } from 'vue';
import { createRouter, createWebHashHistory } from 'vue-router';
import { createAuthOK, authGuard } from '@authok/authok-vue';

const app = createApp(App);
app.use(createRouter({
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/profile',
      name: 'profile',
      component: Profile,
      beforeEnter: authGuard
    }
  ],
  history: createWebHashHistory()
}));
app.use(createAuthOK({ ... }));
app.mount('#app');

Applying the guard to a route, as shown above, will only allow access to authenticated users. When a non-authenticated user tries to access a protected route, the SDK will redirect the user to Authok and redirect them back to your application's redirect_uri (which is configured in createAuthOK, see Configuring the plugin). Once the SDK is done processing the response from Authok and exchanging it for tokens, the SDK will redirect the user back to the protected route they were trying to access initially.

⚠️ If you are using multiple Vue applications with our SDK on a single page, using the above guard does not support a situation where the Authok Domain and ClientID would be different. In that case, read our guide on protecting a route when using multiple Vue applications.

贡献

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

支持 & 反馈

For support or to provide feedback, please raise an issue on our issue tracker.

常见问题

For a rundown of common issues you might encounter when using the SDK, please check out the FAQ.

缺陷报告

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

Authok 是什么

Authok helps you to easily:

  • implement authentication with multiple identity providers, including social (e.g., Google, Facebook, Microsoft, LinkedIn, GitHub, Twitter, etc), or enterprise (e.g., Windows Azure AD, Google Apps, Active Directory, ADFS, SAML, etc.)
  • log in users with username/password databases, passwordless, or multi-factor authentication
  • link multiple user accounts together
  • generate signed JSON Web Tokens to authorize your API calls and flow the user identity securely
  • access demographics and analytics detailing how, when, and where users are logging in
  • enrich user profiles from other data sources using customizable JavaScript rules

为什么使用 Authok?

许可

This project is licensed under the MIT license. See the LICENSE file for more info.