Skip to content

Commit f4d1d65

Browse files
committed
Initial commit from Samples
0 parents  commit f4d1d65

36 files changed

+3907
-0
lines changed

LICENSE

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) 2015 Microsoft Azure Active Directory Samples and Documentation
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.
22+

README.md

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#Windows Azure Active Directory OIDC Web API Sample
2+
3+
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.
4+
5+
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.
6+
7+
8+
## Quick Start
9+
10+
Getting started with the sample is easy. It is configured to run out of the box with minimal setup.
11+
12+
### Step 1: Register a Windows Azure AD Tenant
13+
14+
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.
15+
16+
### Step 2: Register your Web API with your Windows Azure AD Tenant
17+
18+
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)
19+
20+
### Step 3: Download node.js for your platform
21+
To successfully use this sample, you need a working installation of Node.js.
22+
23+
### Step 4: Download the Sample application and modules
24+
25+
Next, clone the sample repo and install the NPM.
26+
27+
From your shell or command line:
28+
29+
* `$ git clone [email protected]:AzureADSamples/Convergence-OpenIDConnect-Nodejs.git`
30+
* `$ npm install`
31+
* `$cd passport-azure-ad`
32+
* `$ npm install`
33+
*
34+
35+
YOU NEED TO RUN NPM INSTALL ON THE passport-azure-ad directory as well as the npm has yet to be updated for convergence.
36+
37+
### Step 5: Configure your server using config.js
38+
39+
**NOTE:** You may also pass the `issuer:` value if you wish to validate that as well.
40+
41+
### Step 6: Run the application
42+
43+
* `$ node app.js`
44+
45+
**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:
46+
47+
* `$ npm install -g bunyan`
48+
* `$ node app.js | bunyan`
49+
50+
### You're done!
51+
52+
You will have a server successfully running on `http://localhost:3000`.
53+
54+
### Acknowledgements
55+
56+
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!
57+
58+
59+
## About The Code
60+
61+
Code hosted on GitHub under MIT license

app.js

+181
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
/**
2+
* Copyright (c) Microsoft Corporation
3+
* All Rights Reserved
4+
* Apache License 2.0
5+
*
6+
* Licensed under the Apache License, Version 2.0 (the "License");
7+
* you may not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*
17+
* @flow
18+
*/
19+
20+
'use strict';
21+
22+
/**
23+
* Module dependencies.
24+
*/
25+
26+
var express = require('express');
27+
var cookieParser = require('cookie-parser');
28+
var expressSession = require('express-session');
29+
var bodyParser = require('body-parser');
30+
var passport = require('passport');
31+
var util = require('util');
32+
var bunyan = require('bunyan');
33+
var config = require('./config');
34+
var OIDCStrategy = require('./lib/passport-azure-ad/index').OIDCStrategy;
35+
36+
var log = bunyan.createLogger({
37+
name: 'Microsoft OIDC Example Web Application'
38+
});
39+
40+
41+
// Passport session setup.
42+
// To support persistent login sessions, Passport needs to be able to
43+
// serialize users into and deserialize users out of the session. Typically,
44+
// this will be as simple as storing the user ID when serializing, and finding
45+
// the user by ID when deserializing.
46+
passport.serializeUser(function(user, done) {
47+
done(null, user.preferred_username);
48+
});
49+
50+
passport.deserializeUser(function(id, done) {
51+
findByEmail(id, function (err, user) {
52+
done(err, user);
53+
});
54+
});
55+
56+
// array to hold logged in users
57+
var users = [];
58+
59+
var findByEmail = function(email, fn) {
60+
for (var i = 0, len = users.length; i < len; i++) {
61+
var user = users[i];
62+
if (user.preferred_username === email) {
63+
return fn(null, user);
64+
}
65+
}
66+
return fn(null, null);
67+
};
68+
69+
// Use the OIDCStrategy within Passport.
70+
// Strategies in passport require a `validate` function, which accept
71+
// credentials (in this case, an OpenID identifier), and invoke a callback
72+
// with a user object.
73+
passport.use(new OIDCStrategy({
74+
callbackURL: config.creds.returnURL,
75+
realm: config.creds.realm,
76+
clientID: config.creds.clientID,
77+
clientSecret: config.creds.clientSecret,
78+
oidcIssuer: config.creds.issuer,
79+
identityMetadata: config.creds.identityMetadata,
80+
skipUserProfile: true // doesn't fetch user profile
81+
},
82+
function(iss, sub, email, claims, profile, accessToken, refreshToken, done) {
83+
log.info('We received claims of: ', claims);
84+
log.info('Example: Email address we received was: ', claims.preferred_username);
85+
// asynchronous verification, for effect...
86+
process.nextTick(function () {
87+
findByEmail(claims.preferred_username, function(err, user) {
88+
if (err) {
89+
return done(err);
90+
}
91+
if (!user) {
92+
// "Auto-registration"
93+
users.push(claims);
94+
return done(null, claims);
95+
}
96+
return done(null, user);
97+
});
98+
});
99+
}
100+
));
101+
102+
103+
104+
105+
var app = express();
106+
107+
// configure Express
108+
app.configure(function() {
109+
app.set('views', __dirname + '/views');
110+
app.set('view engine', 'ejs');
111+
app.use(express.logger());
112+
app.use(express.methodOverride());
113+
app.use(cookieParser());
114+
app.use(expressSession({ secret: 'keyboard cat', resave: true, saveUninitialized: false }));
115+
app.use(bodyParser.urlencoded({ extended : true }));
116+
// Initialize Passport! Also use passport.session() middleware, to support
117+
// persistent login sessions (recommended).
118+
app.use(passport.initialize());
119+
app.use(passport.session());
120+
app.use(app.router);
121+
app.use(express.static(__dirname + '/../../public'));
122+
});
123+
124+
125+
app.get('/', function(req, res){
126+
res.render('index', { user: req.user });
127+
});
128+
129+
app.get('/account', ensureAuthenticated, function(req, res){
130+
res.render('account', { user: req.user });
131+
});
132+
133+
app.get('/login',
134+
passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
135+
function(req, res) {
136+
log.info('Login was called in the Sample');
137+
res.redirect('/');
138+
});
139+
140+
// POST /auth/openid
141+
// Use passport.authenticate() as route middleware to authenticate the
142+
// request. The first step in OpenID authentication will involve redirecting
143+
// the user to their OpenID provider. After authenticating, the OpenID
144+
// provider will redirect the user back to this application at
145+
// /auth/openid/return
146+
app.post('/auth/openid',
147+
passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
148+
function(req, res) {
149+
log.info('Authenitcation was called in the Sample');
150+
res.redirect('/');
151+
});
152+
153+
// GET /auth/openid/return
154+
// Use passport.authenticate() as route middleware to authenticate the
155+
// request. If authentication fails, the user will be redirected back to the
156+
// login page. Otherwise, the primary route function function will be called,
157+
// which, in this example, will redirect the user to the home page.
158+
app.get('/auth/openid/return',
159+
passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
160+
function(req, res) {
161+
log.info('We received a return from AzureAD.');
162+
res.redirect('/');
163+
});
164+
165+
app.get('/logout', function(req, res){
166+
req.logout();
167+
res.redirect('/');
168+
});
169+
170+
app.listen(3000);
171+
172+
173+
// Simple route middleware to ensure user is authenticated.
174+
// Use this route middleware on any resource that needs to be protected. If
175+
// the request is authenticated (typically via a persistent login session),
176+
// the request will proceed. Otherwise, the user will be redirected to the
177+
// login page.
178+
function ensureAuthenticated(req, res, next) {
179+
if (req.isAuthenticated()) { return next(); }
180+
res.redirect('/login')
181+
}

config.js

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Don't commit this file to your public repos. This config is for first-run
2+
//
3+
exports.creds = {
4+
returnURL: 'http://localhost:3000/auth/openid/return',
5+
identityMetadata: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration', // For using Microsoft you should never need to change this.
6+
realm: 'http://localhost:3000',
7+
issuer: 'https://sts.windows.net/519ea014-04c9-4839-9b4a-8a604aff827a/',
8+
clientID: '519ea014-04c9-4839-9b4a-8a604aff827a',
9+
clientSecret: '6wKwKYkcJXAAU9Mc0k4ehhu'
10+
};

lib/passport-azure-ad/.flowconfig

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
[ignore]
2+
3+
[include]
4+
5+
[libs]
6+
7+
[options]

0 commit comments

Comments
 (0)