Coder Social home page Coder Social logo

azure-samples / ms-identity-javascript-nodejs-tutorial Goto Github PK

View Code? Open in Web Editor NEW
37.0 35.0 29.0 4.38 MB

A chapterwise tutorial that will take you through the fundamentals of modern authentication with the Microsoft identity platform in Node.js using MSAL Node

Home Page: https://aka.ms/aadv2

License: MIT License

JavaScript 20.39% HTML 0.34% CSS 0.64% EJS 9.69% PowerShell 57.26% TypeScript 11.67%
microsoft-identity-platform azure-active-directory azure-ad-b2c ms-graph oauth2 authentication authorization msal-node msal azure-app-service

ms-identity-javascript-nodejs-tutorial's Introduction

page_type languages products description urlFragment
sample
javascript
typescript
node-js
ms-graph
msal-node
azure-app-service
azure-key-vault
azure-resource-manager
azure-active-directory
azure-active-directory-b2c
microsoft-identity-platform
Tutorial: Enable your Node.js & Express web app to sign-in users and call APIs with the Microsoft identity platform
ms-identity-javascript-nodejs-tutorial

Tutorial: Enable your Node.js & Express web app to sign-in users and call APIs with the Microsoft identity platform

Build Code Scan GitHub issues npm GitHub

The Microsoft identity platform, along with Azure Active Directory (Azure AD) and Azure Active Directory B2C (Azure AD B2C) are central to the Azure cloud ecosystem. This tutorial aims to take you through the fundamentals of modern authentication with Node.js, using the Microsoft Authentication Library for Node.js (MSAL Node).

This tutorial also features a simple wrapper around MSAL Node ConfidentialClientApplication class in order to streamline routine authentication tasks such as login, logout, token acquisition. You can find the wrapper here: msal-node-wrapper. Fork it and customize as you need. Suggestions and contributions are welcome!

⚠️ msal-node-wrapper is for demo purposes only and is not recommended for production applications. If you're looking for using MSAL Node directly in your web app, please refer to:

We recommend following the chapters in successive order. However, the code samples are self-contained, so feel free to pick samples by topics that you may need at the moment.

⚠️ This is a work in progress. Come back frequently to discover more samples.

Prerequisites

Please refer to each chapter's README for sample-specific prerequisites.

Recommendations

  • jwt.ms for inspecting your tokens
  • Fiddler for monitoring your network activity and troubleshooting
  • Check the MSAL Node FAQ for your questions first
  • Follow the Azure AD Blog to stay up-to-date with the latest developments

Please refer to each chapter's README for sample-specific recommendations.

Contents

Chapter 1: Add Authentication to your web app

Sign-in with Azure AD
Sign-in your users with Azure AD and learn to work with ID Tokens.
Sign-in with Azure AD B2C
Sign-in your customers with Azure AD B2C. Learn to integrate with external social identity providers. Learn how to use user-flows and custom policies.

Chapter 2: Sign-in a user and get an Access Token for Microsoft Graph

Get an Access Token from Azure AD and call Microsoft Graph
Authenticate your users and acquire an Access Token for Microsoft Graph and then call the Microsoft Graph API.

Chapter 3: Deploy your app to Azure

Deploy to Azure App Service
Prepare your app for deployment to various Azure services. Learn how to package and upload files, configure authentication parameters and use Azure services for managing your operations.

Chapter 4: Control access to your app using App Roles and Security Groups

Use App Roles for access control
Define App Roles and use roles claim in a token to implement Role-based Access Control (RBAC) for your web app.
Use Security Groups for access control
Create Security Groups and use groups claim in a token to implement Role-based Access Control (RBAC) for your web app.

Chapter 5: Dive into advanced scenarios

Authenticate using Backend for Frontend proxy
Sign-in users via the Backend for Frontend proxy pattern in a React SPA hosted on top of a Node.js & Express web app using MSAL Node.

We'd love your feedback

Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.

More information

Learn more about the Microsoft identity platform:

See more code samples:

Community Help and Support

Use Stack Overflow to get support from the community. Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before. Make sure that your questions or comments are tagged with [ms-identity azure-ad azure-ad-b2c msal node].

If you find a bug in the sample, please raise the issue on GitHub Issues.

To provide a recommendation, visit the following User Voice page.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

ms-identity-javascript-nodejs-tutorial's People

Contributors

aremo-ms avatar bgavrilms avatar dependabot[bot] avatar derisen avatar idg-sam avatar kalyankrishna1 avatar microsoft-github-operations[bot] avatar robbie-microsoft avatar salman90 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ms-identity-javascript-nodejs-tutorial's Issues

Error on start page

Issue

Please provide us with the following information:

This issue is for the sample

    - [ ] 1-1) Sign-in with Azure AD
    - [ ] 1-2) Sign-in with Azure AD B2C
    - [ ] 2-1) Acquire a Token and call Microsoft Graph
    - [ ]   3) Deploy to Azure Storage and App Service
    - [ ] 4-1) Use App Roles for Role-based Access Control
    - [x] 4-2) Use Security Groups for Role-based Access Control

This issue is for a

    - [x] bug report -> please search issues before submitting
    - [ ] question
    - [ ] feature request
    - [ ] documentation issue or request

Minimal steps to reproduce

All steps describle in https://github.com/Azure-Samples/ms-identity-javascript-nodejs-tutorial/blob/main/4-AccessControl/2-security-groups/README.md#running-the-sample.
Error in npm start

Any log messages given by the failure

npm start

[email protected] start
node app.js

node:internal/modules/cjs/loader:959
throw err;
^

Error: Cannot find module 'jwks-rsa'
Require stack:

  • C:\Geral\Func-React-WebApp\ms-identity-javascript-nodejs-tutorial-main\4-AccessControl\2-security-groups\App\node_modules\microsoft-identity-express\dist\microsoft-identity-express.cjs.development.js
  • C:\Geral\Func-React-WebApp\ms-identity-javascript-nodejs-tutorial-main\4-AccessControl\2-security-groups\App\node_modules\microsoft-identity-express\dist\index.js
  • C:\Geral\Func-React-WebApp\ms-identity-javascript-nodejs-tutorial-main\4-AccessControl\2-security-groups\App\app.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:956:15)
    at Function.Module._load (node:internal/modules/cjs/loader:804:27)
    at Module.require (node:internal/modules/cjs/loader:1028:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object. (C:\Geral\Func-React-WebApp\ms-identity-javascript-nodejs-tutorial-main\4-AccessControl\2-security-groups\App\node_modules\microsoft-identity-express\dist\microsoft-identity-express.cjs.development.js:11:34)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
    at Module.load (node:internal/modules/cjs/loader:1004:32)
    at Function.Module._load (node:internal/modules/cjs/loader:839:12)
    at Module.require (node:internal/modules/cjs/loader:1028:19) {
    code: 'MODULE_NOT_FOUND',
    requireStack: [
    'C:\Geral\Func-React-WebApp\ms-identity-javascript-nodejs-tutorial-main\4-AccessControl\2-security-groups\App\node_modules\microsoft-identity-express\dist\microsoft-identity-express.cjs.development.js',
    'C:\Geral\Func-React-WebApp\ms-identity-javascript-nodejs-tutorial-main\4-AccessControl\2-security-groups\App\node_modules\microsoft-identity-express\dist\index.js',
    'C:\Geral\Func-React-WebApp\ms-identity-javascript-nodejs-tutorial-main\4-AccessControl\2-security-groups\App\app.js'
    ]
    }

Re-Install and Re-start

new error:
npm start

[email protected] start
node app.js

C:\Geral\Func-React-WebApp\ms-identity-javascript-nodejs-tutorial-main\1-Authentication\1-sign-in\App\node_modules\microsoft-identity-express.cjs.development.js:1056
throw new Error(ConfigurationErrorMessages.NO_ERROR_ROUTE);
^

Error: No error route provided!

Create node in App\appSettings.js

error: "/error",

authRoutes: {
    redirect: "/redirect",
    error: "/error",
    unauthorized: "/unauthorized" // the wrapper will redirect to this route in case of unauthorized access attempt.
}

Expected/desired behavior

Library version

Browser and version

Edge

Mention any other details that might be useful

Thanks! We'll be in touch soon.

After npm start > Login > Token issue

Issue

ClientAuthError: request_cannot_be_made: Token request cannot be made without authorization code or refresh token.
    at ClientAuthError.AuthError [as constructor] (/Users/michaelwalker/WebstormProjects/ms-identity-javascript-nodejs-tutorial/2-Authorization/1-call-graph/App/node_modules/@azure/msal-common/dist/index.cjs.js:477:24)

Screen Shot 2022-04-13 at 5 53 24 AM

This issue is for the sample

    - [ ] 1-1) Sign-in with Azure AD
    - [ ] 1-2) Sign-in with Azure AD B2C
    - [x ] 2-1) Acquire a Token and call Microsoft Graph
    - [ ]   3) Deploy to Azure Storage and App Service
    - [ ] 4-1) Use App Roles for Role-based Access Control
    - [ ] 4-2) Use Security Groups for Role-based Access Control

This issue is for a

    - [ ] bug report -> please search issues before submitting
    - [ ] question
    - [ ] feature request
    - [ x] documentation issue or request

Minimal steps to reproduce

Input all necessary appSettiings.js things
Go to http://localhost:4000/home
Click Signin > Finish Oauth flow > Error Page

Any log messages given by the failure

See above

Expected/desired behavior

Match screen shot in readme

Library version

Most recent

Browser and version

Chrome, Edge, Firefox, Safari?

  • Chrome

Mention any other details that might be useful

Thanks! We'll be in touch soon.

ClientAuthError: network_error: Network request failed. Please check network trace to determine root cause. | Fetch client threw: Error: HTTP status code 401 | Attempted to reach:

ClientAuthError: network_error: Network request failed. Please check network trace to determine root cause. | Fetch client threw: Error: HTTP status code 401 | Attempted to reach:

Issue

Please provide us with the following information:

This issue is for the sample

    - [ ] 1-1) Sign-in with Azure AD
    - [ ] 1-2) Sign-in with Azure AD B2C
    - [ ] 2-1) Acquire a Token and call Microsoft Graph
    - [ ]   3) Deploy to Azure Storage and App Service
    - [ ] 4-1) Use App Roles for Role-based Access Control
    - [ ] 4-2) Use Security Groups for Role-based Access Control

This issue is for a

    - [ ] bug report -> please search issues before submitting
    - [ ] question
    - [ ] feature request
    - [ ] documentation issue or request

Minimal steps to reproduce

Any log messages given by the failure

Expected/desired behavior

Library version

Browser and version

Chrome, Edge, Firefox, Safari?

Mention any other details that might be useful

Thanks! We'll be in touch soon.

invalid_grant when running against fabrikam b2c tenant

Issue

Please provide us with the following information:

This issue is for the sample

    - [ ] 1-1) Sign-in with Azure AD
    - [x] 1-2) Sign-in with Azure AD B2C
    - [ ] 2-1) Acquire a Token and call Microsoft Graph
    - [ ]   3) Deploy to Azure Storage and App Service
    - [ ] 4-1) Use App Roles for Role-based Access Control
    - [ ] 4-2) Use Security Groups for Role-based Access Control

This issue is for a

    - [x] bug report -> please search issues before submitting
    - [ ] question
    - [ ] feature request
    - [ ] documentation issue or request

Minimal steps to reproduce

  1. follow steps outlined in README for https://github.com/Azure-Samples/ms-identity-javascript-nodejs-tutorial/blob/main/1-Authentication/2-sign-in-b2c/
  2. Browse to the app at http://localhost:4000/
  3. Signup for an account
  4. Response is

Any log messages given by the failure

ServerError: invalid_grant: undefined - [undefined]: AADB2C90085: The service has encountered an internal error. Please reauthenticate and try again.

Correlation ID: f2dfd3cc-1b63-4ac5-96a1-3c92f0d37eba

Timestamp: 2021-11-24 11:39:35Z

  • Correlation ID: undefined - Trace ID: undefined
    at ServerError.AuthError [as constructor] (C:\tmp\ms-identity-javascript-nodejs-tutorial\1-Authentication\2-sign-in-b2cC:\tmp\App\1-Authentication\2-sign-in-b2c/\node_modules@azure\msal-common\dist\index.cjs.js:477:24)
    at new ServerError (C:\tmp\ms-identity-javascript-nodejs-tutorial\1-Authentication\2-sign-in-b2cC:\tmp\App\1-Authentication\2-sign-in-b2c/\node_modules@azure\msal-common\dist\index.cjs.js:3060:28)
    at ResponseHandler.validateTokenResponse (C:\tmp\ms-identity-javascript-nodejs-tutorial\1-Authentication\2-sign-in-b2cC:\tmp\App\1-Authentication\2-sign-in-b2c/\node_modules@azure\msal-common\dist\index.cjs.js:4565:19)
    at AuthorizationCodeClient. (C:\tmp\ms-identity-javascript-nodejs-tutorial\1-Authentication\2-sign-in-b2cC:\tmp\App\1-Authentication\2-sign-in-b2c/\node_modules@azure\msal-common\dist\index.cjs.js:4826:41)
    at step (C:\tmp\ms-identity-javascript-nodejs-tutorial\1-Authentication\2-sign-in-b2cC:\tmp\App\1-Authentication\2-sign-in-b2c/\node_modules@azure\msal-common\dist\index.cjs.js:79:23)
    at Object.next (C:\tmp\ms-identity-javascript-nodejs-tutorial\1-Authentication\2-sign-in-b2cC:\tmp\App\1-Authentication\2-sign-in-b2c/\node_modules@azure\msal-common\dist\index.cjs.js:60:53)
    at fulfilled (C:\tmp\ms-identity-javascript-nodejs-tutorial\1-Authentication\2-sign-in-b2cC:\tmp\App\1-Authentication\2-sign-in-b2c/\node_modules@azure\msal-common\dist\index.cjs.js:50:58)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

Expected/desired behavior

That I should be able to sign in

Library version

As in the github repo of today
"dependencies": {
"@azure/msal-node": "^1.3.2",
"microsoft-identity-express": "git+https://github.com/Azure-Samples/microsoft-identity-express.git",
"axios": "^0.21.2",
"body-parser": "^1.19.0",
"bootstrap": "^4.5.3",
"ejs": "^3.0.1",
"express": "^4.17.1",
"express-session": "^1.17.1"
},

Browser and version

You get the error in all 4 browsers

Chrome, Edge, Firefox, Safari?

Mention any other details that might be useful

I bet that the client secrets for the app c5f4d666-c952-402b-8e3d-b005fae1ac64 has expired

Thanks! We'll be in touch soon.

Please Fix the following issue I was having when running npm start in sample \4-AccessControl\2-security-groups

npm start
node server.js

internal/modules/cjs/loader.js:316
throw err;
^

Error: Cannot find module 'D:\WORKSPACE\AAD\aad-nodejs-groups\4-AccessControl\2-security-groups\App\node_modules\msal-node-wrapper\dist\index.js'. Please verify that the package.json has a valid "main" entry
at tryPackage (internal/modules/cjs/loader.js:308:19)
at Function.Module._findPath (internal/modules/cjs/loader.js:521:18)
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:872:27)
at Function.Module._load (internal/modules/cjs/loader.js:730:27)
at Module.require (internal/modules/cjs/loader.js:957:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object. (D:\WORKSPACE\AAD\aad-nodejs-groups\4-AccessControl\2-security-groups\App\app.js:9:32)
at Module._compile (internal/modules/cjs/loader.js:1068:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:933:32) {
code: 'MODULE_NOT_FOUND',
path: 'D:\WORKSPACE\AAD\aad-nodejs-groups\4-AccessControl\2-security-groups\App\node_modules\msal-node-wrapper\package.json',
requestPath: 'msal-node-wrapper'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: node server.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Usage of refresh token

Issue

This issue is for the sample

    - [x] 1-1) Sign-in with Azure AD

This issue is for a

    - [ x] question
    - [x] feature request
    - [x] documentation issue or request

I've been testing the mentioned sample with success. However, I think the sample is missing a correct handling of refresh_tokens. I think it would be a great add on to the example. Could you provide me a confirmation that my idea of usage is correct?

  1. Save the refresh token also in the req.session object.
  2. Change the isAuthenticated function to validate id_token expiration time.
  3. If token is expired, acquire a new id_token using the refresh_token. If refresh_token has also expired, return false and clear session cache.

Thank you very much for your work.

Error: No error route provided!

Issue

Please provide us with the following information:
When I tried to run locally after app registration and appSetting configuration, I get error.
Error: No error route provided!

This issue is for the sample

    - [X] 1-1) Sign-in with Azure AD
    - [ ] 1-2) Sign-in with Azure AD B2C
    - [ ] 2-1) Acquire a Token and call Microsoft Graph
    - [ ]   3) Deploy to Azure Storage and App Service
    - [ ] 4-1) Use App Roles for Role-based Access Control
    - [ ] 4-2) Use Security Groups for Role-based Access Control

This issue is for a

    - [ ] bug report -> please search issues before submitting
    - [ ] question
    - [ ] feature request
    - [X] documentation issue or request

Minimal steps to reproduce

Follow the instruction for 1-1 sign in Authentication

Any log messages given by the failure

Expected/desired behavior

Library version

Browser and version

Chrome, Edge, Firefox, Safari?

Mention any other details that might be useful

Thanks! We'll be in touch soon.

ACTION REQUIRED: Microsoft needs this private repository to complete compliance info

There are open compliance tasks that need to be reviewed for your ms-identity-javascript-nodejs-tutorial repo.

Action required: 2 compliance tasks

To bring this repository to the standard required for 2021, we require administrators of this and all Microsoft GitHub repositories to complete a small set of tasks within the next 60 days. This is critical work to ensure the compliance and security of your Azure-Samples GitHub organization.

Please take a few minutes to complete the tasks at: https://repos.opensource.microsoft.com/orgs/Azure-Samples/repos/ms-identity-javascript-nodejs-tutorial/compliance

  • The GitHub AE (GitHub inside Microsoft) migration survey has not been completed for this private repository
  • Classification of the repository as production/non-production is missing in the Compliance tab.

You can close this work item once you have completed the compliance tasks, or it will automatically close within a day of taking action.

If you no longer need this repository, it might be quickest to delete the repo, too.

GitHub inside Microsoft program information

More information about GitHub inside Microsoft and the new GitHub AE product can be found at https://aka.ms/gim.

FYI: current admins at Microsoft include @gsacavdm, @jasonnutter, @RandalliLama, @skwan, @brandwe, @rayluo, @mvrak, @lnalepa, @kalyankrishna1, @Sammak, @brentschmaltz, @iambmelt, @dstrockis

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.