Skip to content

Instantly share code, notes, and snippets.

@sangheestyle
Last active November 19, 2018 18:41
Show Gist options
  • Save sangheestyle/46d1f5f8d844cecc00c530acb492bf9c to your computer and use it in GitHub Desktop.
Save sangheestyle/46d1f5f8d844cecc00c530acb492bf9c to your computer and use it in GitHub Desktop.
Practice adal node.js
{
"name": "practice_adal",
"version": "0.0.1",
"description": "Nothing special",
"main": "index.js",
"scripts": {
"start": "ts-node server.ts"
},
"author": "",
"license": "ISC",
"dependencies": {
"adal-node": "^0.1.28",
"express": "^4.16.4",
"morgan": "^1.9.1"
},
"devDependencies": {
"@types/express": "^4.16.0",
"@types/morgan": "^1.7.35",
"@types/node": "^10.12.9"
}
}
// Requirement:
// Generate key pairs:
// ```
// openssl genrsa -out server.pem 2048
// openssl req -new -key server.pem -out server.csr
// openssl x509 -req -days 365 -in server.csr -signkey server.pem -out server.crt
// ```
// Upload server.crt to admin console
import * as express from 'express';
import * as morgan from "morgan";
import * as fs from 'fs';
import { AuthenticationContext } from 'adal-node';
function getPrivateKey(filename: string): string {
return fs.readFileSync(filename, { encoding: 'utf8' });
}
const params = {
tenant: 'finlandhelsinki.onmicrosoft.com',
authorityHostUrl: 'https://login.windows.net',
clientId: 'c0ad8f06-d5d7-482f-b8a7-972fa831c91a',
thumbprint: '7BB17F9BCD1C1CB949F1002FB29F7D3050F55962',
privateKeyFile: 'server.pem',
resource: 'https://outlook.office365.com/',
};
const authorityUrl: string = params.authorityHostUrl + '/' + params.tenant;
const app: express.Application = express();
const port: number = 3000;
const context = new AuthenticationContext(authorityUrl);
const key = getPrivateKey(params.privateKeyFile);
app.use(morgan('dev'));
app.get('/token', (req, res) => {
context.acquireTokenWithClientCertificate(
params.resource,
params.clientId,
key,
params.thumbprint,
(err, tokenResponse) => {
if (err) {
res.send('well that didn\'t work: ' + err.stack);
} else {
res.send(tokenResponse);
}
}
);
});
app.listen(port, () => {
console.log(`token app listening on port ${port}!`);
console.log(`Try: curl http://localhost:3000/token`);
});
@sangheestyle
Copy link
Author

sangheestyle commented Nov 19, 2018

Result:

{
    tokenType: "Bearer",
    expiresIn: 3599,
    expiresOn: "2018-11-19T19:31:07.515Z",
    resource: "https://outlook.office365.com/",
    accessToken: "JWT",
    isMRRT: true,
    _clientId: "{your client id}",
    _authority: "https://login.windows.net/{your tenant name}.onmicrosoft.com"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment