NET 6 - Azure AD 和 Cookie 身份验证

NET 6 - Azure AD and Cookie Authentication

提问人:Milacay 提问时间:11/17/2023 更新时间:11/17/2023 访问量:35

问:

我是 .NET 的新手,正在尝试学习身份验证。我遵循了本教程 Azure Active Directory(AD) 身份验证,它有两种身份验证方法:使用 Cookie 和 Azure AD(太好了,我两者都需要)。我能够成功地实现两者,但最终遇到了问题。向 Azure AD 进行身份验证后(请假设 AzureAd 设置正确且在 appsettings.json 中工作正常)后,它会重定向回应用程序;但是,始终是假的,并且不显示任何内容。User.Identity.IsAuthenticated@User.Identity.Name

Program.cs 文件:

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;

var builder = WebApplication.CreateBuilder(args);

//set CookieAuthenticationDefaults.AuthenticationScheme as the default authentication scheme
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(x => x.LoginPath = "/account/login");
builder.Services.AddAuthentication()
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"), OpenIdConnectDefaults.AuthenticationScheme, "ADCookies");

// Add microsoft sign in page
builder.Services.AddControllersWithViews().AddMicrosoftIdentityUI();

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.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

login.cshtml 页面:

@model WebAppMvcCookieAuthAad.Models.LoginModel
@{
    ViewData["Title"] = "Login";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Login</h2>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Login">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            @if (!string.IsNullOrEmpty(ViewBag.Message))
            {
                <span class="text-danger">
                    @ViewBag.Message
                </span>
            }
            @Html.HiddenFor(x => x.ReturnUrl)
            <div class="form-group">
                <label asp-for="UserName" class="control-label"></label>
                <input asp-for="UserName" class="form-control" />
                <span asp-validation-for="UserName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Password" class="control-label"></label>
                <input asp-for="Password" class="form-control" />
                <span asp-validation-for="Password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <div class="checkbox">
                    <label>
                        <input asp-for="RememberLogin" /> @Html.DisplayNameFor(model => model.RememberLogin)
                    </label>
                </div>
            </div>
            <div class="form-group">
                <input type="submit" value="Login" />
            </div>
        </form>
    </div>
</div>

<div>
    <label>sign in with aad</label>
    <a asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in with aad</a>
</div>

The AccountController:

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using WebAppMvcCookieAuthAad.Models;

namespace WebAppMvcCookieAuthAad.Controllers
{
    public class AccountController : Controller
    {
        public List<UserModel> users = null;
        public AccountController()
        {
            users = new List<UserModel>();
            users.Add(new UserModel()
            {
                UserId = 1,
                Username = "Tiny",
                Password = "123",
                Role = "Admin"
            });
            users.Add(new UserModel()
            {
                UserId = 2,
                Username = "Other",
                Password = "123",
                Role = "User"
            });
        }
        public IActionResult Login(string ReturnUrl = "/")
        {
            LoginModel objLoginModel = new LoginModel();
            objLoginModel.ReturnUrl = ReturnUrl;
            return View(objLoginModel);
        }
        [HttpPost]
        public async Task<IActionResult> Login(LoginModel objLoginModel)
        {
            if (ModelState.IsValid)
            {
                var user = users.Where(x => x.Username == objLoginModel.UserName && x.Password == objLoginModel.Password).FirstOrDefault();
                if (user == null)
                {
                    ViewBag.Message = "Invalid Credential";
                    return View(objLoginModel);
                }
                else
                {
                    var claims = new List<Claim>() {
                    new Claim(ClaimTypes.NameIdentifier, Convert.ToString(user.UserId)),
                        new Claim(ClaimTypes.Name, user.Username),
                        new Claim(ClaimTypes.Role, user.Role),
                        new Claim("FavoriteDrink", "Tea")
                    };
                    var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    var principal = new ClaimsPrincipal(identity);
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties()
                    {
                        IsPersistent = objLoginModel.RememberLogin
                    });
                    return LocalRedirect(objLoginModel.ReturnUrl);
                }
            }
            return View(objLoginModel);
        }
        public async Task<IActionResult> LogOut()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return LocalRedirect("/");
        }
    }
}

在_Layout页中,我有以下代码来检查用户是否已登录到 Azure AD 中:

<ul class="nav navbar-nav navbar-right">
    <li>
        @if (User.Identity.IsAuthenticated)
        {
            <span class="navbar-text text-dark">Hello @User.Identity?.Name!</span>
            <span class="navbar-text text-dark" style="display:inline;">Hello @User.Identity?.Name!</span>
            <a asp-controller="Account" asp-action="Logout">Logout</a>
        }
        else
        {
            
            <a asp-controller="Account" asp-action="SignIn">Login</a>
        }

    </li>
</ul>

问题是我在登录页面上单击“使用 aad 登录”,它会提示登录 Azure。在我登录 Azure 并被重定向回应用程序后,仍然是 false。我只是在Proogram .cs或控制器中配置/做错了什么。User.Identity.IsAuthenticate

请帮忙。任何建议将不胜感激。提前致谢。

ASP.NET-MVC 格式

评论


答: 暂无答案