Validate Identity Server token in NodeJS API

人走茶凉 提交于 2020-06-01 06:03:12

问题


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?

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

NOTE:

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";
});

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

UPDATE:

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


回答1:


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

npm install token-introspection --save

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);

Example :

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");
})


来源:https://stackoverflow.com/questions/61495822/validate-identity-server-token-in-nodejs-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!