从Javascript刷新Office365授权令牌

Refresh Office365 Authorization Token from Javascript

本文关键字:授权 令牌 Office365 刷新 Javascript      更新时间:2023-09-26

我的一个应用程序当前有问题。

问题是,用户在输入任何数据之前可以长时间保持页面打开,因此有时,当他们输入数据并点击提交按钮时,他们会被重定向到o365进行身份验证,从而丢失输入的数据。

我有适用于该应用程序的所有标准身份验证。然而,我相信为了做到这一点,我需要在单击提交按钮时获得javascript中的刷新令牌,并将该令牌发送到api方法以授予访问权限。

这可能吗?有人知道怎么做吗?

它是一个MVC ASP。NET应用程序使用Owin O365安全与Microsoft Azure AD.

我不确定什么信息或代码片段会在这里相关,所以如果有什么我可以提供的,请询问。

我发现了多个使用angular获取代币等的例子,然而,这不是SPA,也不使用angular。

非常感谢。

更新

我尝试使用以下代码使用ADAL JS检索令牌,但它似乎无法识别AuthorizationContext(config)调用:

    <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/adal.min.js"></script>
    $('#btnSubmit').on('click', function (e) {
        e.preventDefault();
        CheckUserAuthorised();
    });
    function CheckUserAuthorised() {
        window.config = {
            instance: 'https://login.microsoftonline.com/',
            tenant: '##################',
            clientId: '###################',
            postLogoutRedirectUri: window.location.origin,
            cacheLocation: 'localStorage'
        };
        var authContext = new AuthorizationContext(config); //THIS LINE FAILS
        var user = authContext.getCachedUser();
        if (!user) {
            alert("User Not Authorised");
            authContext.login();
        }
        else {
            alert('User Authorized');
        }
    }

这在控制台中给出以下错误:

'AuthorizationContext' is undefined

更新

我还没有通过未定义的错误。这是因为我调用的是AuthorizationContext而不是AuthenticationContext。男生失误。然而,现在,每当我检查上下文的user属性时,它总是为null。我不知道如何解决这个问题,因为上下文是在页面加载时初始化的。

您的代码中缺少一个步骤,这里有一个简单的代码示例,希望它能帮助您:

<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.10/js/adal.min.js"></script>
<body>
<a href="#" onclick="login();">login</a>
<a href="#" onclick="getToken()">access token</a>
<a href="#" onclick="getUser()">get user</a>
</body>
<script type="text/javascript">
    var configOptions = {
        tenant: "<tenant_id>", // Optional by default, it sends common
        clientId: "<client_id>",
        postLogoutRedirectUri: window.location.origin,
    }
    window.authContext = new AuthenticationContext(configOptions);
    var isCallback = authContext.isCallback(window.location.hash);
    authContext.handleWindowCallback();
    function getToken(){
        authContext.acquireToken("https://graph.microsoft.com",function(error, token){
            console.log(error);
            console.log(token);
        })
    }
    function login(){
        authContext.login();
    }
    function getUser(){
        var user = authContext.getCachedUser();
        console.log(user);
    }
</script>

代码示例来自"否"的答案;访问控制允许来源';带有Microsoft Online Auth的标头。问题是不同的,但它们处于相同的场景中。

如有任何进一步的问题,请随时通知我。

我在网上发现了一个类似的例子,您的问题似乎与您正在实例化的对象有关。

代替

new AuthorizationContext(window.config);

尝试

new AuthenticationContext(window.config);

代码运行良好,显示用户未通过身份验证。