Coder Social home page Coder Social logo

azure-samples / active-directory-b2c-msal-node-sign-in-sign-out-webapp Goto Github PK

View Code? Open in Web Editor NEW
16.0 13.0 14.0 83 KB

MSAL-node web app for signing in and out, update profile, and reset password with Azure AD B2C user flows

License: MIT License

Shell 8.53% JavaScript 70.05% Handlebars 21.42%

active-directory-b2c-msal-node-sign-in-sign-out-webapp's Introduction

page_type languages products description urlFragment
sample
javascript
msal-node
azure-active-directory-b2c
microsoft-identity-platform
Enable authentication in your own Node web application using Azure AD B2C
active-directory-b2c-msal-node-sign-in-sign-out-webapp

Enable authentication in your own Node web application and web API using Azure AD B2C

This sample web app uses Azure Active Directory B2C (Azure AD B2C) user flows and the Microsoft Authentication Library (MSAL) (msal-node) to enable authentication in your own Node web application and web API using Azure AD B2C.

Resources

active-directory-b2c-msal-node-sign-in-sign-out-webapp's People

Contributors

kengaderdus avatar microsoft-github-operations[bot] avatar microsoftopensource avatar

Stargazers

 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

active-directory-b2c-msal-node-sign-in-sign-out-webapp's Issues

After clicking on 'revoke sessions' in Azure B2C user profile, the user still appears logged in in Node app

This issue is for a:

- [  X ] documentation issue or request

I am just learning how to do B2C authentication.

Because I have to frequently test the sign in process, I need to somehow 'sign out', so that I can 'sign in' again.

I thought that I could do this by clicking on 'revoke sessions' in Azure AD B2C > Users > User profile .

But after I do this, restart the Node app, and click on the 'Sign In' link again, 'nothing happens' - or rather the Node app returns the AuthToken value as if the user is already signed in.

Minimal steps to reproduce

  • Call the signin route and sign in
  • The user will see the redirect page (this is the desired behaviour)
  • Go to Azure AD B2C > Users > User profile and click on 'revoke sessions' button
  • Stop local Node application
  • Start local Node application
  • Call the signin route again
  • Nothing happens on the frontend, but in the backend Node logs the AuthToken value as if the user is already signed in

Any log messages given by the failure

There are no error messages, but calling the signin route the second time returns the AuthToken value (which it shouldn't cause the user should have been signed out).

Expected/desired behavior

When calling the signin route the second time, I am expecting to see the login form again, so the user can sign in again.

Versions

"@azure/msal-node": "^1.14.4",
"express-session": "^1.17.3",

(Edit: I am able to call the 'signout' route to sign the user out, but would still be interested to know why revoke sessions doesn't force sign the user out)

How to do you make subsequent calls to your own web app API after 'sign in'?

This issue is for a:

- [ X ] documentation issue or request

I've been able to implement the 'sign in' logic within this repo.

But now I want to authenticate subsequent calls to my web app's API, i.e. my Express app's routes.

This repo doesn't seem to cover how to do this.

Below is a summary of what I have done so far.

Firstly, I followed the steps in this article to create the B2C tenant:

https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-tenant

To summarise, the steps are:

  1. Go to Azure Portal
  2. Create a B2C Tenant
  3. Create User Flows
  4. Register Application (and define the redirect URL as http://localhost:3000/redirect)

Then I followed the logic within this repo, which essentially sets up an Express app with:

  1. express-session
  2. msal-node
  3. Some routes

I am using my own simple template engine, but could deconstruct the logic in this repo for my own implementation.

So this is what I have so far:

  1. When a user visits localhost:3000, a page is returned with a link to 'signin'.

  2. When a user clicks on the signin link, the following route handles it:

app.get('/signin',(req, res)=>{
        //Initiate a Auth Code Flow >> for sign in
        //no scopes passed. openid, profile and offline_access will be used by default.
        getAuthCode(process.env.SIGN_UP_SIGN_IN_POLICY_AUTHORITY, [], APP_STATES.LOGIN, res);
});
  1. The user signs in, and the redirect url is handled by the following route (truncated below to make the logic clearer):
app.get('/redirect',(req, res)=>{
    
    //determine the reason why the request was sent by checking the state
    if (req.query.state === APP_STATES.LOGIN) {
        //prepare the request for authentication        
        tokenRequest.code = req.query.code;
        confidentialClientApplication.acquireTokenByCode(tokenRequest).then((response)=>{
        
        req.session.sessionParams = {user: response.account, idToken: response.idToken};
        console.log("\nAuthToken: \n" + JSON.stringify(response));
        // replacing this because I am using my own template system  
        //res.render('signin',{showSignInButton: false, givenName: response.account.idTokenClaims.given_name});
        res.render('index', { page_html: page_html, givenName: response.account.idTokenClaims.given_name });
        }).catch((error)=>{
            console.log("\nErrorAtLogin: \n" + error);
        });
    }else if (req.query.state === APP_STATES.PASSWORD_RESET) {

...
        
    }else if (req.query.state === APP_STATES.EDIT_PROFILE){
    
...

});

For reference, the format of the redirect URL in the address bar is:

http://localhost:3000/redirect?state=login&client_info=LOTS-OF-STUFF-P1&code=LOTS-OF-STUFF-P2..LOTS-OF-STUFF-P3.LOTS-OF-STUFF-P4.LOTS-OF-STUFF-P5  

So, I am now lost in regards to how to authenticate subsequent calls to my app's API (Express routes).

Should I somehow be storing a token in the browser, that I can use on subsequent calls to my own API/Express routes?

There is another repo here that seems to be demonstrating how to authenticate web app API calls:

https://github.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi

But I am confused why there are two repo's that essentially cover the same topic.

Additionally, the second repo uses the passport and passport-azure-ad packages and, unlike this repo, does not use the passport-azure-ad or express-session packages.

So, should I use the logic from one repo only, or both, and if both - how should I combine their logic?

To summarise, I just want to be able to:

  • Allow users to sign in with Azure B2C
  • Allow users to make subsequent calls to my API (Express routes) only if authenticated by Azure B2C

Seeking clarification of which approach, documentation and repositories to use for a Node.js web app

This issue is for a:

- [ X ] documentation issue or request

I am trying to learn how to implement Azure B2C authentication in a Node.js web app.

This includes the following actions:

  • Sign In / Sign Out / Edit Profile
  • Authenticating calls made to the app's own api (i.e when calling Express routes within the Node application)

I am confused when I look at the Web Apps and APIs section in the Azure Active Directory B2C code samples documentation:

https://learn.microsoft.com/en-us/azure/active-directory-b2c/integrate-with-app-code-samples#web-apps-and-apis

It lists two GitHub repositories for Node.js:

https://github.com/Azure-Samples/active-directory-b2c-msal-node-sign-in-sign-out-webapp

https://github.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi

Question 01:
What is the difference between these two repo's - when should I use one over the other?

Screenshot of relevant section:
node_web_apps_and_apis

Question 02:
I am also finding it difficult to differentiate between the different resources mentioned in the README of this repo.

The links are so similarly named - can anyone please clarify the difference between these resources?

Configure authentication in a sample Node.js web application by using Azure AD B2C
https://learn.microsoft.com/en-us/azure/active-directory-b2c/configure-a-sample-node-web-app

Enable authentication in your own Node web application using Azure AD B2C
https://learn.microsoft.com/en-us/azure/active-directory-b2c/enable-authentication-in-node-web-app

Configure authentication in a sample Node.js web API by using Azure AD B2C
https://learn.microsoft.com/en-us/azure/active-directory-b2c/configure-authentication-in-sample-node-web-app-with-api

Enable authentication in your own Node.js web API by using Azure AD B2C
https://learn.microsoft.com/en-us/azure/active-directory-b2c/enable-authentication-in-node-web-app-with-api

Screenshot of README:
repo_readme

AADB2C90079: Clients must send a client_secret when redeeming a confidential grant.

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

Basically, I use the exact same code (with exceptions of the client secret and the application id).
The confidentialClientConfig is the same (again, with my own clientId, authority, etc...)
The getAuthCode function and the endpoints ("/signin", "/redirect", ...) are the same.
The AD B2C configuration is exactly as prescribed.

Any log messages given by the failure

{"errorCode":"invalid_request","errorMessage":"undefined - [undefined]: AADB2C90079: Clients must send a client_secret when redeeming a confidential grant.\r\nCorrelation ID: bfac0c4b-d0c4-423b-9889-7c846145813d\r\nTimestamp: 2022-03-24 16:16:52Z\r\n - Correlation ID: undefined - Trace ID: undefined","subError":"","name":"ServerError"}

Debug console:
[Thu, 24 Mar 2022 16:24:55 GMT] : [00ee5b5f-c32a-458c-9ee3-816c128a767c] : @azure/[email protected] : Verbose - createAuthority called
[Thu, 24 Mar 2022 16:24:55 GMT] : [00ee5b5f-c32a-458c-9ee3-816c128a767c] : @azure/[email protected] : Verbose - Auth code client created
[Thu, 24 Mar 2022 16:24:55 GMT] : [00ee5b5f-c32a-458c-9ee3-816c128a767c] : @azure/[email protected] : Info - in acquireToken call

Expected/desired behavior

I would expect the acquireTokenByCode function to return the access token succesfully.

OS and Version?

Windows 10.

Versions

@azure/[email protected]

Mention any other details that might be useful


Thanks! We'll be in touch soon.

Issue running in Docker

Issue running project in Docker.
I was able to run the test application locally, however, when running in a Docker container I am getting the below error.

{"errorCode":"endpoints_resolution_error","errorMessage":"Error: could not resolve endpoints. Please check network and try again. Detail: ClientAuthError: openid_config_error: Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints. Attempted to retrieve endpoints from: https://wemotepoc.b2clogin.com/{tennantname}.onmicrosoft.com/b2c_1_{signinpolicy}/v2.0/.well-known/openid-configuration","subError":"","name":"ClientAuthError"}

Minimal steps to reproduce

containerize the project by creating a docker-compose.yml file in the same directory of the project

version: "3"
services:
node:
image: "node:8"
container_name: testapp
user: "node"
network_mode: host
working_dir: /home/node/app
environment:
- NODE_ENV=production
volumes:
- ./:/home/node/app
command: "node index.js"

bring up the project
docker-compose up

Any log messages given by the failure

{"errorCode":"endpoints_resolution_error","errorMessage":"Error: could not resolve endpoints. Please check network and try again. Detail: ClientAuthError: openid_config_error: Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints. Attempted to retrieve endpoints from: https://wemotepoc.b2clogin.com/{tennantname}.onmicrosoft.com/b2c_1_{signinpolicy}/v2.0/.well-known/openid-configuration","subError":"","name":"ClientAuthError"}

Expected/desired behavior

OS and Version?

macOS running docker

Versions

Mention any other details that might be useful


Getting a code challenge error when signin-in

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

I follow the exact documentation provided at the url https://docs.microsoft.com/azure/active-directory-b2c/configure-a-sample-node-web-app, and pressing the sign-in button ends up in error

Any log messages given by the failure

AADB2C99059: The supplied request must present a code_challenge

Expected/desired behavior

Sign-in sucessfully, I don't know how to add a code challenge on this demo app, or clear instructions how to do so.

OS and Version?

Windows 10

Versions

Mention any other details that might be useful


Thanks! We'll be in touch soon.

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.