12

I am working with react and I have to give my user login through Azure B2C, So I am trying to do that but I am not able to find out how to do that and what is the.

What I have tried

  1. I got this example from Microsoft site which is done using plain JavaScript (vanilla), I have no idea how I will implement this in my react code.

So I tried to move with some react library, I google around and found This library

I have followed the same code they have written, but when I hit login button it takes me to login page of azure, So in my app.js I am doing console.log(authentication.getAccessToken()); after login it throws null, I don't know why

My code

authentication.initialize({
        // optional, will default to this
        instance: 'https://login.microsoftonline.com/tfp',
        // My B2C tenant
        tenant: 'mytenant.onmicrosoft.com',
        // the policy to use to sign in, can also be a sign up or sign in policy
        signInPolicy: 'B2c_signupsignin',
        // the the B2C application you want to authenticate with (that's just a random GUID - get yours from the portal)
        clientId: 'fdfsds5-5222-ss522-a659-ada22',
        // where MSAL will store state - localStorage or sessionStorage
        cacheLocation: 'sessionStorage',
        // the scopes you want included in the access token
        scopes: ['https://mytenant.onmicrosoft.com/api/test.read'],
        // optional, the redirect URI - if not specified MSAL will pick up the location from window.href
        redirectUri: 'http://localhost:3000',
    });

And then on click of login I am doing this

const Log_in = () => {
        authentication.run(() => {});
        
    };

in my app.js I am doing like below

import authentication from 'react-azure-b2c';

function App() {
    console.log(authentication.getAccessToken());   
}

So initially it is showing null which is fine, but after login also it is throwing error only.

So I was not able to resolve this, that's why I move to the other library which is almost similar to this

  1. This one

So here when I click on login button I am getting error as

Error

The example I got from Microsoft with valina Javascript, I think that is the perfect way to do but How can I imliment that through react I don't know

This the code with vanilla js

I have been stuch here from long time i don't know what to do now, not able to find good example on google to implement it with react

PS: I am using react hooks functional component to write my code, please guide me through this

I just want to implement this using react in a proper way, I know out tehre so many peoples who are already using this, so I just want to see a good example.

Edit / update

I tried doing like this

    b2cauth.initialize({
    instance: 'https://mylogin.b2clogin.com/tfp',
    tenant: 'mylogin.b2clogin.com',
    signInPolicy: 'B2C_1_SigninSignupUsername',
    clientId: 'fc3081ec-504a-4be3-a659-951a9408e248',
    cacheLocation: 'sessionStorage',
    scopes: ['https://mylogin.b2clogin.com/api/demo.read'],
    redirectUri: 'http://localhost:3000',
});
b2cauth.run(() => {
    ReactDOM.render(<App />, document.getElementById('root'));
    serviceWorker.unregister();
});

I check Microsoft link pasted as answer, and changed instance: instance: 'https://mylogin.b2clogin.com/tfp',

to

instance:'https://my-tanent-name.b2clogin.com/tenent-id/oauth2/authresp',

but I am getting error as bad request

and I check network tab and I check the url it is hitting and it is hitting below

https://login.microsoftonline.com/common/discovery/instance?api-version=1.0&authorization_endpoint=https://my-tenatnt-name.b2clogin.com/tenant-id/oauth2/authrespmy-tenant-name.b2clogin.com/b2c_1_signinsignupusername/oauth2/v2.0/authorize

I tried removing https from instance and hit it like this

//mytenant.b2clogin.com/tenant-id/oauth2/authresp

it throws error as Uncaught AuthorityUriInsecure

Error

I think it is going to wrong place

manish thakur
  • 760
  • 9
  • 35
  • 76
  • My answer was deleted by the moderator, so commenting, you don't need to create any button, so when the user hit your website URL, it will be redirected to Microsoft b2c page, and their users will enter their details. and after successful sign in it will be redirected back to your app, this redirection configuration will happen when you register your app in portal. – Manish Aug 26 '20 at 03:15
  • but this CORS issue I think you can resolve by adding http://localhost:3001 in portal. – Manish Aug 26 '20 at 03:18
  • check this link https://learn.microsoft.com/en-us/samples/azure-samples/active-directory-b2c-javascript-msal-singlepageapp/active-directory-b2c-javascript-msal-singlepageapp/ – Manish Aug 26 '20 at 03:54
  • try this, https://medium.com/@fiqriismail/how-to-secure-your-reactjs-frontend-with-azure-ad-b2c-8fd165f602e8, git hub repo for this https://github.com/fiqriismail/tutorialcode – Manish Aug 26 '20 at 04:03
  • @Manish yes I have already tried this, not working, the above library is not good as it was active way back, no body is there to help if issue – manish thakur Aug 26 '20 at 04:20
  • Please check my recent answer to a similar question. Most likely your URL is wrong and needs to be based on b2clogin.com. https://stackoverflow.com/questions/62975275/cors-no-access-control-allow-origin-when-trying-to-call-b2c-login/62985723#62985723 – Alex AIT Aug 28 '20 at 11:02
  • @AlexAIT I tried that but still stuck, could you please help me out ? – manish thakur Sep 01 '20 at 07:21

1 Answers1

6

Your coordinates for the b2c instance are not correct (see note). You can find more details: https://learn.microsoft.com/en-us/azure/active-directory-b2c/b2clogin

If you like you can use this sample, which shows how to use B2C policy from React application using oidc-client.js library. By default it is configured to use PKCE but you can configure it to use implicit flow instead if needed (not recommended).

Complete instructions provided in the git repo but here is the high level overview.

  • You need to first create application in b2c along with the policy (not shown). You should add two redirect uris -- https://localhost:3000 and https://localhost:3000/callback.html

enter image description here

  • You can also add permissions in case you like to receive an access_token in addition to the id_token.

enter image description here

  • Your manifest should look similar to:
{
    "id": "443ca8db-7bd1-4ebd-9671-ce94e006a18a",
    "acceptMappedClaims": null,
    "accessTokenAcceptedVersion": 2,
    "addIns": [],
    "allowPublicClient": null,
    "appId": "50d2c416-a5ad-4c5c-b36a-0d1ac5b48167",
    "appRoles": [],
    "oauth2AllowUrlPathMatching": false,
    "createdDateTime": "2020-09-02T00:11:35Z",
    "groupMembershipClaims": null,
    "identifierUris": [],
    "informationalUrls": {
        "termsOfService": null,
        "support": null,
        "privacy": null,
        "marketing": null
    },
    "keyCredentials": [],
    "knownClientApplications": [],
    "logoUrl": null,
    "logoutUrl": null,
    "name": "OIDC-Test-APP",
    "oauth2AllowIdTokenImplicitFlow": false,
    "oauth2AllowImplicitFlow": false,
    "oauth2Permissions": [],
    "oauth2RequirePostResponse": false,
    "optionalClaims": null,
    "orgRestrictions": [],
    "parentalControlSettings": {
        "countriesBlockedForMinors": [],
        "legalAgeGroupRule": "Allow"
    },
    "passwordCredentials": [],
    "preAuthorizedApplications": [],
    "publisherDomain": "contoso.onmicrosoft.com",
    "replyUrlsWithType": [
        {
            "url": "http://localhost:3000/signin-callback.html",
            "type": "Spa"
        },
        {
            "url": "http://localhost:3000/",
            "type": "Spa"
        }
    ],
    "requiredResourceAccess": [
        {
            "resourceAppId": "00000003-0000-0000-c000-000000000000",
            "resourceAccess": [
                {
                    "id": "37f7f235-527c-4136-accd-4a02d197296e",
                    "type": "Scope"
                },
                {
                    "id": "7427e0e9-2fba-42fe-b0c0-848c9e6a8182",
                    "type": "Scope"
                }
            ]
        },
        {
            "resourceAppId": "18ac2afe-2c1f-4ea8-8d63-14dd50ee4f85",
            "resourceAccess": [
                {
                    "id": "d5515006-5646-4398-ad59-fffc357f3423",
                    "type": "Scope"
                }
            ]
        }
    ],
    "samlMetadataUrl": null,
    "signInUrl": null,
    "signInAudience": "AzureADandPersonalMicrosoftAccount",
    "tags": [],
    "tokenEncryptionKeyId": null
}
  • Clone the repo and update the settings present inside AuthSettings.ts to match your tenant. You must update client_id and contoso which is the tenant name.
const settings = {

      // This is  the metadata endpoint
      authority: 'https://contoso.b2clogin.com/contoso.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=B2C_1A_signup_signin',
      
      // Turn off calls to user info since CORS will block it
      loadUserInfo: false, 

      // The URL where the Web UI receives the login result
      redirect_uri: 'http://localhost:3000/signin-callback.html',

      // The no longer recommended implicit flow must be used if CORS is disabled
      // If you want to use impicit flow use id_token instead of code for the return type.
      response_type: 'code',

      // Other OAuth settings
      client_id: '18ac2afe-2c1f-4ea8-8d63-14dd50ee4f85',
      
      // openid is required, remove https://contoso.onmicrosoft.com/test/Read if access_token is not required.
      scope: 'openid https://contoso.onmicrosoft.com/test/Read', 
       // Supply these details explicitly. Directly copied from azure ad b2c policy metadata endpoint.
       metadata: {
        issuer: 'https://contoso.b2clogin.com/9859cd0c-9d99-4683-abcc-87462f67a0bc/v2.0/',
        authorization_endpoint: 'https://contoso.b2clogin.com/contoso.onmicrosoft.com/oauth2/v2.0/authorize?p=b2c_1a_signup_signin',
        token_endpoint: 'https://contoso.b2clogin.com/contoso.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1a_signup_signin',
        jwks_uri : 'https://contoso.b2clogin.com/contoso.onmicrosoft.com/discovery/v2.0/keys?p=b2c_1a_signup_signin',
        end_session_endpoint: "https://contoso.b2clogin.com/contoso.onmicrosoft.com/oauth2/v2.0/logout?p=b2c_1a_signup_signin&post_logout_redirect_uri=http%3A%2F%2Flocalhost:3000%2F"

    },

  } as UserManagerSettings;
  • Build and run the app using yarn or npm

  • Application will launch by default on http://localhost:3000

enter image description here

  • Click Login and it should take you to the b2c policy to complete the journey.

enter image description here

  • After you complete the journey in the b2c policy you will be redirected back to the application.

enter image description here

Razi
  • 1,102
  • 1
  • 8
  • 21
  • that tfp is not required ? – manish thakur Aug 27 '20 at 03:46
  • Manish, I have added a working config file to my answer for you to compare your entries with. Currently, I cannot tell from your entries which OIDC flow you are using but if you can share that it would be helpful. I am using OIDC implicit flow as reflected from my config files. – Razi Aug 28 '20 at 17:48
  • I can share, but the above `stsSettings` you are defining do i also need to define that, if yes where, I am using https://www.npmjs.com/package/react-azure-adb2c this library – manish thakur Aug 30 '20 at 07:36
  • Manish -- I actually have a working sample using oidc-client.js with react and b2c. If you don't mind using that library, I can share it as part of my answer so you can basically use it. – Razi Aug 30 '20 at 21:23
  • I have added the details along with the link to a working sample. – Razi Sep 02 '20 at 04:03