简体   繁体   中英

Azure AD authentication in ASP.NET MVC 5

My problem is that I cannot make Azure AD auth work when creating the App registrations (in Azure portal) manually.

It all works fine if I create a new website using the MVC 5 template and let Visual Studio (2017) create a new App registration.

在此处输入图片说明

When I try to use the one I created it doesn't work and I'm getting this exception:

在此处输入图片说明

stack trace:

at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.d__8.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.d__3.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.d__24.MoveNext()

Startup code I use in both:

private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
    private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
    private static string tenant = ConfigurationManager.AppSettings["ida:TenantId"];
    private string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

    public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri = postLogoutRedirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                },
                TokenValidationParameters = new TokenValidationParameters
                {

                    RequireSignedTokens = false,

                },
            });
    }

The only difference I was able to find is that the automatically created App registration has one key and its manifest contains "passwordCredentials".

在此处输入图片说明

Manually created app doesn't have it. I use the IIS Express for both websites. Both Application ID and Tenant ID are correct as well as HTTPS port. All OWIN packages have the same version (in both apps). I think IIS Express somehow uses that key from above but I couldn't find where or how it's applied as my startup code is exactly the same. Any help appreciated

PS: I also tried to host it on local IIS with the same result...

I wasn't able to make it work with tenant ID (still have no idea why) but when I use tenant name it finally works with manually created App registration.

public partial class Startup
{
    private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
    private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
    private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
    private string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

    /// <summary>
    /// Configures the authentication.
    /// </summary>
    /// <param name="app">The application.</param>
    public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri = postLogoutRedirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });
    }
}

I've been going through the same problem so am sharing my solution :

you have first to create a new secret key in your application on azure. Then add this key to your web.config

<add key="ida:ClientSecret" value="A***]E7uR****5:EEy.Wg?i" />

and in your code use :

 Notifications = new OpenIdConnectAuthenticationNotifications()
                    {


 AuthorizationCodeReceived = (context) => private static string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];

 ClientCredential credential = new ClientCredential(clientId, appKey);

 string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM