![](/img/trans.png)
[英]Getting username in an mvc application with no authentication and anonymous authentication enabled in IIS
[英]How to force MVC application to ask for credentials with Windows authentication enabled
我正在開發一個應用程序,該應用程序從另一個應用程序的 API 中檢索一些數據並將其顯示在表中。 我已經設置了 Windows 身份驗證(基於某個 AD 組的成員身份)並且它有效,但我想這樣做,以便在嘗試訪問所需頁面時始終要求用戶提供憑據。 我怎樣才能做到這一點?
我是 ASP.NET 的初學者,所以我沒有想出任何嘗試,我已經做了一些谷歌搜索,但沒有找到任何相關的東西。 當我認為我做到了時,它真的很舊,不再適用。
這是我的 appsettings.json:
"SecuritySettings": {
"ADGroup": "ad\\GSRLB2P_ISP_ITSD_INFRA_VST" }
控制器:
public class DeviceController : Controller
{
[Authorize(Policy = "ADRoleOnly")]
public IActionResult Index(string sortOrder, string searchString)
...
啟動:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddAuthorization(options =>
{
options.AddPolicy("ADRoleOnly", policy => policy.RequireRole(Configuration["SecuritySettings:ADGroup"]));
});
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
}
我知道身份驗證有效,因為當我將組名更改為其他名稱時,它不允許我訪問該頁面。 但無論如何,我希望頁面要求提供憑據。 是否可以?
您可以使用return HttpUnauthorized()
在用戶第一次點擊該頁面時發送 HTTP 401 響應。
Windows 身份驗證的工作方式如下:
如果服務器隨后發送另一個401,則瀏覽器將提示輸入新憑據。
如果您這樣做,您應該啟用會話並在會話中存儲一個標志,表明您已經發送了 401,以便您下次可以讓它們進入。 像這樣的東西:
[Authorize(Policy = "ADRoleOnly")]
public IActionResult Index(string sortOrder, string searchString) {
if (!HttpContext.Session.Keys.Contains("Sent401")) {
HttpContext.Session.SetString("Sent401", "yes");
return HttpUnauthorized();
}
...
}
你可以為你的控制器方法嘗試這樣的事情:
public ActionResult Index()
{
...
return new HttpUnauthorizedResult(); // force a login prompt
}
這將導致瀏覽器在頁面加載時拋出登錄提示。 正如這里的另一個答案所說,您還需要在返回該結果之前設置某種條件,例如檢查當前用戶是否已通過身份驗證; 否則,上面的代碼只會反復提示用戶。
<system.web>
<identity impersonate="true"/>
<authentication mode="Windows"></authentication>
</system.web>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.