从Javascript刷新Office365授权令牌

时间:2016-07-26 12:29:42

标签: javascript asp.net azure oauth owin

我目前的某个应用程序存在问题。

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

我已经为该应用程序运行了所有标准身份验证。但是,我相信为了做到这一点,我需要在单击提交按钮时在javascript中获取刷新的令牌,并将此令牌发送到api方法以便提供访问权。

这可能吗?有人知道如何去做吗?

这是一个使用Owin O365安全性和Microsoft Azure AD的MVC ASP.NET应用程序。

我不确定哪些信息或代码片段与此相关,所以如果我能提供任何内容,请询问。

我找到了使用angular获取令牌等的多个示例,但是,这不是SPA,也不使用角度。

非常感谢提前。

更新

我尝试使用以下代码使用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。小学生错误。但是现在,每当我检查上下文的用户属性时,它始终为null。我不知道如何在页面加载时初始化上下文。

2 个答案:

答案 0 :(得分:0)

我在网络上发现了类似的example,您的问题似乎与您要实例化的对象有关。

而不是

new AuthorizationContext(window.config);

尝试

new AuthenticationContext(window.config);

代码运行得很好,表明用户未经过身份验证。

答案 1 :(得分:0)

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

<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>

代码示例来自No 'Access-Control-Allow-Origin' header with Microsoft Online Auth的答案。问题不同,但它们处于相同的情况。

任何进一步的关注,请随时告诉我。

相关问题