question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Session state creating issue while redirecting to redirect URI

See original GitHub issue

Core Library

MSAL Node (@azure/msal-node)

Core Library Version

1.14.3

Wrapper Library

MSAL Node Extensions (@azure/msal-node-extensions)

Wrapper Library Version

NA

Public or Confidential Client?

Confidential

Description

On Local the solution is working flawlessly as expected and once we move the solution to azure app service it breaks.

I am getting Error 404 page not found while it is redirecting, after it goes to authorize endpoint and send the authorization code to redirect uri. I get the below error

https://.azurewebsites.net/auth/redirect?code=<Authorization_Code>&session_state=18b77656-7bb0-45e7-a678-5944ec526564

After i remove the session state manually and try it works fine .

Can someone help me understand why this is happening and how to correct this. (Like skip session state while sending)

Error Message

Not getting redirected to the application Home page

Getting 404 page not found

https://.azurewebsites.net/auth/redirect?code=<Authorization_Code>&session_state=18b77656-7bb0-45e7-a678-5944ec526564

Msal Logs

No response

MSAL Configuration

{
    auth: {
        clientId: "<Client-ID>",
        authority: "https://login.microsoftonline.com/<tenant-id>",
        clientSecret: "<client-secret>"
    },
    system: {
        loggerOptions: {
            loggerCallback(loglevel, message, containsPii) {
                console.log(message);
            },
            piiLoggingEnabled: false,
            logLevel: msal.LogLevel.Verbose,
        }
    }
};

Relevant Code Snippets

// Import dependencies
const express = require("express");
// Initialize express
const app = express();
const session = require("express-session");
const msal = require('@azure/msal-node');

const sessionConfig = {
    secret: 'Thanos1993',
    resave: false,
    saveUninitialized: false,
    cookie: {
        secure: false, // set this to true on production
    }
}

app.use(session(sessionConfig));

// Authentication parameters
const config = {
    auth: {
        clientId: "<Client-ID>",
        authority: "https://login.microsoftonline.com/<tenant-id>",
        clientSecret: "<client-secret>"
    },
    system: {
        loggerOptions: {
            loggerCallback(loglevel, message, containsPii) {
                console.log(message);
            },
            piiLoggingEnabled: false,
            logLevel: msal.LogLevel.Verbose,
        }
    }
};

const REDIRECT_URI = "http://localhost:3000/auth/redirect";

// Initialize MSAL Node object using authentication parameters
const cca = new msal.ConfidentialClientApplication(config);



app.set('view engine','ejs');

app.get('/', (req, res) => {
    res.render('home')
});

app.get('/auth', (req, res) => {

    // Construct a request object for auth code
    const authCodeUrlParameters = {
        scopes: ["user.read"],
        redirectUri: REDIRECT_URI,
    };

    // Request auth code, then redirect
    cca.getAuthCodeUrl(authCodeUrlParameters)
        .then((response) => {
            res.redirect(response);
        }).catch((error) => res.send(error));
});

app.get('/auth/redirect', (req, res) => {

    // Use the auth code in redirect request to construct
    // a token request object
    const tokenRequest = {
        code: req.query.code,
        scopes: ["user.read"],
        redirectUri: REDIRECT_URI,
    };

    // Exchange the auth code for tokens
    cca.acquireTokenByCode(tokenRequest)
        .then((response) => {
           // res.send(response);
            console.log(response);
            console.log(response.account.name);
            req.session.user = response.account.name
            req.session.isAuthenticated = true;
            res.redirect('/home');
        }).catch((error) => res.status(500).send(error));
});

app.get('/home', ensureAuthenticated ,(req,res)=>{
    res.send("You have reached the Home Page after authentication");
})

app.get('/about', ensureAuthenticated ,(req,res)=>{
    res.send("You have reached the About Page after authentication");
})

app.get('/logout',(req,res)=>{
    console.log(`Logging out the user : ${req.session.user}`);
    req.session.destroy(function (err) {
      res.redirect('/'); 
     });
  })

app.listen(3000, () => {console.log(`listening on port 3000!`)});


function ensureAuthenticated(req, res, next) {
    if (req.session.isAuthenticated) { 
        console.log(`User is Authenticated : ${req.session.isAuthenticated}`)
        return next(); 
    }
     res.redirect('/');
    }

Reproduction Steps

  1. Locally the Application work flawless
  2. When we move the application to Azure it breaks after authrorization code is get and it needs to redirect.
  3. In mobile browser it works fine , error is coming only in desktop browser.
  4. I we remove the session_State and manually try the url it works gets access token and redirect to application

Expected Behavior

After Getting Authorization code it should go to redirect uri and get the access token and redirect to application home page

Identity Provider

Azure AD / MSA

Browsers Affected (Select all that apply)

Chrome, Edge, Internet Explorer

Regression

No response

Source

External (Customer)

Issue Analytics

  • State:closed
  • Created 10 months ago
  • Comments:12 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
tushaar9027commented, Nov 23, 2022

ou can mitigate this issue by

@derisen i am not using any [Application Gateway configured] in my environment, nor any [some URL rewrite rule].

Let me try to use the responseMode: “form_post” and see if that works . Thanks for analyzing the issue atleast i have some lead now.

0reactions
derisencommented, Dec 1, 2022

@tushaar9027 assuming this is mitigated with form_post. Closing, but let us know if not.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Manage session state across redirects - Stack Overflow
They suggest using session storage to persist a redirect url from before the app takes the user to the SSO site for authentication,...
Read more >
OIDC code contains session_state in redirect URI ... - Red Hat
This leads to a 403 forbidden when a user is redirected to our application, because the redirect URI in the code has the...
Read more >
Don't redirect after setting a Session variable (or do it right)
A problem I see over and over again on the ASP.NET forums is the following:In a login page, if the user and password...
Read more >
Redirect Users - Auth0
Using cookies and browser sessions. Using state parameters. During a user's authentication, the redirect_uri request parameter is used as a callback URL.
Read more >
Redirections in HTTP - MDN Web Docs - Mozilla
URL redirection, also known as URL forwarding, is a technique to give more ... Temporary redirections are also used when creating, updating, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found