Coder Social home page Coder Social logo

react-azure-adb2c's Introduction

README

Azure AD B2C is a cost effective identity provider covering social and enterprise logins but it can be awekward to integrate with - its documentation is currently not great and using it involves rooting around across multiple samples, the ADAL library, and the MSAL library.

That being the case I've focused this package on B2C although with minor changes it could be used more broadly. MSAL itself, which this library wraps, is rather generic but B2C has some specific requirements and I think half of the problem with the documentation is that you end up drifting across B2C and straight AD. I wanted to make things simpler for B2C.

Hopefully this will help people writing React apps. It makes use of MSAL underneath and the core of it (other than protecting routes) will probably work with other frameworks too but I use React at the moment. As it's an SPA my assumption in the library and documentation below is that you ultimately want to get an access token that you can use to call remote APIs. See this Azure AD B2C post here for details on how to set this up on the B2C side.

PRs welcome!

Installation

If you are using npm:

npm install react-azure-adb2c --save

Or if you are using yarn:

yarn add react-azure-adb2c

Initializing the Library

You'll first need to load the module and pass some configuration to the library. Normally this would go in your index.js file:

import authentication from 'react-azure-adb2c';
authentication.initialize({
    // optional, will default to this
    instance: 'https://login.microsoftonline.com/tfp/', 
    // your B2C tenant
    tenant: 'myb2ctenant.onmicrosoft.com',
    // the policy to use to sign in, can also be a sign up or sign in policy
    signInPolicy: 'mysigninpolicy',
    // the policy to use for password reset
    resetPolicy: 'mypasswordresetpolicy',
    // the the B2C application you want to authenticate with (that's just a random GUID - get yours from the portal)
    applicationId: '75ee2b43-ad2c-4366-9b8f-84b7d19d776e',
    // where MSAL will store state - localStorage or sessionStorage
    cacheLocation: 'sessionStorage',
    // the scopes you want included in the access token
    scopes: ['https://myb2ctenant.onmicrosoft.com/management/admin'],
    // optional, the redirect URI - if not specified MSAL will pick up the location from window.href
    redirectUri: 'http://localhost:3000',
    // optional, the URI to redirect to after logout
    postLogoutRedirectUri: 'http://myapp.com'
});

Authenticating When The App Starts

If you want to set things up so that a user is authenticated as soon as they hit your app (for example if you've got a link to an app from a landing page) then, in index.js, wrap the lines of code that launch the React app with the authentication.run function:

authentication.run(() => {
  ReactDOM.render(<App />, document.getElementById('root'));
  registerServiceWorker();  
});

Triggering Authentication Based on Components Mounting (and routing)

If you want to set things up so that a user is authenticated as they visit a part of the application that requires authentication then the appropriate components can be wrapped inside higher order components that will handle the authentication process. This is done using the authentication.required function, normally in conjunction with a router. The example below shows this using the popular react-router:

import React, { Component } from 'react';
import authentication from 'react-azure-adb2c'
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import HomePage from './Homepage'
import MembersArea from './MembersArea'

class App extends Component {
  render() {
    return (
      <Router basename={process.env.PUBLIC_URL}>
        <Switch>
          <Route exact path="/" component={HomePage} />
          <Route exact path="/membersArea" component={authentication.required(MembersArea)}>
        </Switch>
      </Router>
    );
  }
}

Getting the Access Token

Simply call the method getAccessToken:

import authentication from 'react-azure-adb2c'

// ...

const token = authentication.getAccessToken();

Signing Out

To sign out:

import authentication from 'react-azure-adb2c'

// ...

authentication.signOut();

Thanks

To build this I made use of the B2C site, the MSAL library docs, the react-adal source and this React MSAL sample. Thanks!

react-azure-adb2c's People

Contributors

dnewell1986 avatar jamesrandall 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-azure-adb2c's Issues

SSO Support

How to implement SSO(Single Sign On) with this library.

Has anyone managed to get this working with IE11?

Hello,

Love this library but I am struggling to make it work on IE11, it works fine in Chrome and Edge. I included React polyfills and updated package.json browser list.

Error:
JavaScript critical error at line 1199, column 65 in https://localhost:5001/static/js/main.chunk.js\n\nSCRIPT1002: Syntax error

And that line looks like this in main.chunk.js

react_azure_adb2c__WEBPACK_IMPORTED_MODULE_8___default.a.run(() => {
react_dom__WEBPACK_IMPORTED_MODULE_4___default.a.render(react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_5__["BrowserRouter"], {
basename: baseUrl,
__source: {
fileName: _jsxFileName,
lineNumber: 41
},
_self: undefined
}, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(App__WEBPACK_IMPORTED_MODULE_6
["default"], {
__source: {
fileName: _jsxFileName,
lineNumber: 42
},
_self: undefined
})), rootElement);
Object(registerServiceWorker__WEBPACK_IMPORTED_MODULE_7
["default"])();
}); //ReactDOM.render(
//
//
// ,
// rootElement);
//registerServiceWorker();

Repeat login redirects in incognito browser

I have a react-router-dom Route set up to require authentication as per the package's documentation:

    import React from 'react';
    import { Route, BrowserRouter as Router, Switch } from 'react-router-dom';
    import authentication from 'react-azure-adb2c';
    import Home from '../Home';
    import Products from '../Products';
    
    authentication.initialize({
      instance: 'https://login.microsoftonline.com/tfp/',
      tenant: process.env.REACT_APP_AAD_DOMAIN,
      signInPolicy: process.env.REACT_APP_AAD_POLICY_ID,
      applicationId: process.env.REACT_APP_AAD_CLIENT_ID,
      scopes: [process.env.REACT_APP_AAD_SCOPES],
      cacheLocation: 'sessionStorage',
      redirectUri: process.env.REACT_APP_URL,
      postLogoutRedirectUri: process.env.REACT_APP_URL,
    });
    
    function App() {
      return (
        <Router>
          <Switch>
            <Route exact path="/" component={Home} />
            <Route
              exact
              path="/products"
              component={authentication.required(Products)} // require login to access /products
            />
          </Switch>
        </Router>
      );
    }
    
    export default App;

This works as expected in a normal browser window, the user clicks a link to /products, gets redirected to an Azure AD B2C login page, gets pushed back to the app on login, and then redirected to /products.

But in an incognito browser, when the user gets pushed back to the app after login, they get redirected back to the Azure login page a second time. If they log in again with the second prompt, then they get pushed to /products, as they should have the first time.

Wondering if this has been an issue for anyone else using this package?

authentication.run not firing when deployed to Azure

I have deployed my app to Azure and for some reason the authentication.run is not firing. I can console.log the config settings, and everything looks OK. Just gives me a blank page.

Anyone else run into this issue?

componentWillMount has been renamed

Hi!

Started getting this warning. Might be good to update the code.

Warning: componentWillMount has been renamed, and is not recommended for use. See https://fb.me/react-async-component-lifecycle-hooks for details.

  • Move code with side effects to componentDidMount, and set initial state in the constructor.
  • Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run npx react-codemod rename-unsafe-lifecycles in your project source folder.

Please update the following components: _class

The issue is in this line: component={auth.getAuth().required(Login)}

Cheers!

No typings exist

The current state of the library makes it difficult to consume in Typescript based projects.

To address this I believe that supplying a basic set of typing for the library

`msal` dependency out of date.

Looks like you're fixed to "msal": "^0.1.5" and I think they're up to v0.2.3 now. Happy to submit a PR, but want to make sure you're up for it ?

How to configure if we have multiple SignIn Policy?

We see that initialize is called in index.js which forms UserAgentApplication using signInPolicy.

We have different signinPolicy per user domain, so if user is from xyz organization with email [email protected] then we want them to go through b2c_1_xyzsigninpolicy and if user is from abc organization with email [email protected] then we want them to go through b2c_1_abcsigninpolicy.

We have not used one policy as we do not want to show "SignIn to ABC" and "SignIn to XYZ" buttons on B2C Custom login UI.

Instead, what we want to do is have a Login UI in our App which will have only Email TextBox. When user will enter [email protected] then based on email domain, we want them to redirect to xyzsigninpolicy login screen.

How can we dynamically change the Authority in this codebase? When redirectUrl will be sent back from this policy, will the code in index.js execute again?

Also, we are using scheme instead of wrapping show App in authentication HOC as we want to allow /login /logout /404 /403 and /home page to be accessed without authentication.

Please advise if this is possible using this library. Thanks.

Toekn is not storing in cache and it is redirecting to login page

I got Uncaught (in promise) UnsupportedAuthorityValidation error when i use library.
To avoid this error i set validateAuthority to false in node modules.
After setting validateAuthority to false i am able to see the login page and i tried to click on sign in then it will redirect to application and after 2 to 3 secs it will redirects to login page.
Token is not storing in cache

Issue with Instance discovery metadata

MSAL4J performs instance discovery before any acquireToken() or GetAccount() API call as per this url

When I override the default configuration setting to use our own domain as b2c_instance the above instance discovery trying to hit the following url which is returning 404. This doesn't allow me to get to the login page.

https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=https://<my instance url>/<tenent-id>/<policy_name>/oauth2/v2.0/authorize

Has anyone faced this issue, my company uses its own domain instead of login.microsoftonline.com for all the oauth endpoints.

I am stuck with this issue, any help is appreciated here.

Thanks
Venkat

Merge with react-aad-msal?

Hey! I'm currently one of the owners of the react-aad-msal library, which is also a React wrapper around MSAL. I had a lot of the same frustrations which led me to try to write my own wrapper until I saw a few people already doing something similar.

Looks like our projects mostly do the same thing, but while we're farther along with the MSAL integration, we're missing a few of the Azure B2C features you have. Would you be interested in helping to migrate the features over and combine libraries? I can do most of the work and take over maintenance if you could help identify the feature gaps...

The Identity team at Microsoft has it in their roadmap to build an official React wrapper for MSAL at an unspecified time next year, but I'm hoping if the community can fill the gap they'll accept our solution as a sanctioned library well before then.

Uncaught (in promise) UnsupportedAuthorityValidation

Hi

I have used the below-given sample credentials its working fine and redirected to the Microsoft login screen.

b2cauth.initialize({
instance: 'https://login.microsoftonline.com/tfp/',
tenant: 'peachitad.onmicrosoft.com',
signInPolicy: 'B2C_1_react_signup',
applicationId: '702f55a3-72fd-4da1-a22b-1dc82e70a049',
cacheLocation: 'sessionStorage',
scopes: ['https://peachitad.onmicrosoft.com/api/user_impersonation'],
redirectUri: 'http://localhost:3000',
postLogoutRedirectUri: window.location.origin,
});

But I have changed into my own Azure AD B2C credential am getting the Uncaught (in promise) UnsupportedAuthorityValidation error.
Kindly give me any suggestions.

Optional authentication

I have pages, where I do not want to enforce authentication, but I would take advantage of it, if it is here.
Right now authentication.getAccessToken() returns null for such pages.

Is there workaround?
Thank you for the great framework!

Sign out not working

When I call authentication.signOut(); it fails. When I check Network Request URL I see double // in url

react-azure-adb2c

and if I remove one / and go to url it works find

Setup with create-react-app

Hi

I'm trying to setup this library with a newly created React project setup using create-react-app my-app. After installing react-azure-adb2c and setting up the configuration with my Azure ADB2C tenant info, using the authentication.run((), nothing seems to happen when the application is launched.

I can see in the browser Network activity there is an openid-configuration with status of 200. Is there an added configuration required to call and see some UI or have i missed something out - how do i get to login page to get access token?

Using version 0.2.0

Thanks

Needs validateAuthority flag to work with b2clogin.com redirects

Great package, thanks for putting this together! I even thought this was the official MS package since it was featured on TechNet: https://social.technet.microsoft.com/wiki/contents/articles/52573.azure-ad-b2c-secure-your-reactjs-frontend.aspx

One small issue, the recommended login redirect to <your-domain>.b2clogin.com requires the flag validateAuthority to be set to false when calling Msal.UserAgentApplication(): https://docs.microsoft.com/bs-latn-ba/azure/active-directory-b2c/b2clogin

I have added this change to the initialize function on our fork and verified that it works:
information-experience-sweden-ab@fdc6855

user/login name

It would be helpful if we could get the user/login name from the authentication object. It doesn't look like there is anyway of getting it out at the moment

localhost:3000/null on IE

after login page of azure my app redirect to localhost:3000/null in internet explorer but working fine on other browsers. please help out

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.