How to use the passport-azure-ad.BearerStrategy function in passport-azure-ad

To help you get started, we’ve selected a few passport-azure-ad examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Azure / platform-chaos-api / src / lib / app.ts View on Github external
})
  azureChaos.factory.Logger.configure({
    // tslint:disable-next-line
    logImpl: console.log
  })
  azureChaos.factory.AzureAuthenticator.configure({
    msRestImpl: require('ms-rest-azure')
  })

  const proc = azureChaos.factory.RequestProcessor.create()
  const registry = azureChaos.factory.ExtensionRegistry.create()
  const app = express()

  if (opts && opts.isProd) {
    // in production, use Bearer Strategy for auth
    passport.use(new BearerStrategy({
      audience: opts.authAudience,
      clientID: opts.authClientId,
      identityMetadata: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration',
      issuer: opts.authIssuer,
      loggingLevel: 'error'
    }, (token, done) => {
      done(null, token)
    }))
  } else {
    // if !isProd the test suite is being run so mock authentication
    const mockStrategy = new MockStrategy(
      (token, done) => {
        if (token === constants.MOCK_TOKEN) {
          done(null, {})
        } else {
          done(null, false, { message: 'bad token' })
github Azure-Samples / active-directory-javascript-nodejs-webapi-v2 / index.js View on Github external
var options = {
    identityMetadata: "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration/",
    clientID: "85327f73-fd44-46b9-a159-28544ff72288",
    validateIssuer: false,
    loggingLevel: 'warn',
    passReqToCallback: false
};

// Check for client id placeholder
if (options.clientID === 'YOUR_CLIENT_ID') {
    console.error("Please update 'options' with the client id (application id) of your application");
    return;
}

var bearerStrategy = new BearerStrategy(options,
    function (token, done) {
        // Send user info using the second argument
        done(null, {}, token);
    }
);

var app = express();
app.use(morgan('dev'));

app.use(passport.initialize());
passport.use(bearerStrategy);

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept");
    next();
github Azure-Samples / active-directory-b2c-javascript-nodejs-webapi / index.js View on Github external
var tenantID = tenantName + ".onmicrosoft.com";
var clientID = "25eef6e4-c905-4a07-8eb4-0d08d5df8b3f";
var policyName = "B2C_1_SUSI";
var domain = tenantName + ".b2clogin.com"

var options = {
    identityMetadata: "https://" + domain + "/" + tenantID + "/v2.0/.well-known/openid-configuration/",
    clientID: clientID,
    policyName: policyName,
    isB2C: true,
    validateIssuer: true,
    loggingLevel: 'info',
    passReqToCallback: false
};

var bearerStrategy = new BearerStrategy(options,
    function (token, done) {
        // Send user info using the second argument
        done(null, {}, token);
    }
);

var app = express();
app.use(morgan('dev'));

app.use(passport.initialize());
passport.use(bearerStrategy);

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept");
    next();
github Azure-Samples / active-directory-b2c-javascript-nodejs-webapi / index.js View on Github external
var b2cDomainHost = "fabrikamb2c.b2clogin.com";
var tenantIdGuid = "775527ff-9a37-4307-8b3d-cc311f58d925";
var policyName = "B2C_1_SUSI";

var options = {
    identityMetadata: "https://" + b2cDomainHost + "/" + tenantIdGuid + "/" + policyName + "/v2.0/.well-known/openid-configuration/",
    clientID: clientID,
    policyName: policyName,
    isB2C: true,
    validateIssuer: false,
    loggingLevel: 'info',
    loggingNoPII: false,
    passReqToCallback: false
};

var bearerStrategy = new BearerStrategy(options,
    function (token, done) {
        // Send user info using the second argument
        done(null, {}, token);
    }
);

var app = express();
app.use(morgan('dev'));

app.use(passport.initialize());
passport.use(bearerStrategy);

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept");
    next();
github Azure-Samples / active-directory-node-webapi / node-server / app.js View on Github external
/* You'll want to do something smarter.
**/

var findById = function(id, fn) {
    for (var i = 0, len = users.length; i < len; i++) {
        var user = users[i];
        if (user.sub === id) {
            log.info('Found user: ', user);
            return fn(null, user);
        }
    }
    return fn(null, null);
};


var oidcStrategy = new OIDCBearerStrategy(options,
    function(token, done) {
        log.info('verifying the user');
        log.info(token, 'was the token retreived');
        findById(token.sub, function(err, user) {
            if (err) {
                return done(err);
            }
            if (!user) {
                // "Auto-registration"
                log.info('User was added automatically as they were new. Their sub is: ', token.sub);
                users.push(token);
                owner = token.sub;
                return done(null, token);
            }
            owner = token.sub;
            return done(null, user, token);
github AzureADQuickStarts / AppModelv2-WebAPI-nodejs / node-server / app.js View on Github external
// Use the common stuff you probably want
server.use(restify.acceptParser(server.acceptable));
server.use(restify.dateParser());
server.use(restify.queryParser());
server.use(restify.gzipResponse());
server.use(restify.bodyParser({
    mapParams: true
})); // Allows for JSON mapping to REST
server.use(restify.authorizationParser()); // Looks for authorization headers

// Let's start using Passport.js

server.use(passport.initialize()); // Starts passport
server.use(passport.session()); // Provides session support

var bearerStrategy = new OIDCBearerStrategy(options,
    function(token, done) {
        log.info(token, 'was the token retreived');
        if (!token.oid)
            done(new Error('oid is not found in token'));
        else {
            owner = token.oid;
            done(null, token);
        }
    }
);

passport.use(bearerStrategy);

/// Now the real handlers. Here we just CRUD

/**
github DefinitelyTyped / DefinitelyTyped / types / passport-azure-ad / passport-azure-ad-tests.ts View on Github external
else done(new Error("Invalid token"));
};

const verifyOidc: VerifyOIDCFunctionWithReq = (req: Request, profile: IProfile, done: VerifyCallback) => {
    if (!profile.oid)
        done(null, profile);
    else done(new Error("Invalid token"));
};

const verifyOidcWithoutReq: VerifyOIDCFunction = (profile: IProfile, done: VerifyCallback) => {
    if (!profile.oid)
        done(null, profile);
    else done(new Error("Invalid token"));
};

new BearerStrategy(bearerStrategyOptions, verifyBearer);

new OIDCStrategy(oidcStrategyOptions, verifyOidc);

new OIDCStrategy(oidcStrategyOptionWithoutRequest, verifyOidcWithoutReq);
github benc-uk / smilr / node / data-api / lib / auth.js View on Github external
module.exports = function(app) {
  console.log("### Setting up AAD bearer token validation middleware");

  app.use(passport.initialize());
  app.use(passport.session());
  
  const strategy = new BearerStrategy({
    identityMetadata: `https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration`,
    clientID: process.env.SECURE_CLIENT_ID,
    allowMultiAudiencesInToken: true,
    validateIssuer: false,
    loggingLevel: 'error',
  }, gotValidToken)

  passport.use(strategy);
};
github CatalystCode / project-fortis / project-fortis-services / src / auth.js View on Github external
function initialize(app, route) {
  if (!adClientId) return console.warn('!!!!!!!!!!!! No Active Directory Client Id configured; auth is disabled !!!!!!!!!!!!');

  const adOptions = {
    identityMetadata: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration',
    clientID: adClientId,
    validateIssuer: false,
    issuer: null,
    passReqToCallback: true,
    allowMultiAudiencesInToken: false,
    loggingLevel: adLogLevel
  };

  const bearerStrategy = new OIDCBearerStrategy(adOptions, (req, token, done) => {
    const user = { identifier: token.preferred_username };
    done(null, user, token);
  });

  app.use(passport.initialize());
  app.use(passport.session());
  passport.use(bearerStrategy);
  passport.use(new AnonymousStrategy());
  app.use(route, passport.authenticate(['oauth-bearer', 'anonymous'], { session: false }));
}
github Azure-Samples / active-directory-node-webapi-basic / app.js View on Github external
'use strict';

const
      restify = require('restify')
    , restifyPlugins = require ('restify').plugins
    , passport = require('passport')
    , BearerStrategy = require('passport-azure-ad').BearerStrategy
    , config = require('./config')
    , authenticatedUserTokens = []
    , serverPort = process.env.PORT || config.serverPort
;

const authenticationStrategy = new BearerStrategy(config.credentials, (token, done) => {
    let currentUser = null;

    let userToken = authenticatedUserTokens.find((user) => {
        currentUser = user;
        user.sub === token.sub;
    });

    if(!userToken) {
        authenticatedUserTokens.push(token);
    }

    return done(null, currentUser, token);
});

passport.use(authenticationStrategy);

passport-azure-ad

OIDC and Bearer Passport strategies for Azure Active Directory

MIT
Latest version published 2 years ago

Package Health Score

61 / 100
Full package analysis