I'm working on a web app that uses Azure AD for user authentication. However, I am struggling to redirect the user to the home page after they successfully signed out. I've tried following this documentation, but this isn't the solution I am looking for.
In SignOut()
in HomeController.cs, is there an alternative way without returning
SignOut(new AuthenticationProperties { RedirectUri = callbackUrl },
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme)
This is what I have:
Index.cshtml
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://learn.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>
HomeController.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;
}
}
Program.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();
appsettings.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": "*"
}