В настоящее время у нас есть приложение ASPX для веб-форм, к которому я пытаюсь добавить аутентификацию Azure в качестве опции входа.В настоящее время я не хочу переписывать приложение как приложение MVC.
Я добавил файл Startup.cs в приложение, а также Microsoft.Owin.Security, Microsoft.Owin.Security.Cookies, Microsoft.Owin.Security.OpenIdConnect.В настоящее время приложение использует проверку подлинности на основе форм, но я хотел бы добавить Azure в качестве типа входа и будет отслеживать, какой тип входа они используют с переменной, чтобы приложение знало, как их выходить из системы.Я не могу заставить его отправить меня на страницу общего входа Microsoft.Кто-нибудь знает, что я делаю неправильно, чтобы заставить это работать?
Если я просматриваю контекст с кнопки после ее запуска, ответом является 401, но если я использую тот же идентификатор клиента и использую предоставленный Microsoft Azure SampleПриложение правильно настроено на портале Azure.
В моем файле Startup.cs у меня есть:
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.Owin.Security.Notifications;
[assembly: OwinStartup(typeof(ClientDevicesManagement.Startup))]
namespace ClientDevicesManagement
{
public class Startup
{
// The Client ID (a.k.a. Application ID) is used by the application to uniquely identify itself to Azure AD
string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];
// RedirectUri is the URL where the user will be redirected to after they sign in
string redirectUrl = System.Configuration.ConfigurationManager.AppSettings["redirectUrl"];
// Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];
// Authority is the URL for authority, composed by Azure Active Directory endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com)
string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);
/// <summary>
/// Configure OWIN to use OpenIdConnect
/// </summary>
/// <param name="app"></param>
public void Configuration(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
// Sets the ClientId, authority, RedirectUri as obtained from web.config
ClientId = clientId,
Authority = authority,
RedirectUri = redirectUrl,
// PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
PostLogoutRedirectUri = redirectUrl,
//Scope is the requested scope: OpenIdConnectScopes.OpenIdProfileis equivalent to the string 'openid profile': in the consent screen, this will result in 'Sign you in and read your profile'
Scope = OpenIdConnectScope.OpenIdProfile,
// ResponseType is set to request the id_token - which contains basic information about the signed-in user
ResponseType = OpenIdConnectResponseType.IdToken,
// ValidateIssuer set to false to allow work accounts from any organization to sign in to your application
// To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name or Id (example: contoso.onmicrosoft.com)
// To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false
},
// OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = OnAuthenticationFailed
}
}
);
}
/// <summary>
/// Handle failed authentication requests by redirecting the user to the home page with an error in the query string
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
{
context.HandleResponse();
context.Response.Redirect("/?errormessage=" + context.Exception.Message);
return Task.FromResult(0);
}
}
}
В моем login.aspx я добавил кнопку asp, которая запускает это вкод позади:
protected void btn_azure_Click(object sender, EventArgs e)
{
Context.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
web.config выглядит следующим образом:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<REMOVED DB STINGS>
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ClientId" value="REMOVED CLIENT ID" />
<add key="RedirectUrl" value="http://localhost:44463/" />
<add key="Tenant" value="common" />
<add key="Authority" value="https://login.microsoftonline.com/{0}" />
</appSettings>
<system.web>
<sessionState timeout="59"></sessionState>
<!--<trust level="full"/>-->
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<!-- other configuration sections -->
<!--TEMPTEST-->
<siteMap defaultProvider="default">
<providers>
<clear />
<add name="admin" type="System.Web.XmlSiteMapProvider" siteMapFile="~/sitemaps/admin.sitemap" />
<add name="operation" type="System.Web.XmlSiteMapProvider" siteMapFile="~/sitemaps/operation.sitemap" />
<add name="tech" type="System.Web.XmlSiteMapProvider" siteMapFile="~/sitemaps/tech.sitemap" />
<add name="vendor" type="System.Web.XmlSiteMapProvider" siteMapFile="~/sitemaps/vendor.sitemap" />
<add name="default" type="System.Web.XmlSiteMapProvider" siteMapFile="~/sitemaps/default.sitemap" />
<add name="user" type="System.Web.XmlSiteMapProvider" siteMapFile="~/sitemaps/user.sitemap" />
</providers>
</siteMap>
<customErrors mode="Off" />
<authentication mode="Forms">
<forms loginUrl="login.aspx" name=".tgcpauth" defaultUrl="~/default.aspx" timeout="30" slidingExpiration="true" cookieless="UseCookies" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="aspmx.l.google.com" userName="REMOVED" password="REMOVED" port="25" />
</smtp>
</mailSettings>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system.net>
<location path="styles/login.css">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>