当前位置:  开发笔记 > 编程语言 > 正文

AuthenticationContext.AcquireTokenAsync是C#的新手

如何解决《AuthenticationContext.AcquireTokenAsync是C#的新手》经验,为你挑选了1个好方法。



1> BrewMate..:

所以不确定你是否在Android,iOS或Xamarin.Forms上这样做.下面是我将如何使用ADAL和Azure进行身份验证(代码正在我的工作中):

在Android上:

public async Task Authenticate(Activity context, string authority, string resource, string clientId, string returnUri)
{
    var authContext = new AuthenticationContext(authority);
    if (authContext.TokenCache.ReadItems().Any())
        authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);

    var uri = new Uri(returnUri);
    var platformParams = new PlatformParameters(context);
    try
    {
        var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);
        return authResult;
    }
    catch (AdalException e)
    {
        return null;
    }
}

在iOS上:

public async Task Authenticate(UIViewController controller, string authority, string resource, string clientId, string returnUri)
    {
        var authContext = new AuthenticationContext(authority);
        if (authContext.TokenCache.ReadItems().Any())
            authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);

        var controller = UIApplication.SharedApplication.KeyWindow.RootViewController;
        var uri = new Uri(returnUri);
        var platformParams = new PlatformParameters(controller);

        try
        {
            var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);
            return authResult;
        }
        catch (AdalException e)
        {
            return null;
        }
    }

在UWP上:

public async Task Authenticate(string authority, string resource, string clientId, string returnUri)
{
    var authContext = new AuthenticationContext(authority);
    if (authContext.TokenCache.ReadItems().Any())
        authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);

    var uri = new Uri(returnUri);
    var platformParams = new PlatformParameters(PromptBehavior.Auto);
    try
    {
        var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);
        return authResult;
    }
    catch (AdalException e)
    {
        return null;
    }
}

我传入上述方法的变量:

string authority = "https://login.windows.net/common";
string ResourceID = "Backend ClientId";//Backend (web app)
string clientId = "Native App ClientId";//native app
string returnUri = "https://{My Azure Site}.azurewebsites.net/.auth/login/done";

如果你想在Xamarin.Forms中这样做,下面是我的GitHub解决方案的链接,我已经通过这些方法公开了这些方法DependencyService.

PCL实施

iOS实现

Android实施

我希望这有帮助!如果您的响应中出现任何错误,请检查以确保您在Azure中正确设置了权限.我是这样做的.另一个很好的资源是Adrian Hall的Xamarin/Azure书

编辑:添加了UWP的东西

推荐阅读
黄晓敏3023
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有