Переназначение несанкционированных пользователей asp net
Я работаю над простым сайтом в asp.net.
Я хотел бы ограничить доступ к стороне, так что разрешены только пользователи в определенной группе AD. Я сделал это, и он работает нормально. Но когда пользователь, не входящий в группу AD, пытается получить доступ к сайту, он получает приглашение для входа. Как перенаправить неавторизованного пользователя на пользовательскую страницу, а не получать приглашение для входа?
Ниже мой web.config. Самая низкая часть кода - это то, что я пытался, но не работал.
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Windows"/>
<authorization>
<allow roles="DOMAIN\GROUP"/>
<deny users="*"/>
</authorization>
</system.web>
<location path="AccessDenied.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
</configuration>
Я добавил это в файл Global.asax.cs:
protected void Application_EndRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Response.Status.StartsWith("401"))
{
HttpContext.Current.Response.ClearContent();
Server.Execute("AccessDenied.aspx");
}
}
Любые идеи?
EDIT:
Я пробовал некоторые из размещенных решений, но они не работали.
Но я работал с этим кодом:
void Application_EndRequest(object sender, System.EventArgs e)
{
if (((Response.StatusCode == 401)
&& (Request.IsAuthenticated == true)))
{
Response.ClearContent();
Response.Redirect("~/AccessDenied.aspx");
}
}
}
Ответы
Ответ 1
Вы можете использовать Response.Redirect
или Server.Transfer
Response.Redirect("AccessDenied.aspx");
Полный пример:
protected void Application_EndRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Response.Status.StartsWith("401"))
{
HttpContext.Current.Response.ClearContent();
Response.Redirect("AccessDenied.aspx");
}
}
Ответ 2
Предполагая, что вы хотите обрабатывать все "несанкционированные" ошибки:
<customErrors defaultRedirect="Error.aspx" mode="On">
<error statusCode="401" redirect="Unauthorized.aspx" />
<error statusCode="403" redirect="Forbidden.aspx" />
</customErrors>
Любые 401 (несанкционированные) запросы будут перенаправлены на Unauthorized.aspx.
Ответ 3
У меня был больше успеха с этим:
// This is a workaround for the fact that we are not using MVC and its attributes
// This is the situation where a user is logged in - but not authorized for this page
void Application_EndRequest (object sender, System.EventArgs e)
{
if (((Response.StatusCode == 302) && (Request.IsAuthenticated == true)))
{
try
{
string sLoc = Response.Headers ["Location"];
if (sLoc.Contains ("Login"))
{
Response.ClearContent ();
Response.Redirect ("~/AccessDenied.aspx");
}
}
catch
{
}
}
}
Ответ 4
<authorization>
<!--<allow users="*"/>-->This here means allow everyone .
<allow users="AD"/> -- Add this group to AD domain .
<deny users="?"/> --Deny unknown users(Not authenticated)
<allow roles="Admins"/> --If you have created roles .
Если у вас есть локальная группа, чем использование <allow user ="AD">
, но вам необходимо зарегистрировать ее в домене AD.
<allow roles ="AD" />
будет работать только с группами домена AD не для локальных групп.
protected void Application_EndRequest(Object sender,EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context.Response.Status.Substring(0,3).Equals("401"))
{
context.Response.ClearContent();
//do redirect here
}
}