c# - “authority”应为 Uri 格式参数名称 : authority

标签 c# asp.net-mvc azure azure-active-directory adal

我根据这个例子开发了我的mvc应用程序: https://github.com/AzureADSamples/WebApp-WebAPI-OpenIDConnect-DotNet

身份验证与 Azure AAD 完美配合,我可以看到用户已登录:

http://screencast.com/t/v7G6OgXC

但是在下面的 Controller 中我想打印出一些APP属性,并且收到上面的错误

'authority' should be in Uri format Parameter name: authority Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: 'authority' should be in Uri format Parameter name: authority

我在 Controller 中的代码是这样的:

using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.IdentityModel.Protocols;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace PruebasAD.Controllers
{
    public class ActiveDirectoryController : Controller
    {
        private static string azureAdGraphApiEndPoint = ConfigurationManager.AppSettings["ida:AzureAdGraphApiEndPoint"];
        private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        private static string appKey = ConfigurationManager.AppSettings["ida:AppKey"];

        // GET: ActiveDirectory
        public ActionResult GetAzureAadApp()
        {
            // Instantiate an instance of ActiveDirectoryClient.
            Uri serviceRoot = new Uri(azureAdGraphApiEndPoint);
            ActiveDirectoryClient adClient = new ActiveDirectoryClient(
                serviceRoot,
                async () => await GetAppTokenAsync());

            // Create the extension property
            string extPropertyName = "VehInfo";
            ExtensionProperty extensionProperty = new ExtensionProperty()
            {
                Name = extPropertyName,
                DataType = "String",
                TargetObjects = { "User" }
            };

            Application app =(Application)adClient.Applications.Where(
                    a => a.AppId == clientId).ExecuteSingleAsync().Result;

            if (app == null)
            {
                throw new ApplicationException("Unable to get a reference to application in Azure AD.");
            }

            return View(app);
        }

        private static async Task<string> GetAppTokenAsync()
        {
            string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
            string appKey = ConfigurationManager.AppSettings["ida:AppKey"];
            string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
            string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
            string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
            string azureAdGraphApiEndPoint = ConfigurationManager.AppSettings["ida:AzureAdGraphApiEndPoint"];
            // This is the resource ID of the AAD Graph API.  We'll need this to request a token to call the Graph API.
            string graphResourceId = ConfigurationManager.AppSettings["ida:GraphResourceId"];

            string Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

            // Instantiate an AuthenticationContext for my directory (see authString above).
            AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance, false);

            // Create a ClientCredential that will be used for authentication.
            // This is where the Client ID and Key/Secret from the Azure Management Portal is used.
            ClientCredential clientCred = new ClientCredential(clientId, appKey);

            // Acquire an access token from Azure AD to access the Azure AD Graph (the resource)
            // using the Client ID and Key/Secret as credentials.
            AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(azureAdGraphApiEndPoint, clientCred);

            // Return the access token.
            return authenticationResult.AccessToken;
        }
    }


    public class CompanyInfo
    {
        public int Nit;
        public string Nombre;
    }
}

为了安全起见,web.config 进行了一些更改

<add key="ida:GraphResourceId" value="https://graph.windows.net" />
    <add key="ida:GraphUserUrl" value="https://graph.windows.net/{0}/me?api-version=2013-11-08" />
    <add key="ida:ClientId" value="xx-b1aa-42ab-9693-6c22d01ca338" />
    <add key="ida:AppKey" value="xx/6Vsq0CuhQyYVcR5Vggw=" />
    <add key="ida:Tenant" value="xx.onmicrosoft.com" />
    <add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}" />
    <add key="ida:PostLogoutRedirectUri" value="https://localhost:44300/" />
    <add key="ida:AzureAdGraphApiEndPoint" value="https://graph.windows.net/xx-d5f0-453b-8f60-2be9b41b2ea0" />

最佳答案

您需要将Authority传递给AuthenticationContext()而不是aadInstance:

// Instantiate an AuthenticationContext for my directory (see authString above).
AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);

关于c# - “authority”应为 Uri 格式参数名称 : authority,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30404915/

相关文章:

c# - 排列具有偏好的不同 lambda 比较

asp.net-mvc - 将选择列表绑定(bind)到 mvc 3 中的模型

azure - 如何安排 ADF Pipeline 每天运行多个小时?

azure - 从azure中的服务总线队列获取数据时出错

asp.net-mvc - MVC 返回 Json 结果

azure - 尝试在 ubuntu 上运行 "az login"时出现 Python 异常和权限被拒绝异常

c# - visual studio express 2012 中的 PowerPacks 命名空间错误

c# - 更改 Windows 8 锁屏背景?

c# - 在 C# Visual Studio 中工作时 mysql 存储过程的问题

c# - ASP.NET MVC : Get lowercase links (instead of Camel Case)