How to use msal - 10 common examples

To help you get started, we’ve selected a few msal examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Azure-Samples / Serverless-microservices-reference-architecture / web / serverless-microservices-web / src / utils / Authentication.js View on Github external
import { UserAgentApplication, Logger } from 'msal';

const ACCESS_TOKEN = 'rideshare_access_token';
const ID_TOKEN = 'rideshare_id_token';
const EXPIRES_AT = 'rideshare_expires_at';
const USER_DETAILS = 'rideshare_user_details';

let logger = new Logger((level, message, containsPii) => {
  console.log(message);
});

export class Authentication {
  constructor() {
    // The window values below should by set by public/js/settings.js
    this._scopes = window.authScopes;
    this._clientId = window.authClientId;
    this._authority = window.authAuthority;

    var cb = this._tokenCallback.bind(this);
    var opts = {
      validateAuthority: false
    };
    this._userAgentApplication = new UserAgentApplication(
      this._clientId,
github syncweek-react-aad / react-aad / sample / src / authProvider.js View on Github external
{
    auth: {
      authority: process.env.REACT_APP_AUTHORITY,
      clientId: process.env.REACT_APP_AAD_APP_CLIENT_ID,
      postLogoutRedirectUri: window.location.origin,
      redirectUri: window.location.origin,
      validateAuthority: true,

      // After being redirected to the "redirectUri" page, should user
      // be redirected back to the Url where their login originated from?
      navigateToLoginRequestUrl: false,
    },
    // Enable logging of MSAL events for easier troubleshooting.
    // This should be disabled in production builds.
    system: {
      logger: new Logger(
        (logLevel, message, containsPii) => {
          console.log('[MSAL]', message);
        },
        {
          level: LogLevel.Verbose,
          piiLoggingEnabled: false,
        },
      ),
    },
    cache: {
      cacheLocation: 'sessionStorage',
      storeAuthStateInCookie: true,
    },
  },
  {
    scopes: ['openid'],
github syncweek-react-aad / react-aad / sample / src / authProvider.js View on Github external
redirectUri: window.location.origin,
      validateAuthority: true,

      // After being redirected to the "redirectUri" page, should user
      // be redirected back to the Url where their login originated from?
      navigateToLoginRequestUrl: false,
    },
    // Enable logging of MSAL events for easier troubleshooting.
    // This should be disabled in production builds.
    system: {
      logger: new Logger(
        (logLevel, message, containsPii) => {
          console.log('[MSAL]', message);
        },
        {
          level: LogLevel.Verbose,
          piiLoggingEnabled: false,
        },
      ),
    },
    cache: {
      cacheLocation: 'sessionStorage',
      storeAuthStateInCookie: true,
    },
  },
  {
    scopes: ['openid'],
  },
  {
    loginType: LoginType.Popup,
    // When a token is refreshed it will be done by loading a page in an iframe.
    // Rather than reloading the same page, we can point to an empty html file which will prevent
github dotnet / aspnetcore / src / Components / WebAssembly / Authentication.Msal / src / Interop / AuthenticationService.ts View on Github external
constructor(private readonly _settings: AuthorizeServiceConfiguration) {

        // It is important that we capture the callback-url here as msal will remove the auth parameters
        // from the url as soon as it gets initialized.
        const callbackUrl = location.href;
        this._msalApplication = new Msal.UserAgentApplication(this._settings);

        // This promise will only resolve in callback-paths, which is where we check it.
        this._callbackPromise = this.createCallbackResult(callbackUrl);
    }
github Azure / azure-sdk-for-js / sdk / identity / identity / src / credentials / interactiveBrowserCredential.browser.ts View on Github external
}

    this.msalConfig = {
      auth: {
        clientId: options.clientId!, // we just initialized it above
        authority: `${options.authorityHost}/${options.tenantId}`,
        ...(options.redirectUri && { redirectUri: options.redirectUri }),
        ...(options.postLogoutRedirectUri && { redirectUri: options.postLogoutRedirectUri })
      },
      cache: {
        cacheLocation: "localStorage",
        storeAuthStateInCookie: true
      }
    };

    this.msalObject = new msal.UserAgentApplication(this.msalConfig);
  }
github Azure-Samples / Serverless-microservices-reference-architecture / web / serverless-microservices-web / src / utils / Authentication.js View on Github external
constructor() {
    // The window values below should by set by public/js/settings.js
    this._scopes = window.authScopes;
    this._clientId = window.authClientId;
    this._authority = window.authAuthority;

    var cb = this._tokenCallback.bind(this);
    var opts = {
      validateAuthority: false
    };
    this._userAgentApplication = new UserAgentApplication(
      this._clientId,
      this._authority,
      cb,
      opts
    );
  }
github AzureAD / microsoft-authentication-library-for-js / lib / msal-angularjs / lib / msal-angular.js View on Github external
this.init = function (configOptions, httpProvider) {
                if (configOptions) {
                    _config = configOptions;
                    if (!configOptions.optionalParams) {
                        configOptions.optionalParams = {};
                    }

                    configOptions.optionalParams.isAngular = true;

                    if (httpProvider && httpProvider.interceptors) {
                        httpProvider.interceptors.push('ProtectedResourceInterceptor');
                    }

                    // create instance with given config
                    _msal = new Msal.UserAgentApplication(configOptions.clientID, configOptions.authority, configOptions.tokenReceivedCallback, configOptions.optionalParams);
                    if (configOptions.routeProtectionConfig) {
                        _msal.routeProtectionConfig = configOptions.routeProtectionConfig;
                    }
                    else {
                        _msal.routeProtectionConfig = {};
                    }

                    _msal.loginScopes = [_msal.clientId];
                    _constants = Msal.Constants;

                } else {
                    throw new Error('You must set configOptions, when calling init');
                }
                // loginResource is used to set authenticated status
                updateDataFromCache(_msal.loginScopes);
            };
github AzureAD / microsoft-authentication-library-for-js / lib / msal-angular / dist / msal.service.js View on Github external
else {
                    callback = msal._tokenReceivedCallback;
                }
            }
            this.getLogger().verbose("Processing the hash: " + hash);
            this.saveTokenFromHash(requestInfo);
            // Return to callback if it is sent from iframe
            var token = requestInfo.parameters["access_token"] || requestInfo.parameters["id_token"];
            var error = requestInfo.parameters["error"];
            var errorDescription = requestInfo.parameters["error_description"];
            var tokenType = null;
            var msalError = new MSALError(error, errorDescription);
            var authenticationResult = new AuthenticationResult(token);
            if (requestInfo.stateMatch) {
                if (requestInfo.requestType === "RENEW_TOKEN") {
                    tokenType = Constants.accessToken;
                    authenticationResult.tokenType = tokenType;
                    this._renewActive = false;
                    // Call within the same context without full page redirect keeps the callback
                    // id_token or access_token can be renewed
                    if (window.parent === window && !window.parent.callBackMappedToRenewStates[requestInfo.stateResponse]) {
                        if (token) {
                            this.broadcastService.broadcast("msal:acquireTokenSuccess", authenticationResult);
                        }
                        else if (error && errorDescription) {
                            this.broadcastService.broadcast("msal:acquireTokenFailure", msalError);
                        }
                    }
                }
                else if (requestInfo.requestType === "LOGIN") {
                    tokenType = Constants.idToken;
                    authenticationResult.tokenType = tokenType;
github AzureAD / microsoft-authentication-library-for-js / lib / msal-angular / src / msal.service.ts View on Github external
tokenType = Constants.accessToken;
                    authenticationResult.tokenType = tokenType;
                    this._renewActive = false;
                    // Call within the same context without full page redirect keeps the callback
                    // id_token or access_token can be renewed
                    if (window.parent === window && !window.parent.callBackMappedToRenewStates[requestInfo.stateResponse]) {
                        if (token) {
                            this.broadcastService.broadcast("msal:acquireTokenSuccess", authenticationResult);
                        }
                        else if (error && errorDescription) {
                            this.broadcastService.broadcast("msal:acquireTokenFailure",   msalError);
                        }
                    }

                } else if (requestInfo.requestType === "LOGIN") {
                    tokenType = Constants.idToken;
                    authenticationResult.tokenType = tokenType;
                    this.updateDataFromCache(this.loginScopes);
                    if (this._oauthData.userName) {
                        setTimeout(() => {
                            // id_token is added as token for the app
                            this.updateDataFromCache(this.loginScopes);
                            //todo temp commented
                            //  this.userInfo = this._oauthData;
                        }, 1);
                        this.broadcastService.broadcast("msal:loginSuccess", authenticationResult);
                    } else {
                        this.broadcastService.broadcast("msal:loginFailure", msalError);
                    }
                }

                if (callback && typeof callback === "function") {
github AzureAD / microsoft-authentication-library-for-js / lib / msal-angular / dist / msal.service.js View on Github external
tokenType = Constants.accessToken;
                    authenticationResult.tokenType = tokenType;
                    this._renewActive = false;
                    // Call within the same context without full page redirect keeps the callback
                    // id_token or access_token can be renewed
                    if (window.parent === window && !window.parent.callBackMappedToRenewStates[requestInfo.stateResponse]) {
                        if (token) {
                            this.broadcastService.broadcast("msal:acquireTokenSuccess", authenticationResult);
                        }
                        else if (error && errorDescription) {
                            this.broadcastService.broadcast("msal:acquireTokenFailure", msalError);
                        }
                    }
                }
                else if (requestInfo.requestType === "LOGIN") {
                    tokenType = Constants.idToken;
                    authenticationResult.tokenType = tokenType;
                    this.updateDataFromCache(this.loginScopes);
                    if (this._oauthData.userName) {
                        setTimeout(() => {
                            // id_token is added as token for the app
                            this.updateDataFromCache(this.loginScopes);
                            //todo temp commented
                            //  this.userInfo = this._oauthData;
                        }, 1);
                        this.broadcastService.broadcast("msal:loginSuccess", authenticationResult);
                    }
                    else {
                        this.broadcastService.broadcast("msal:loginFailure", msalError);
                    }
                }
                if (callback && typeof callback === "function") {