在NodeJS API中验证Identity Server令牌 [英] Validate Identity Server token in NodeJS API

查看:457
本文介绍了在NodeJS API中验证Identity Server令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个令牌,它已由Identity Server(IDP)发行,然后有一个NodeJS应用程序,并且 我想在NodeJS API中验证该令牌吗?

I have a token that it has been issued by Identity Server(IDP) and then have a NodeJS application and I want to validate that token in NodeJS API?

我正在尝试使用 jose (基于

I'm trying to use jose (based on this) but I did not know how to use it. Is it possible to do it?

注意:

在我的ASP NET CORE API中,作为客户端,我只需在startup class中添加以下命令来验证我的API?

In my ASP NET CORE API, here that is as a client I have to only add the following command in startup class to validate my API?

services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
   .AddIdentityServerAuthentication(options =>
     {
       // base-address of your identityserver
       options.Authority = "http://localhost:5000";
       options.RequireHttpsMetadata = false;
       // name of the API resource
       options.ApiName = "api1";
       // options.ApiSecret = "xxx";
});

在我的NodeJS api中,像上面的Web api这样的客户端,我应该怎么做?

In my NodeJS api that is as a client like web api above What should I do ?

更新:

我访问了这篇文章,但没有帮助我! 用于NodeJS API的Identity Server 4

I visited this article but I did not helped me ! Identity Server 4 for NodeJS API

推荐答案

如果只想验证令牌,则可以使用以下

If you want only to validate your token you can use the following package:

npm install token-introspection --save

此程序包配置了端点和客户端凭据,并返回了一个函数. 使用令牌和可选的token_type_hint调用该函数将返回一个Promise.

This package is configured with endpoint and client credentials, and a function is returned. Calling that function with token, and optional token_type_hint will return a Promise.

const tokenIntrospection = require('token-introspection')({
    endpoint: 'https://example.com/introspect',
    client_id: '<Client ID>',
    client_secret: '<Client Secret>',
});

tokenIntrospection(token).then(console.log).catch(console.warn);

示例:

这是一个用于验证令牌的中间件:

Here is a middleware to validate the token :

module.exports = (req, res, next) => {

    const token = "wEvxS0y2TkvCjLpKP33oGTK0BcKUb6MHt1u3AeMu8h4"; // get your token from your request 

    const tokenIntrospection = require('token-introspection')({
        endpoint: 'http://localhost:5000/connect/introspect',
        client_id: 'api1',
        client_secret: 'apisecret',
    });
    tokenIntrospection(token).then(result => {
        console.log(result);
        next();
    }).catch(console.warn);
}

然后您可以按以下方式使用它:

then you can use it as below :

const auth = require('./atuh')

app.get('/', auth, (req, res, next) => {
    res.send("Hi");
})

这篇关于在NodeJS API中验证Identity Server令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆