2
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
3
* Licensed under the MIT License.
4
4
*/
5
-
6
- //initialize express
7
5
const express = require ( "express" ) ;
8
- const app = express ( ) ;
9
- const port = 3000 ;
10
- app . get ( '/' , ( req , res ) => redirectToAzureAd ( req , res ) ) ;
11
- app . get ( '/redirect' , ( req , res ) => acquireToken ( req , res ) ) ;
6
+ const msal = require ( '@azure/msal-node' ) ;
7
+
8
+ const SERVER_PORT = process . env . PORT || 3000 ;
12
9
13
10
// initialize msal public client application
14
- let msal = require ( '@azure/msal-node' ) ;
15
11
const publicClientConfig = {
16
12
auth : {
17
13
clientId : "99cab759-2aab-420b-91d8-5e3d8d4f063b" ,
@@ -24,27 +20,27 @@ const publicClientConfig = {
24
20
storeAuthStateInCookie : false // Set this to "true" if you are having issues on IE11 or Edge
25
21
}
26
22
} ;
27
-
28
23
const pca = new msal . PublicClientApplication ( publicClientConfig ) ;
29
24
30
- app . listen ( port , ( ) => console . log ( `Example app listening on port ${ port } !` ) )
31
-
32
- function redirectToAzureAd ( req , res ) {
25
+ // Create Express App and Routes
26
+ const app = express ( ) ;
33
27
28
+ app . get ( '/' , ( req , res ) => {
34
29
const authCodeUrlParameters = {
35
30
scopes : [ "user.read" ] ,
36
31
redirectUri : [ "http://localhost:3000/redirect" ] ,
37
32
} ;
38
33
34
+ // get url to sign user in and consent to scopes needed for application
39
35
pca . getAuthCodeUrl ( authCodeUrlParameters )
40
36
. then ( ( response ) => {
41
37
console . log ( response ) ;
42
38
res . redirect ( response ) ;
43
39
} )
44
40
. catch ( ( error ) => console . log ( JSON . stringify ( error ) ) ) ;
45
- }
41
+ } ) ;
46
42
47
- function acquireToken ( req , res ) {
43
+ app . get ( '/redirect' , ( req , res ) => {
48
44
const tokenRequest = {
49
45
code : req . query . code ,
50
46
redirectUri : "http://localhost:3000/redirect" ,
@@ -54,9 +50,11 @@ function acquireToken(req, res){
54
50
55
51
pca . acquireTokenByCode ( tokenRequest ) . then ( ( response ) => {
56
52
console . log ( JSON . stringify ( response ) ) ;
57
- res . send ( 200 ) ;
53
+ res . status ( 200 ) . json ( response ) ;
58
54
} ) . catch ( ( error ) => {
59
- res . send ( 500 ) ;
60
55
console . log ( JSON . stringify ( error . response ) ) ;
56
+ res . status ( 500 ) . send ( JSON . stringify ( error . response ) ) ;
61
57
} )
62
- }
58
+ } ) ;
59
+
60
+ app . listen ( SERVER_PORT , ( ) => console . log ( `Msal Node Auth Code Sample app listening on port ${ SERVER_PORT } !` ) )
0 commit comments