Skip to content
This repository has been archived by the owner on May 26, 2023. It is now read-only.

Commit

Permalink
Initial commit from Samples
Browse files Browse the repository at this point in the history
  • Loading branch information
brandwe committed Aug 24, 2015
0 parents commit f4d1d65
Show file tree
Hide file tree
Showing 36 changed files with 3,907 additions and 0 deletions.
22 changes: 22 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
The MIT License (MIT)

Copyright (c) 2015 Microsoft Azure Active Directory Samples and Documentation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

61 changes: 61 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#Windows Azure Active Directory OIDC Web API Sample

This Node.js app will give you with a quick and easy way to set up a Web application in node.js with Express usind OpenID Connect. The sample server included in the download are designed to run on any platform.

We've released all of the source code for this example in GitHub under an MIT license, so feel free to clone (or even better, fork!) and provide feedback on the forums.


## Quick Start

Getting started with the sample is easy. It is configured to run out of the box with minimal setup.

### Step 1: Register a Windows Azure AD Tenant

To use this sample you will need a Windows Azure Active Directory Tenant. If you're not sure what a tenant is or how you would get one, read [What is an Azure AD tenant](http://technet.microsoft.com/library/jj573650.aspx)? or [Sign up for Azure as an organization](http://azure.microsoft.com/en-us/documentation/articles/sign-up-organization/). These docs should get you started on your way to using Windows Azure AD.

### Step 2: Register your Web API with your Windows Azure AD Tenant

After you get your Windows Azure AD tenant, add this sample app to your tenant so you can use it to protect your API endpoints. If you need help with this step, see: [Register the REST API Service Windows Azure Active Directory](https://github.com/AzureADSamples/WebAPI-Nodejs/wiki/Setup-Windows-Azure-AD)

### Step 3: Download node.js for your platform
To successfully use this sample, you need a working installation of Node.js.

### Step 4: Download the Sample application and modules

Next, clone the sample repo and install the NPM.

From your shell or command line:

* `$ git clone git@github.com:AzureADSamples/Convergence-OpenIDConnect-Nodejs.git`
* `$ npm install`
* `$cd passport-azure-ad`
* `$ npm install`
*

YOU NEED TO RUN NPM INSTALL ON THE passport-azure-ad directory as well as the npm has yet to be updated for convergence.

### Step 5: Configure your server using config.js

**NOTE:** You may also pass the `issuer:` value if you wish to validate that as well.

### Step 6: Run the application

* `$ node app.js`

**Is the server output hard to understand?:** We use `bunyan` for logging in this sample. The console won't make much sense to you unless you also install bunyan and run the server like above but pipe it through the bunyan binary:

* `$ npm install -g bunyan`
* `$ node app.js | bunyan`

### You're done!

You will have a server successfully running on `http://localhost:3000`.

### Acknowledgements

We would like to acknowledge the folks who own/contribute to the following projects for their support of Windows Azure Active Directory and their libraries that were used to build this sample. In places where we forked these libraries to add additional functionality, we ensured that the chain of forking remains intact so you can navigate back to the original package. Working with such great partners in the open source community clearly illustrates what open collaboration can accomplish. Thank you!


## About The Code

Code hosted on GitHub under MIT license
181 changes: 181 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
/**
* Copyright (c) Microsoft Corporation
* All Rights Reserved
* Apache License 2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @flow
*/

'use strict';

/**
* Module dependencies.
*/

var express = require('express');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var bodyParser = require('body-parser');
var passport = require('passport');
var util = require('util');
var bunyan = require('bunyan');
var config = require('./config');
var OIDCStrategy = require('./lib/passport-azure-ad/index').OIDCStrategy;

var log = bunyan.createLogger({
name: 'Microsoft OIDC Example Web Application'
});


// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.
passport.serializeUser(function(user, done) {
done(null, user.preferred_username);
});

passport.deserializeUser(function(id, done) {
findByEmail(id, function (err, user) {
done(err, user);
});
});

// array to hold logged in users
var users = [];

var findByEmail = function(email, fn) {
for (var i = 0, len = users.length; i < len; i++) {
var user = users[i];
if (user.preferred_username === email) {
return fn(null, user);
}
}
return fn(null, null);
};

// Use the OIDCStrategy within Passport.
// Strategies in passport require a `validate` function, which accept
// credentials (in this case, an OpenID identifier), and invoke a callback
// with a user object.
passport.use(new OIDCStrategy({
callbackURL: config.creds.returnURL,
realm: config.creds.realm,
clientID: config.creds.clientID,
clientSecret: config.creds.clientSecret,
oidcIssuer: config.creds.issuer,
identityMetadata: config.creds.identityMetadata,
skipUserProfile: true // doesn't fetch user profile
},
function(iss, sub, email, claims, profile, accessToken, refreshToken, done) {
log.info('We received claims of: ', claims);
log.info('Example: Email address we received was: ', claims.preferred_username);
// asynchronous verification, for effect...
process.nextTick(function () {
findByEmail(claims.preferred_username, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
// "Auto-registration"
users.push(claims);
return done(null, claims);
}
return done(null, user);
});
});
}
));




var app = express();

// configure Express
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.logger());
app.use(express.methodOverride());
app.use(cookieParser());
app.use(expressSession({ secret: 'keyboard cat', resave: true, saveUninitialized: false }));
app.use(bodyParser.urlencoded({ extended : true }));
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(__dirname + '/../../public'));
});


app.get('/', function(req, res){
res.render('index', { user: req.user });
});

app.get('/account', ensureAuthenticated, function(req, res){
res.render('account', { user: req.user });
});

app.get('/login',
passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
function(req, res) {
log.info('Login was called in the Sample');
res.redirect('/');
});

// POST /auth/openid
// Use passport.authenticate() as route middleware to authenticate the
// request. The first step in OpenID authentication will involve redirecting
// the user to their OpenID provider. After authenticating, the OpenID
// provider will redirect the user back to this application at
// /auth/openid/return
app.post('/auth/openid',
passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
function(req, res) {
log.info('Authenitcation was called in the Sample');
res.redirect('/');
});

// GET /auth/openid/return
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
app.get('/auth/openid/return',
passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
function(req, res) {
log.info('We received a return from AzureAD.');
res.redirect('/');
});

app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});

app.listen(3000);


// Simple route middleware to ensure user is authenticated.
// Use this route middleware on any resource that needs to be protected. If
// the request is authenticated (typically via a persistent login session),
// the request will proceed. Otherwise, the user will be redirected to the
// login page.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
10 changes: 10 additions & 0 deletions config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Don't commit this file to your public repos. This config is for first-run
//
exports.creds = {
returnURL: 'http://localhost:3000/auth/openid/return',
identityMetadata: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration', // For using Microsoft you should never need to change this.
realm: 'http://localhost:3000',
issuer: 'https://sts.windows.net/519ea014-04c9-4839-9b4a-8a604aff827a/',
clientID: '519ea014-04c9-4839-9b4a-8a604aff827a',
clientSecret: '6wKwKYkcJXAAU9Mc0k4ehhu'
};
7 changes: 7 additions & 0 deletions lib/passport-azure-ad/.flowconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[ignore]

[include]

[libs]

[options]
Loading

0 comments on commit f4d1d65

Please sign in to comment.