How to properly import and use the MSAL (Microsoft Authentication Library for js) into a typescript react single page application?

前端 未结 4 2017
慢半拍i
慢半拍i 2020-12-15 06:02

Problem

I can\'t seem to get the MSAL library to import properly into my typescript code. I\'m using the MSAL for JS library (which is supposed to have typings) in

相关标签:
4条回答
  • 2020-12-15 06:09

    If you install the exports-loader (npm install exports-loader --save-dev) you can avoid the script tag and add the following to your directives:

    var Msal = require("exports-loader?Msal!../../../node_modules/msal/out/msal.js"); 
    
    0 讨论(0)
  • 2020-12-15 06:23

    I had the same issue and couldn't wait for the author to fix it, so forked and modified the original code. Just as a temporary fix you can use my version msalx instead of msal.

    npm install msalx

    You can find the source code and an example usage in react at: https://github.com/malekpour/microsoft-authentication-library-for-js#example

    0 讨论(0)
  • 2020-12-15 06:27

    As you have correctly mentioned - in the msal.d.ts there are no exports - its not a module, and therefore you should not try importing.

    Instead you can use it like this:

    /// <reference path="./node_modules/msal/out/msal.d.ts" />
    
    const userAgentApplication = new Msal.UserAgentApplication("your_client_id", null, (errorDes, token, error, tokenType) =>
        {
    
        });
    

    Note that even in readme they specify only one way of using their library - by including script tag, not by importing module. And further looking into their source code shows they are not using modules as well.

    0 讨论(0)
  • 2020-12-15 06:30

    It looks like the latest version of MSAL.js does have a CommonJS export. You can now just do the following in TypeScript (tested with version 2.3.3 of TypeScript and 0.1.3 of MSAL.js):

    import * as Msal from 'msal';
    

    Now in your .ts (or in my case .tsx file) you can, for instance, setup a click event handler and create a UserAgentApplication object:

    // In you class somewhere
    private userAgentApplication: any = undefined;
    
    // The login button click handler
    handleLoginClick = (event: any): void => {
        if (!this.userAgentApplication) {
            this.userAgentApplication = new Msal.UserAgentApplication(
                'clientID string', 'authority string or empty', this.authCallback, { cacheLocation: 'localStorage'});
        }
        // Other login stuff...
    }
    
    // In React render()
    public render() {
        return (
            <Button
                bsStyle="warning"
                type="button"
                onClick={(e) => this.handleLoginClick(e)}
            >
            Log in
            </Button>
        );
    }
    
    0 讨论(0)
提交回复
热议问题