5 个在 JavaScript 项目中使用 JavaScript OAuth 库

370次阅读  |  发布于2年以前

OAuth 是一种开放标准的安全机制,可让您授权一个应用程序与您帐户上的另一个应用程序交互。

它的创建是为了允许一项服务授权另一项服务。OAuth 不公开用户凭据,而是依靠授权令牌来连接用户和服务提供商。

对用户授权的需求可能因业务策略而异。例如,如果您的组织需要面向用户的 API,例如,访问 Google Drive 或代表您发送推文,OAuth 是一个不错的选择。

因此,在本文中,我将讨论可以在您的下一个 Web 应用程序中使用的前 5 个 JavaScript OAuth 库,它们将使用户授权变得更加容易。

1、jsonwebtoken

JSON Web 令牌的实现。

可以说,JSON Web Token 可能是使用最广泛和最受欢迎的 JavaScript OAuth 库。它在使用 JSON Web 令牌 (JWT) 处理敏感信息的 Web 应用程序中非常有用。

JSON Web Token 库具有丰富的功能,例如,

除了所有这些之外,JSON 网络令牌库每周有大约 640 万次下载和 14.3K GitHub stars。

用于对令牌进行签名的技术可以随时更改,从而提供了使令牌更安全并防止个人数据泄露或恶意数据注入的自由。

您可以使用 npm 和 npm i jsonwebtoken 命令轻松下载它。下面是一个异步符号的简单示例。

jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' }, function(err, token) {
  console.log(signed);
});

2、身份验证

NextAuth.js 是 Next.js 应用程序的完整开源身份验证解决方案。

它的设计完全是为了支持 Next.js 和 Serverless。此外,Next-auth 支持无密码登录机制。以及它旨在确保安全并在默认情况下帮助处理用户数据。此外,还支持跨站点请求,并在发布路由上提供必要的隐私。

除此之外,它还具有一些现有功能和出色的文档以吸引开发人员。我可以很容易地列出其中的一些,如下:

它目前的版本为 3.28.0,每周下载量为 65.3K,GitHub stars 为 7.3K。

您可以通过运行 npm i next-auth 轻松安装 next-auth,下面的示例显示了 next-auth 的简单示例。

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
export default NextAuth({
 providers: [
 // OAuth authentication providers…
 Providers.Facebook({
 clientId: process.env.FACEBOOK_ID,
 clientSecret: process.env.FACEBOOK_SECRET
 }),
 Providers.Google({
 clientId: process.env.GOOGLE_ID,
 clientSecret: process.env.GOOGLE_SECRET
 }),
 // Passwordless/sign in
 Providers.Email({
 server: process.env.MAIL_SERVER,
 from: 'NextAuth.js <nextauth@example.com>'
 }),
 ],
 // Optional SQL or MongoDB database to persist users
 database: process.env.DATABASE_URL
}) 
import {
  useSession, signIn, signOut
} from 'next-auth/client'

export default function Component() {
  const [ session, loading ] = useSession()
  if(session) {
    return <>
      Signed in as {session.user.email} <br/>
      <button onClick={() => signOut()}>Sign out</button>
    </>
  }
  return <>
    Not signed in <br/>
    <button onClick={() => signIn()}>Sign in</button>
  </>
}

3、 angular-oauth2-oidc

angular-oauth2-oidc 专为 Angular 设计,支持 OAuth 2 和 OpenId Connect (OIDC)。已经为即将到来的 OAuth 2.1 做好了准备。

这个库在所有现代浏览器和 IE 上使用 webpack 进行了全面测试,包括 Angular 4.3 到 Angular 12 及其路由器、PathLocationStrategy、HashLocationStrategy 和 CommonJS-Bundling。此外,它还具有丰富的文档,可以帮助任何新手开发人员。

它提供的主要功能如下:

它每周有 107K 的下载量和 1.4K 的 GitHub stars。

您可以通过运行 npm i angular-oauth2-oidc 命令使用 npm 安装它,下面的代码显示了使用 angular-oauth2-oidc 的简单示例。

第 1 步 - 设置 NgModule(app.module)。

import { OAuthModule } from 'angular-oauth2-oidc';
[...]

@NgModule({

  imports: [ 
    [...]
    HttpModule,
    OAuthModule.forRoot()
  ],
  ........

export class AppModule {

}

第 2 步 - 隐式流配置和登录页面。

import { AuthConfig } from 'angular-oauth2-oidc';

export const authConfig: AuthConfig = {

  // Url of the Identity Provider
  issuer: 'https://demo.identityserver.com/identity',

  // Login Url of the Identity Provider
  loginurl: 'https://demo.identityserver.com/identity/connect/authorize',

  // Login Url of the Identity Provider
  logouturl: 'https://demo.identityserver.com/identity/connect/endsession',


  // URL of the SPA to redirect the user to after login
  redirectUri: window.location.origin + '/dashboard.html',

  // The SPA's id. The SPA is registerd with this id at the auth-server
  clientId: 'billing_demo',

  // set the scope for the permissions the client should request
  // The first three are defined by OIDC. Also provide user sepecific
  scope: 'openid profile email billing_demo_api',
}

第 3 步 - 触发向用户显示身份服务器登录页面的隐式流程。

import { OAuthService } from 'angular-oauth2-oidc';
import { JwksValidationHandler } from 'angular-oauth2-oidc';
import { authConfig } from './auth.config';
import { Component } from '@angular/core';

@Component({
    selector: 'billing-app',
    templateUrl: './app.component.html'
})
export class AppComponent {

    constructor(private oauthService: OAuthService) {

      this.ConfigureImplicitFlowAuthentication();
    }

    private ConfigureImplicitFlowAuthentication() {

      this.oauthService.configure(authConfig);

      this.oauthService.tokenValidationHandler = new JwksValidationHandler();

      this.oauthService.loadDiscoveryDocument().then(doc) => {
    this.oauthService.tryLogin()
      .catch(err => {
        console.error(err);
      })
      .then(() => {
        if(!this.oauthService.hasValidAccessToken()) {
          this.oauthService.initImplicitFlow()
        }
      });
    });
    }
}

4、Passport—oauth2

Passport 和 Node.js 的 OAuth 2.0 身份验证策略。

该库允许您在 Node.js 应用程序中使用 OAuth 2.0 身份验证。OAuth 2.0 身份验证可以通过插入 Passport 实现到任何支持 Connect 式中间件(例如 Express)的应用程序或框架中。

重要的是要意识到此策略通常支持 OAuth 2.0。通常也可以使用特定于提供者的方法,这减少了不必要的配置并促进了任何特定于提供者的怪癖。可以在文档中找到受支持的提供程序。

passport-oauth2 具有一些令人兴奋的功能,例如:

这也是一个非常流行的 OAuth 库,每周下载量约为 368K,GitHub stars超过 501。

使用 npm 安装一如既往地简单。您只需要运行 npm ipassport-oauth2 命令,然后您就可以使用 passport.authenticate() 尝试以下示例,指定 'oauth2' 策略来验证请求。

例如,作为 Express 应用程序中的路由中间件:

app.get('/auth/passportauth',
  passport.authenticate('oauth2'));
app.get('/auth/passportauth/callback',
  passport.authenticate('oauth2', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

5、Simple—oauth2

一个用于 Oauth2 的简单 Node.js 客户端库。

simple-oauth2 目前的版本是 4.2,要使用这个库,你需要安装 Node 12.x 或更高版本。

它提供的功能如下:

支持的 Grant 类型:

完成任何受支持的授权类型后,将获得访问令牌。

您可以使用 npm i simple-oauth2 命令安装它并自行尝试。例如,一个简单的授权代码授权类型示例可以如下所示。

步骤 1- 使用最少的配置创建任何受支持的授权类型的客户端实例。

const config = {
  client: {
    id: '<client-id>',
    secret: '<client-secret>'
  },
  auth: {
    tokenHost: 'https://api.oauth.com'
  }
};

const { ClientCredentials, ResourceOwnerPassword, AuthorizationCode } = require('simple-oauth2');

第2步

async function run() {
  const client = new AuthorizationCode(config);

  const authorizationUri = client.authorizeURL({
    redirect_uri: 'http://localhost:3000/callback',
    scope: '<scope>',
    state: '<state>'
  });

  // Redirect example using Express (see http://expressjs.com/api.html#res.redirect)
  res.redirect(authorizationUri);

  const tokenParams = {
    code: '<code>',
    redirect_uri: 'http://localhost:3000/callback',
    scope: '<scope>',
  };

  try {
    const accessToken = await client.getToken(tokenParams);
  } catch (error) {
    console.log('Access Token Error', error.message);
  }
}

run();

总结在开发项目中, JavaScript Web 应用程序选择 OAuth 库时,必须考虑您的程序、网站或应用程序如何对用户进行身份验证。他们有适当的权限吗?您是否已向相关服务提供商授予代表用户验证其身份和访问数据的许可?您将使用的 OAuth 版本等。

即使您使用 OAuth 库来自动化该过程,您也应该始终意识到个人或该服务提供商将如何使用(或维护)应用程序数据。

因此,我希望今天内容能够给对您有所帮助,帮助您在下一个 JavaScript 项目中选择出最佳的 OAuth 库。

最后,感谢您的时间,感谢您的阅读。

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8