如何正确导入和使用MSAL(js的Microsoft身份验证库)到打字稿反应单页面应用程序?

nbr*_*wne 18 javascript typescript azure-ad-msal typescript-typings

问题

我似乎无法将MSAL库正确导入到我的打字稿代码中.我正在使用带有react-typescript脚本的create-react-app 搭建的简单打字稿/反应项目中使用MSAL for JS库(应该有打字).我是打字稿的新手,不知道我是否遗漏了一些明显的东西,或者当它与打字稿项目一起使用时,是否存在MSAL包的问题.

细节:

  1. 我使用NPM添加了MSAL包npm install --save msal.
  2. 我尝试使用不同的形式将MSAL导入我的.ts import {Msal} from 'msal';
  3. 这会导致打字稿错误 Could not find a declaration file for module 'msal'. '<path>/node_modules/msal/out/msal.js' implicitly has an 'any' type.
  4. 想到这很奇怪,我查看了node_module/msal/out文件夹并看到了一个'msal.d.ts'文件,这就是我所期望的.
  5. 当我查看msal.d.ts文件的内容时,我没有看到任何导出,我通常希望看到.
  6. 我尝试使用@types安装声明npm install --save-dev @types/msal,但它不存在.
  7. 我也尝试使用它将其导入到我的文件中let Msal = require('Msal');,但是得到一个错误,即Msal.UserAgentApplication不是构造函数.
  8. 我没有太多运气试图使用/// reference指令并向主index.html添加脚本标记.这也不是解决问题的正确方法.

ExampleMsal.ts

import { observable, action, computed } from 'mobx';
import * as Msal from 'msal'; // <-- This line gives the error

class ExampleMsal{
    @observable 
    private _isLoggedIn: boolean;

    constructor() {
        this._isLoggedIn = false;
    }

    @computed 
    get isLoggedIn(): boolean {
        return this._isLoggedIn;
    }

    @action 
    signIn() {

        let userAgentApplication = new Msal.UserAgentApplication('<client-id>', null, 
        function (errorDes: string, token: string, error: string, tokenType: string) {
            // this callback is called after loginRedirect OR acquireTokenRedirect 
            // (not used for loginPopup/aquireTokenPopup)
        }
        );

        userAgentApplication.loginPopup(['user.read']).then(function(token: string) {
            let user = userAgentApplication.getUser();
            if (user) {
                // signin successful
                alert('success');
            } else {
                // signin failure
                alert('fail');
            }
        }, function (error: string) {
            // handle error
            alert('Error' + error);
        });        
        this._isLoggedIn = true;
    }

    @action 
    signOut() {
        this._isLoggedIn = false;
    }
}

export default ExampleMsal;
Run Code Online (Sandbox Code Playgroud)

tsconfig.json

{
  "compilerOptions": {
    "outDir": "build/dist",
    "module": "commonjs",
    "target": "es5",
    "lib": ["es6", "dom"],
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    "rootDir": "src",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true,
    "experimentalDecorators": true
  },
  "exclude": [
    "node_modules",
    "build",
    "scripts",
    "acceptance-tests",
    "webpack",
    "jest",
    "src/setupTests.ts"
  ],
  "types": [
    "typePatches"
  ]
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*nke 12

看起来最新版本的MSAL.js 确实有一个CommonJS导出.您现在可以在TypeScript中执行以下操作(使用TypeScript版本2.3.3和MSAL.js的0.1.3进行测试):

import * as Msal from 'msal';
Run Code Online (Sandbox Code Playgroud)

现在,在您的.ts(或在我的案例.tsx文件中),您可以设置单击事件处理程序并创建UserAgentApplication对象:

// 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>
    );
}
Run Code Online (Sandbox Code Playgroud)


Ami*_*mid 11

正如你正确提到的那样 - 在msal.d.ts中没有导出 - 它不是模块,因此你不应该尝试导入.

相反,你可以像这样使用它:

/// <reference path="./node_modules/msal/out/msal.d.ts" />

const userAgentApplication = new Msal.UserAgentApplication("your_client_id", null, (errorDes, token, error, tokenType) =>
    {

    });
Run Code Online (Sandbox Code Playgroud)

请注意,即使在自述文件中,它们也只指定了一种使用其库的方法 - 包括脚本标记,而不是导入模块.进一步查看他们的源代码显示他们也没有使用模块.

  • MSAL的后续版本似乎现在运行良好,我使用的是版本0.1.3,它很简单:`import*as Msal from'msal';`运行良好. (10认同)

Ali*_*our 10

我有同样的问题,不能等待作者修复它,所以分叉并修改原始代码.就像临时修复一样,您可以使用我的版本msalx而不是msal.

npm install msalx

您可以在以下网址找到源代码和示例用法:https://github.com/malekpour/microsoft-authentication-library-for-js#example

  • 你先生是英雄 (3认同)

小智 6

如果安装exports-loader(npm install exports-loader --save-dev),则可以避免使用脚本标记并将以下内容添加到指令中:

var Msal = require("exports-loader?Msal!../../../node_modules/msal/out/msal.js"); 
Run Code Online (Sandbox Code Playgroud)