Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redis token cache for msal-node? #2828

Closed
2 tasks done
eanders-ms opened this issue Jan 5, 2021 · 12 comments · Fixed by #3986
Closed
2 tasks done

Redis token cache for msal-node? #2828

eanders-ms opened this issue Jan 5, 2021 · 12 comments · Fixed by #3986
Assignees
Labels
enhancement Enhancement to an existing feature or behavior. msal-node Related to msal-node package

Comments

@eanders-ms
Copy link
Contributor

Library

Description

Does a redis-backed token cache exist for msal-node (for use in confidential client application)? If not, could you point me to an existing implementation in another framework/language that would serve as a good reference? I would try to port it to js. I'm looking at the dotnet library's equivalent as a potential candidate.

Source

  • Internal (Microsoft)
@eanders-ms eanders-ms added the question Customer is asking for a clarification, use case or information. label Jan 5, 2021
@jo-arroyo jo-arroyo added the msal-node Related to msal-node package label Jan 5, 2021
@github-actions
Copy link
Contributor

This issue has not seen activity in 14 days. It will be closed in 7 days if it remains stale.

@github-actions github-actions bot added the no-issue-activity Issue author has not responded in 5 days label Jan 20, 2021
@jo-arroyo jo-arroyo removed the no-issue-activity Issue author has not responded in 5 days label Jan 25, 2021
@sameerag
Copy link
Member

Unfortunately we do not have a redis-backed token storage for msal-node. Can you expand a little on what you are trying to do? We can also chat offline and see what best I can do to help.

@jo-arroyo jo-arroyo added enhancement Enhancement to an existing feature or behavior. and removed question Customer is asking for a clarification, use case or information. labels Feb 1, 2021
@benvdh
Copy link

benvdh commented Feb 6, 2021

@eanders-ms There was actually discussion on this a while ago in an msal-python issue:

AzureAD/microsoft-authentication-library-for-python#98

@sameerag I am looking for something similar in a python context, but the use case generalizes to platforms like node as well. In my case it concerns a backend web-application running on kubernetes with multiple replicated pods, where MSAL is used to gather an authentication token to connect to another Microsoft API. Having a distributed cache like Redis would save us a few API calls.

@sameerag
Copy link
Member

I followed up on this and there is a library wide effort we want to make to standardize persistence for web apps (distributed cache). We are not yet clear on the timelines though. We will reach out once this feature gets the green, please watch out our roadmap for the announcement.

@richban
Copy link

richban commented Mar 27, 2021

I would like to request this feature as well! I would like to use redis for my use case.

@manandkumaar
Copy link

I am looking for the solution/recommendation on the below remarks.
I understood that the persistent cache logic in the below file has to be replaced with redis for example.

https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/samples/msal-node-samples/ExpressTestApp/TestApp/App/utils/cachePlugin.js

Highly appreciated if anyone can point to any reference implementation.

image

@benvdh
Copy link

benvdh commented Jun 14, 2021

@manandkumaar As far as I know there is no reference implementation available of implementing a redis-based cache. You only have two different implementations by Microsoft:

  1. The typical in-memory cache (which is (likely) based on a javascript object in JS, and a dictionary in python (see thread above))
  2. The serializable cache example (file-based cache, where the whole cache gets serialized into an on-disk format (json in the above JS example you refer to)

So if you want to have redis cache, you have roughly 2 options for now:

  1. Studying the code samples above (the python thread I link to also gives some insights and answers to functional issues), and implementing it yourself.
  2. Waiting for microsoft until they have implemented this feature library-wide (as sameerag remarked above).

@jasonnutter jasonnutter linked a pull request Oct 6, 2021 that will close this issue
@derisen
Copy link
Contributor

derisen commented Oct 11, 2021

Hey @eanders-ms @benvdh @richban @manandkumaar, check out the ExpressTestApp sample, which has an example distributed cache implementation now. msal-node will eventually provide APIs to make working with this easier, but hopefully this helps in the meantime. Make sure to take a look at caching docs as well.

@MatthewVaccaro
Copy link

@derisen Thank you for this! It's extremely helpful!

@MatthewVaccaro
Copy link

Implemented as close as I could but I feel like I am getting a delay. Is this expected?

When running below I don't get any errors and I can see my cachePlugin "working".
My config has an added key called "cache". I found if I don't supply this upfront it wont allow me to update it later. The prescribed way of writing the CachePlugin requires you to pass a session ID upfront so you can leverage it later.

Heres where I feel it's not working. Each time initializeTokenCachePlugin runs the first time and it gives the initial value not the updated value. On subsequent requests, it has the new value (session-id). Is this expected?

File: msAuthLibrary
`let { cachePlugin } = require("../util/cachePlugin");
const msal = require("@azure/msal-node");

const config = {
auth: {
clientId: process.env.OAUTH_CLIENT_ID,
authority: process.env.OAUTH_AUTHORITY,
clientSecret: process.env.OAUTH_CLIENT_SECRET,
},
cache: {
cachePlugin: cachePlugin("inital"),
},
system: {
loggerOptions: {
loggerCallback(loglevel, message, containsPii) {
console.log(${message}.magenta);
},
piiLoggingEnabled: false,
logLevel: msal.LogLevel.Verbose,
},
},
};

let authProvider = new msal.ConfidentialClientApplication(config);

async function initializeTokenCachePlugin(req, res, next) {
const { cachePlugin } = require("../util/cachePlugin");
authProvider.tokenCache.persistence = cachePlugin(req.sessionID);
next();
}`


file: server.js
`require("dotenv").config();
var createError = require("http-errors");
var express = require("express");
var cookieParser = require("cookie-parser");
var path = require("path");
var logger = require("morgan");
const msal = require("@azure/msal-node");
let msAuthLibrary = require("./logic/middleware/msAuthLibrary");
const cors = require("cors");
var indexRouter = require("./routes/index");
const authRouter = require("./routes/auth");
const accountRouter = require("./routes/accounts");
const contactsRouter = require("./routes/contacts");
const fielsdRouter = require("./routes/fields");
const responsesRouter = require("./routes/responses");
const platformRouter = require("./routes/platform");

const session = require("./logic/middleware/sessions");

var app = express();
app.use(express.json());

// CORS Cofig
app.use(
cors({
"Access-Control-Allow-Origin": process.env.ALLOW_ORIGIN,
})
);

// Session Middleware
app.set("trust proxy", true);
app.use(session.config);
app.use(session.logger);

app.locals.msalClient = msAuthLibrary.authProvider;

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

app.use(msAuthLibrary.initializeTokenCachePlugin);

app.use("/", indexRouter);
app.use("/auth", authRouter);
app.use("/resources/accounts", accountRouter);
app.use("/resources/platforms", platformRouter);
app.use("/resources/contacts", contactsRouter);
app.use("/resources/fields", fielsdRouter);
app.use("/resources/responses", responsesRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});

module.exports = app;
`

@richban
Copy link

richban commented Feb 14, 2022

Apply the syntax highlight properly for better readability. I might be able to help you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement Enhancement to an existing feature or behavior. msal-node Related to msal-node package
Projects
None yet
Development

Successfully merging a pull request may close this issue.

8 participants