Code Monkey home page Code Monkey logo

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

page_type languages products description urlFragment
sample
javascript
nodejs
electron
ms-graph
microsoft-entra-id
Demonstrates how to use MSAL Node to sign-in users and acquire access tokens for a protected resource such as Microsoft Graph in an Electron desktop application using the OAuth 2.0 authorization code flow with PKCE.
ms-identity-javascript-nodejs-desktop

An Electron desktop application using MSAL Node on Microsoft identity platform

This sample demonstrates how to use MSAL Node to sign-in a user and acquire an access token for a protected resource such as Microsoft Graph in an Electron desktop application using the authorization code grant with PKCE flow.

This sample backs the following articles on Microsoft Docs:

ℹ️ Looking for a TypeScript implementation? See: ElectronTestApp

ℹ️ Looking for an Electron with React implementation? See: ElectronSystemBrowserTestApp

⚠️ This sample does not implement persistent caching. See Caching with MSAL Node for more information.

Features

This sample demonstrates the following MSAL Node concepts:

  • Configuration
  • Login and logout
  • Acquiring an access token
  • Calling a web API

Contents

File/folder Description
AppCreationScripts/ Contains Powershell scripts for automating app registration.
App/authProvider.js Main authentication logic resides here.
App/main.js Application main process.
App/graph.js Instantiates Graph SDK client.
App/renderer.js Renderer processes and UI methods.
App/constants.js Example user accounts in JSON .
App/preload.js Give the Renderer process controlled access to some Node API.
App/authConfig.js Configuration objects to be passed to MSAL instance.

Getting Started

Prerequisites

Register and Setup the application

Step 1: Register the application

  1. Navigate to the Microsoft Entra admin center and select the Microsoft Entra ID service.
  2. Select the App Registrations blade on the left, then select New registration.
    1. In the Name section, enter a meaningful application name that will be displayed to users of the app, for example msal-node-desktop.
    2. In the Supported account types section, select Accounts in this organizational directory only.
    3. Select Register to create the application.
  3. In the list of pages for the app, select Authentication.
  4. Select Add a platform, select Mobile and desktop applications
  5. In the Redirect URIs section enter the following redirect URI http://localhost
  6. Select Configure.
Configure Optional Claims
  1. Still on the same app registration, select the Token configuration blade to the left.
  2. Select Add optional claim:
    1. Select optional claim type, then choose ID.
    2. Select the optional claim login_hint.

    An opaque, reliable login hint claim. This claim is the best value to use for the login_hint OAuth parameter in all flows to get SSO. See $optional claims for more details.

    1. Select Add to save your changes.

Step 2: Clone the repository

Clone this repository git clone https://github.com/Azure-Samples/ms-identity-javascript-nodejs-desktop.git

Step 3: Configure the Electron sample project

  1. Open the .authConfig.js file and provide the required configuration values.
    1. Replace the string Enter_the_Application_Id_Here with your app/client ID on Microsoft Entra admin center.
    2. Replace the string Enter_the_Tenant_Info_Here with your tenant ID on Microsoft Entra admin center.
    3. Replace the string Enter_the_Cloud_Instance_Id_Here with https://login.microsoftonline.com/ (include the trailing slash).
    4. Replace the string Enter_the_Graph_Endpoint_Here. with https://graph.microsoft.com/ (include the trailing slash).

step 4: Run the sample

  1. You'll need to install the dependencies of this sample once:
cd ms-identity-javascript-nodejs-desktop
npm install
  1. Then, run the application via command prompt or console:
npm start

Contributing

If you'd like to contribute to this sample, see CONTRIBUTING.MD.

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-desktop's People

Contributors

derisen avatar didunayodeji avatar idg-sam avatar microsoft-github-operations[bot] avatar microsoftopensource avatar salman90 avatar sameerag avatar

Stargazers

 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

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

Link to Electron with React implementation not working

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [x] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Go to https://github.com/Azure-Samples/ms-identity-javascript-nodejs-desktop
Go to the section "ℹ️ Looking for an Electron with React implementation? See: ElectronReactTestApp" in the README.
Click on ElectronReactTestApp and the link will lead to a 404 page.

Expected/desired behavior

A link to an Electron React App example

OS and version?

Any

Versions

latest

Mention any other details that might be useful


Thanks! We'll be in touch soon.

Content overflow on login screen

When creating a new browserwindow object in electron the login page content has an overflow, showing a scrollbar. The scrollbar only moves a tiny amount up and down. Would be better to remove it.

This issue is for a: (mark with an x)

- [ x ] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

This behavior is present in the example app ms-identity-javascript-nodejs-desktop-main

Any log messages given by the failure

Expected/desired behavior

New browserwindow object opens login page without scrollbars (overflow hidden)

OS and version?

Chrome, Other

Versions

2.14.1

Mention any other details that might be useful

ipcMain.handle('login', async () => {

  // create a new electron window
  const authWindow = new BrowserWindow({
    width: 800,
    height: 600,
    show: true,
    frame: false,
    webPreferences: {
      nodeIntegration: false,
    },
  });
  // get token
  const tokenRequest = {
    scopes: [
      'User.Read',
      'Tasks.Read',
      'Group.ReadWrite.All',
      'Directory.ReadWrite.All',
    ],
  };
  const token = await authProvider.getToken(authWindow, tokenRequest);

  // close the auth window
  authWindow.destroy();

  return 'succeeded';
});

Thanks! We'll be in touch soon.

cc @rbWies

ClientAuthError: request_cannot_be_made: Token request cannot be made without authorization code or refresh token.

This issue is for a: (mark with an x)

- [ x] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Follow setup instructions on readme.md

Any log messages given by the failure

[email protected] start
electron App/Main.js

[Tue, 20 Apr 2021 22:17:23 GMT] : : @azure/[email protected] : Info - getAuthCodeUrl called
[Tue, 20 Apr 2021 22:17:23 GMT] : : @azure/[email protected] : Verbose - initializeRequestScopes called
[Tue, 20 Apr 2021 22:17:23 GMT] : : @azure/[email protected] : Verbose - buildOauthClientConfiguration called
[Tue, 20 Apr 2021 22:17:23 GMT] : : @azure/[email protected] : Verbose - createAuthority called
[Tue, 20 Apr 2021 22:17:23 GMT] : : @azure/[email protected] : Verbose - Retrieving all cache keys
[Tue, 20 Apr 2021 22:17:23 GMT] : : @azure/[email protected] : Verbose - Getting cache key-value store
[Tue, 20 Apr 2021 22:17:24 GMT] : : @azure/[email protected] : Verbose - Getting cache key-value store
[Tue, 20 Apr 2021 22:17:24 GMT] : : @azure/[email protected] : Verbose - Setting cache key value store
[Tue, 20 Apr 2021 22:17:24 GMT] : : @azure/[email protected] : Verbose - Auth client config generated
[Tue, 20 Apr 2021 22:17:42 GMT] : : @azure/[email protected] : Info - acquireTokenByCode called
[Tue, 20 Apr 2021 22:17:42 GMT] : : @azure/[email protected] : Verbose - initializeRequestScopes called
[Tue, 20 Apr 2021 22:17:42 GMT] : : @azure/[email protected] : Verbose - buildOauthClientConfiguration called
[Tue, 20 Apr 2021 22:17:42 GMT] : : @azure/[email protected] : Verbose - createAuthority called
[Tue, 20 Apr 2021 22:17:42 GMT] : : @azure/[email protected] : Verbose - Retrieving all cache keys
[Tue, 20 Apr 2021 22:17:42 GMT] : : @azure/[email protected] : Verbose - Getting cache key-value store
[Tue, 20 Apr 2021 22:17:42 GMT] : : @azure/[email protected] : Verbose - Getting cache key-value store
[Tue, 20 Apr 2021 22:17:42 GMT] : : @azure/[email protected] : Verbose - Getting cache key-value store
[Tue, 20 Apr 2021 22:17:42 GMT] : : @azure/[email protected] : Verbose - Setting cache key value store
[Tue, 20 Apr 2021 22:17:42 GMT] : : @azure/[email protected] : Verbose - Auth client config generated
[Tue, 20 Apr 2021 22:17:42 GMT] : : @azure/[email protected] : Info - in acquireToken call
(node:63536) UnhandledPromiseRejectionWarning: ClientAuthError: request_cannot_be_made: Token request cannot be made without authorization code or refresh token.
at ClientAuthError.AuthError [as constructor] (/Users/user/Downloads/ms-identity-javascript-nodejs-desktop-main/node_modules/@azure/msal-common/dist/index.js:398:24)
at new ClientAuthError (/Users/user/Downloads/ms-identity-javascript-nodejs-desktop-main/node_modules/@azure/msal-common/dist/index.js:634:28)
at Function.ClientAuthError.createTokenRequestCannotBeMadeError (/Users/user/Downloads/ms-identity-javascript-nodejs-desktop-main/node_modules/@azure/msal-common/dist/index.js:747:16)
at AuthorizationCodeClient. (/Users/user/Downloads/ms-identity-javascript-nodejs-desktop-main/node_modules/@azure/msal-common/dist/index.js:4364:51)
at step (/Users/user/Downloads/ms-identity-javascript-nodejs-desktop-main/node_modules/@azure/msal-common/dist/index.js:79:23)
at Object.next (/Users/user/Downloads/ms-identity-javascript-nodejs-desktop-main/node_modules/@azure/msal-common/dist/index.js:60:53)
at /Users/user/Downloads/ms-identity-javascript-nodejs-desktop-main/node_modules/@azure/msal-common/dist/index.js:53:71
at new Promise ()
at __awaiter (/Users/user/Downloads/ms-identity-javascript-nodejs-desktop-main/node_modules/@azure/msal-common/dist/index.js:49:12)
at AuthorizationCodeClient.acquireToken (/Users/user/Downloads/ms-identity-javascript-nodejs-desktop-main/node_modules/@azure/msal-common/dist/index.js:4357:16)
(node:63536) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:63536) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.`

Expected/desired behavior

Demo should work

OS and version?

MacOS 10.15.7

Mention any other details that might be useful

I added all the required variables to the .env file.

No code found in URL

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ x ] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Follow README steps

Any log messages given by the failure

(node:9112) UnhandledPromiseRejectionWarning: Error: No code found in URL
at Function. (C:\Users\chsuh\Documents\work\repos\ms-identity-javascript-nodejs-desktop\App\CustomProtocolListener.js:41:18)
(Use electron --trace-warnings ... to show where the warning was created)
(node:9112) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

Expected/desired behavior

I want to use the Sign In but it returns this error

OS and version?

Mac OS 12.4 (I have tried on Windows 11 as well)

Versions

{
"name": "electron-test-app",
"version": "1.0.0",
"description": "A sample Electron application that uses msal-node to acquire tokens",
"main": "Main.js",
"scripts": {
"start": "electron App/Main.js"
},
"keywords": [
"msal-node",
"electron",
"javascript"
],
"author": "",
"license": "MIT",
"devDependencies": {
"babel": "^6.23.0",
"electron": "^18.2.3",
"webpack": "^5.6.0"
},
"dependencies": {
"@azure/msal-node": "^1.0.0",
"axios": "^0.21.4",
"bootstrap": "^4.5.3",
"dotenv": "^8.2.0",
"jquery": "^3.5.1",
"popper.js": "^1.16.1"
}
}

Mention any other details that might be useful


Thanks! We'll be in touch soon.

Error After Build With Electron

Minimal steps to reproduce
I tried to follow the guide: "Tutorial: Access users and call the Microsoft Graph API in an Electron desktop app"
directly from the official Microsoft documents at the url
https://docs.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-nodejs-desktop
but when you run the app it works smoothly while doing the buil via electron-builder, it gives no compilation error but the app when trying to opening it gives the error below.

The problem relates to the AuthProvider.js file, specifically on the line
/ *

  • To demonstrate best security practices, this Electron sample application makes use of
  • a custom file protocol instead of a regular web (https: //) redirect URI in order to
  • handle the redirection step of the authorization flow, as suggested in the OAuth2.0 specification for Native Apps.
  • /
    const CUSTOM_FILE_PROTOCOL_NAME = process.env.REDIRECT_URI.split (':') [0]; // e.g. msal: // redirect

Any log messages given by the failure

Uncaught Exception:
TypeError: Cannot read properties of undefined (reading 'split')
at Object. (.../Desktop/Electron/ElectronDesktopApp/dist/mac-arm64/pippo.app/Contents/Resources/app.asar/App/AuthProvider.js:11:60)
at Module._compile (node:internal/modules/cjs/loader:1116:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1169:10)
at Module.load (node:internal/modules/cjs/loader:988:32)
at Module._load (node:internal/modules/cjs/loader:829:12)
at Function.c._load (node:electron/js2c/asar_bundle:5:13343)
at Module.require (node:internal/modules/cjs/loader:1012:19)
at require (node:internal/modules/cjs/

OS and Version?

macOS 12.3 Monterey

Versions
{
"name": "pippo",
"productName": "pippo",
"description": "pippo",
"version": "1.0.4",
"main": "App/main.js",
"license": "ISC",
"icon": "images/icon.icns",
"author": "pippo",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"start": " electron .",
"dist": "electron-builder"
},
"keywords": [],
"dependencies": {
"@azure/msal-node": "^1.9.0",
"axios": "^0.27.2",
"bindings": "^1.5.0",
"bootstrap": "^5.1.3",
"dotenv": "^16.0.1",
"jquery": "^3.6.0",
"popper.js": "^1.16.1"
},
"devDependencies": {
"babel": "^6.23.0",
"electron": "^18.2.3",
"electron-builder": "^23.0.3",
"webpack": "^5.72.1"
},
"build": {
"appId": "com.pippo.app",
"icon": "images/icon.icns",
"copyright": "Copyright © 2022 ${author}"
}
}

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.