我正在開發一個使用 Azure AD 進行用戶身份驗證的 Web 應用程式。但是,在用戶成功退出后,我正在努力將用戶重定向到主頁。我已嘗試遵循此檔案,但這不是我正在尋找的解決方案。
在SignOut()HomeController.cs 中,有沒有不回傳的替代方法
SignOut(new AuthenticationProperties { RedirectUri = callbackUrl },
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme)
這就是我所擁有的:
索引.cshtml
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
<p>@ViewBag.test</p>
@if (User?.Identity?.IsAuthenticated ?? false)
{
<h2>User is login</h2>
<a asp-controller="Home" asp-action="SignOut">Sign out</a>
}
else
{
<h2>User is not login</h2>
}
</div>
家庭控制器.cs
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Identity.Web;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Authorization;
using HealthAD.Models;
using HealthAD.Graph;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
namespace HealthAD.Controllers;
[Authorize(Policy = "OpenIdConnect")]
[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
public class HomeController : Controller
{
private readonly GraphProfileClient _graphProfileClient;
private readonly ITokenAcquisition _tokenAcquisition;
private readonly ILogger<HomeController> _logger;
public string UserDisplayName { get; private set; } = "";
public HomeController(
ILogger<HomeController> logger,
GraphProfileClient graphProfileClient,
ITokenAcquisition tokenAcquisition
)
{
_logger = logger;
_graphProfileClient = graphProfileClient;
_tokenAcquisition = tokenAcquisition;
}
public async Task<ActionResult<Microsoft.Graph.User?>> Test()
{
// await OnGetAsync();
var test = await _graphProfileClient.GetUserProfile();
return test;
}
[AllowAnonymous]
public IActionResult Index()
{
ViewBag.test = "Test";
return View();
}
[HttpGet]
public IActionResult SignOut()
{
var callbackUrl = Url.Action(nameof(SignedOut), "Home", values: null, protocol: Request.Scheme);
return SignOut
(
new AuthenticationProperties { RedirectUri = callbackUrl },
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme
);
}
[HttpGet]
public IActionResult SignedOut()
{
if (User?.Identity?.IsAuthenticated ?? false)
{
return RedirectToAction(nameof(HomeController.Index), "Index");
}
return RedirectToAction(nameof(HomeController.Index), "Index");
}
public async Task<IActionResult> Privacy()
{
var test = await _graphProfileClient.GetUserProfile();
ViewBag.name = test.DisplayName;
return View();
}
public async Task OnGetAsync()
{
var user = await _graphProfileClient.GetUserProfile();
UserDisplayName = user.DisplayName;
}
}
程式.cs
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Identity.Web;
using HealthAD.Graph;
var builder = WebApplication.CreateBuilder(args);
var initialScopes = builder.Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(" ");
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services
.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
builder.Services.AddAuthorization(configurations =>
{
configurations.AddPolicy("OpenIdConnect", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(OpenIdConnectDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build()
);
});
builder.Services.AddScoped<GraphProfileClient>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
應用設定.json
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"ClientId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"TenantId": "xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxx",
"Domain": "domain.com",
"CallbackPath": "/signin-oidc",
"SignedOutCallbackPath ": "/signout-oidc",
"ClientSecret": "xxxxx~xxxxxx-xxxxxx-xxxxxxxxxxxxxxxxx"
},
"DownstreamApi": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "user.read"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
uj5u.com熱心網友回復:
請注意,中間件中的順序必須如下所示,這很重要。
app.UseAuthentication();
app.UseAuthorization();
嘗試在您的應用程式中構建一個注銷 URI,以便當用戶單擊注銷鏈接或按鈕時,您會將您的用戶重定向到該 URI。注銷 URI 的格式為:
https://login.microsoftonline.com/{0}/oauth2/logout?post_logout_redirect_uri=
另請注意,如果沒有會話,則注銷重定向失敗即;如果我們在
"https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri=https://localhost/myapp/logout/?&client_id=;"沒有會話的情況下使用請求,它會帶您到顯示“成功注銷”的頁面,但它不會重定向,因為 AzureAD 不會在沒有正確會話的情況下重定向,因為那不是安全實踐。
- 如果需要,還可以轉到門戶中的應用注冊并將注銷 url設定為回復 url。
請檢查AzureAD microsoft authentication library for-js 問題
在 AccountController 中,嘗試修改回呼重定向 url。作為一種解決方法,嘗試構建您自己的 AccountController 如下所示并將用戶重定向到: https://login.microsoftonline.com/common/oauth2/logout然后注銷重定向回您的應用程式主頁。
public class AccountController : Controller { [HttpGet] public IActionResult SignIn() { ... } [HttpGet] public IActionResult SignOut() { var callbackUrl = Url.Action(nameof(SignedOut), "Account", values: null, protocol: Request.Scheme); return SignOut( new AuthenticationProperties { RedirectUri = callbackUrl }, CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme); } [HttpGet] public IActionResult SignedOut() { if (User.Identity.IsAuthenticated) { // Redirect to home page if the user is authenticated. return RedirectToAction(nameof(HomeController.Index), "Home"); } return RedirectToAction(nameof(HomeController.Index), "pathtoberedirectedto"); }
參考:
- 在 .NET 核心中使用 Azure AD 身份驗證時如何指定自定義注銷 URL - 代碼日志
- asp.net mvc 4 - 注銷 MVC 4 上的清除會話 - VoidCC
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/461494.html
標籤:C# asp.net-mvc 天蓝色活动目录 .net-6.0
