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

Remove or reduce non-identity code from the code sample #65

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
178 changes: 128 additions & 50 deletions 1-Authentication/5-sign-in-express/App/app.js
Original file line number Diff line number Diff line change
@@ -1,68 +1,146 @@
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const msal = require('@azure/msal-node');
const express = require('express');
const session = require('express-session');
const createError = require('http-errors');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const { msalConfig, TENANT_SUBDOMAIN, REDIRECT_URI, POST_LOGOUT_REDIRECT_URI } = require('./authConfig');

// Initialize MSAL Node (confidential app)

const msalInstance = new msal.ConfidentialClientApplication(msalConfig);

require('dotenv').config();
/**
* The MSAL.js library allows you to pass your custom state as state parameter in the Request object
* By default, MSAL.js passes a randomly generated unique state parameter value in the authentication requests.
* The state parameter can also be used to encode information of the app's state before redirect.
* You can pass the user's state in the app, such as the page or view they were on, as input to this parameter.
* For more information, visit: https://docs.microsoft.com/azure/active-directory/develop/msal-js-pass-custom-state-authentication-request
* In this scenario, the states also serve to show the action that was requested of B2C since only one redirect URL is possible.
*/

var path = require('path');
var express = require('express');
var session = require('express-session');
var createError = require('http-errors');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const APP_STATES = {
LOGIN: 'login'
}

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var authRouter = require('./routes/auth');
/**
* Request Configuration
* We manipulate these two request objects below
* to acquire a token with the appropriate claims.
*/
const authCodeRequest = {
redirectUri: REDIRECT_URI,
};

// initialize express
var app = express();
const tokenRequest = {
redirectUri: REDIRECT_URI,
};

/**
* Using express-session middleware for persistent user session. Be sure to
* familiarize yourself with available options. Visit: https://www.npmjs.com/package/express-session
* Using express-session middleware. Be sure to familiarize yourself with available options
* and set them as desired. Visit: https://www.npmjs.com/package/express-session
*/
app.use(
session({
secret: process.env.EXPRESS_SESSION_SECRET || 'Enter_the_Express_Session_Secret_Here',
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: false, // set this to true on production
},
})
);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
const sessionConfig = {
secret: process.env.EXPRESS_SESSION_SECRET || 'Enter_the_Express_Session_Secret_Here',
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: false, // set value to true in production
}
}

//Create an express instance
const app = express();

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


app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/auth', authRouter);
/**
* This method is used to generate an auth code request, the first leg of authorization code grant flow
* @param {array} scopes: scopes to request the auth code for
* @param {string} state: state of the application
* @param {Object} res: express middleware response object
*/

// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
const getAuthCode = (authority, scopes, state, res) => {

// prepare the request
console.log("Fetching Authorization code")
authCodeRequest.authority = authority;
authCodeRequest.scopes = scopes;
authCodeRequest.state = state;

// request an authorization code to exchange for a token
return msalInstance.getAuthCodeUrl(authCodeRequest)
.then((response) => {
console.log("\nAuthCodeURL: \n" + response);
//redirect to the auth code URL/send code to
res.redirect(response);
})
.catch((error) => {
res.status(500).send(error);
});
}

app.get('/', (req, res) => {
if (req.session.isAuthenticated && req.session.isAuthenticated === true) {
res.send('<a href="/id-token-claims">View id token claims</a> </br> <a href="/signout">Sign out</a>');
}else{
res.send('<a href="/signin">Sign in</a> </br>')
}
});

// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
app.get('/signin', (req, res) => {
//Initiate a Auth Code Flow >> for sign in
//no scopes passed. openid, profile and offline_access will be used by default.
getAuthCode(msalConfig.auth.authority, [], APP_STATES.LOGIN, res);
});

// render the error page
res.status(err.status || 500);
res.render('error');
app.get('/signout',async (req, res)=>{
logoutUri = process.env.LOGOUT_ENDPOINT || `${msalConfig.auth.authority}${TENANT_SUBDOMAIN}.onmicrosoft.com/oauth2/v2.0/logout?post_logout_redirect_uri=${POST_LOGOUT_REDIRECT_URI}`;
req.session.destroy(() => {
//When session destruction succeeds, notify CIAM service using the logout uri.
res.redirect(logoutUri);
});
});

module.exports = app;
app.get('/id-token-claims', (req, res) => {
if (req.session.isAuthenticated && req.session.isAuthenticated === true) {
// list all id token claims
for (let key in req.session.account.idTokenClaims){
let claimAndValue = key + ":" + req.session.account.idTokenClaims[key];
console.log(claimAndValue);
}
} else {
res.redirect('/');
}
});

app.get('/redirect', (req, res) => {
//prepare the request to acquire id token by using acquireTokenByCode()
tokenRequest.code = req.query.code;
msalInstance.acquireTokenByCode(tokenRequest).then((tokenResponse)=>{

//add response info to express session
req.session.account = tokenResponse.account;
req.session.idToken = tokenResponse.idToken
req.session.isAuthenticated = true;
//log tokenResponse
console.log("\nAuthToken: \n" + JSON.stringify(tokenResponse));
//log a claim, such as name to show how to get a token claim from the id token
console.log("\nGiven name: \n" + JSON.stringify(tokenResponse.account.idTokenClaims.name));
res.redirect('/');
}).catch((error)=>{
console.log("\nErrorAtLogin: \n" + error);
});
});


app.listen(process.env.SERVER_PORT || 3000, () => {
console.log('Msal Node Auth Code Sample app listening on port ! ' + (process.env.SERVER_PORT || 3000));
});
184 changes: 0 additions & 184 deletions 1-Authentication/5-sign-in-express/App/auth/AuthProvider.js

This file was deleted.

2 changes: 1 addition & 1 deletion 1-Authentication/5-sign-in-express/App/authConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
require('dotenv').config();

const TENANT_SUBDOMAIN = process.env.TENANT_SUBDOMAIN || 'Enter_the_Tenant_Subdomain_Here';
const REDIRECT_URI = process.env.REDIRECT_URI || 'http://localhost:3000/auth/redirect';
const REDIRECT_URI = process.env.REDIRECT_URI || 'http://localhost:3000/redirect';
const POST_LOGOUT_REDIRECT_URI = process.env.POST_LOGOUT_REDIRECT_URI || 'http://localhost:3000';

/**
Expand Down
Loading