c# - ASP.NET MVC Web 应用在发布和验证后重定向到 localhost
问题描述
我正在尝试使用 Azure Active Directory 进行身份验证创建一个简单的 MVC Web 应用程序。我使用 Visual Studio 2017 中的连接服务向导为我执行此操作。我目前的问题是一切都在我的本地机器上完美运行,我能够登录,被重定向到网络应用程序的索引页面,也能够注销。但是,当我发布这个应用程序时,我被重定向到 localhost: https://localhost:44389/而不是 Web 应用程序的索引页面。
- 将 Startup.Auth.cs 中 app.UseOpenIdConnectAuthentication() 方法中的 PostLogoutRedirectUri 更改为指向:
" https://CU-kvtest.azurewebsites.net/ "
这没有用,仍然去了本地主机。
2.更改Web.Config文件中的PostLogoutRedirectUri指向“ https://CU-kvtest.azurewebsites.net/ ”。那也不起作用,仍然去了本地主机
- 转到 Azure 门户并转到名为 ContosoUniversity2 的 Azure Active Directory(这是我正在使用的目录的名称)并将 redirectURI 更改为“ https://CU-kvtest.azurewebsites.net/ ”,这开始导致其他问题。我设置了一个密钥库,可以安全地获取我的 connectionString,现在这个问题开始了:
所以这次尝试也失败了。
- 然后我去我在 Azure 门户中发布的应用服务并添加了两个应用设置:
ida:PostLogoutRedirectUri=" https://CU-kvtest.azurewebsites.net/ " PostLogoutRedirectUri="https://CU-kvtest.azurewebsites.net/"
那也不起作用,只会再次将我指向本地主机。
我真的不知道我还能做什么。我不明白我做错了什么......
启动.Auth.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IdentityModel.Claims;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Owin;
using ContosoUniversity.Models;
namespace ContosoUniversity
{
public partial class Startup
{
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
public static readonly string Authority = aadInstance + tenantId;
// 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 = "https://graph.windows.net/";
public void ConfigureAuth(IAppBuilder app)
{
ApplicationDbContext db = new ApplicationDbContext();
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = Authority,
PostLogoutRedirectUri = "https://CU-kvtest.azurewebsites.net/",
Notifications = new OpenIdConnectAuthenticationNotifications()
{
// If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
ClientCredential credential = new ClientCredential(clientId, appKey);
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
return authContext.AcquireTokenByAuthorizationCodeAsync(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
}
}
});
}
}
}
网络配置
<?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=301880
-->
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false" />
</configSections>
<configBuilders>
<builders>
<add name="AzureKeyVault" vaultName="kv-talha-final" type="Microsoft.Configuration.ConfigurationBuilders.AzureKeyVaultConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Azure, Version=1.0.0.0, Culture=neutral" /></builders>
</configBuilders>
<!--<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ContosoUniversity2;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>-->
<!--Azure connection string-->
<connectionStrings>
<add name="SchoolContext" connectionString="thisdoesntmatter" providerName="System.Data.SqlClient" />
<add name="DefaultConnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-ContosoUniversity-bb3d24b7-855d-4be5-b5ee-a97316af18f2.mdf;Initial Catalog=aspnet-ContosoUniversity-bb3d24b7-855d-4be5-b5ee-a97316af18f2;Integrated Security=True" providerName="System.Data.SqlClient" />
</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="connectionString" value="dummy" />
<!--This is the domain called ContosoUniversity2-->
<add key="ida:ClientId" value="XXXXXXXXXXXXXXXX" />
<add key="ida:AADInstance" value="https://login.microsoftonline.com/" />
<add key="ida:ClientSecret" value="XXXXXXXXXXXX" />
<add key="ida:Domain" value="mtalha97hotmail.onmicrosoft.com" />
<!--The tenant is ContosoUniversity2-->
<add key="ida:TenantId" value="XXXXXXXXXXXXXXXXX" />
<add key="ida:PostLogoutRedirectUri" value="dummy" />
</appSettings>
<!--
For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.
The following attributes can be set on the <httpRuntime> tag.
<system.Web>
<httpRuntime targetFramework="4.7.2" />
</system.Web>
-->
</configuration>
AccountController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.Owin.Security;
namespace ContosoUniversity.Controllers
{
public class AccountController : Controller
{
public void SignIn()
{
// Send an OpenID Connect sign-in request.
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
public void SignOut()
{
string callbackUrl = Url.Action("SignOutCallback", "Account", routeValues: null, protocol: Request.Url.Scheme);
HttpContext.GetOwinContext().Authentication.SignOut(
new AuthenticationProperties { RedirectUri = callbackUrl },
OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
}
public ActionResult SignOutCallback()
{
if (Request.IsAuthenticated)
{
// Redirect to home page if the user is authenticated.
return RedirectToAction("Index", "Home");
}
return View();
}
}
}
用户配置文件控制器.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using System.Threading.Tasks;
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using ContosoUniversity.Models;
namespace ContosoUniversity.Controllers
{
[Authorize]
public class UserProfileController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
private string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
private string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private string graphResourceID = "https://graph.windows.net/";
// GET: UserProfile
public async Task<ActionResult> Index()
{
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
try
{
Uri servicePointUri = new Uri(graphResourceID);
Uri serviceRoot = new Uri(servicePointUri, tenantID);
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
async () => await GetTokenForApplication());
// Use the token for querying the graph to get the user details
var result = await activeDirectoryClient.Users
.Where(u => u.ObjectId.Equals(userObjectID))
.ExecuteAsync();
IUser user = result.CurrentPage.ToList().First();
return View(user);
}
catch (AdalException)
{
// Return to error page.
return View("Error");
}
// If the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
catch (Exception)
{
return View("Relogin");
}
}
public void RefreshSession()
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/UserProfile" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
public async Task<string> GetTokenForApplication()
{
string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
// Get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
ClientCredential clientcred = new ClientCredential(clientId, appKey);
// Initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
return authenticationResult.AccessToken;
}
}
}
解决方案
推荐阅读
- python - 如何改进我对德语文本的多类文本分类?
- sql - 在 Postgresql 中使用冲突忽略特定行和合并操作
- laravel - 为什么 Laravel homestead 不从视图中显示欢迎页面并显示另一个?
- javascript - 映射函数React中的条件表单元格
- r - 如果命令具有像“cmd | head”这样的管道,我如何使用 system 或 system2
- reactjs - 如何从异步存储中获取项目,在键中设置值,然后使用该值向 api 发出 axios 请求以进行响应?
- sql - 按顺序组合记录
- c# - 使用类库静态方法的 Serilog 输出
- google-cloud-run - Terraform中如何控制资源是否存在?
- javascript - 直接导出反应属性与 toRef 包装