次のように、コントローラーをAuthorize属性で装飾しました。
[Authorize(Roles="ExecAdmin")]
ExecAdmin以外のユーザーとしてログインした後でそのコントローラーにアクセスしようとすると、ログインページにリダイレクトしようとしているように見えます。しかし、リダイレクトしようとしているページは私のログインページではなく、LogOnUserControl.ascxというビューです。これは私のログインページに表示されない部分的なビューです。
なぜこれを行っているのかわかりません。あるいは、LogOnUserControl.ascxを表示している他のページに完全にリダイレクトしようとしているのかもしれません。それとも、名前に「LogOn」が含まれているものを探しているのでしょうか。(私のログインビューの名前はLogOn.aspxですが...)
どのページにリダイレクトするかをどのように伝えることができますか?
更新:私はglobal.asaxにこれを持っています
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null || authCookie.Value == "")
{
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch
{
return;
}
string[] roles = authTicket.UserData.Split(new char[] { ';' });
//Context.ClearError();
if (Context.User != null)
{
Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
}
}
...私は役割を定義する非標準的な方法を使用しているので; つまり、ASP.NETメンバーシップスキームを使用していません(web.configなどで定義されたロールプロバイダーを使用)。代わりに、次のように役割を設定しています。
// get user's role
string role = rc.rolesRepository.GetUserType(rc.loginRepository.GetUserID(userName)).ToString();
// create encryption cookie
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(120),
createPersistentCookie,
role //user's role
);
// add cookie to response stream
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
(これは、ユーザーが検証された後に呼び出されます。)
これが全体にどのように影響するかはわかりませんが...
更新:Robertのソリューションのおかげで、これが私がそれを解決した方法です-AuthorizeAttributeクラスを拡張します:
public class AuthorizeAttributeWithMessage : AuthorizeAttribute
{
private string _message = "";
public string Message
{
get {
return _message;
}
set {
_message = value;
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
// user is logged in but wrong role or user:
filterContext.Controller.TempData.Add("Message", Message);
}
base.HandleUnauthorizedRequest(filterContext);
}
}
次に、ログオンビューで:
<%
if (HttpContext.Current.Request.IsAuthenticated)
{
// authenticated users should not be here
Response.Redirect("/Home/Index");
}
%>
そしてホームページビューで:
<% if (TempData != null && TempData.Count > 0 && TempData.ContainsKey("Message"))
{ %>
<div class="largewarningtext"><%= TempData["Message"]%></div>
<% } %>
そして、影響を受けるコントローラーの上に:
[AuthorizeAttributeWithMessage(Roles = "Consultant,ExecAdmin", Message = "You do not have access to the requested page")]
これには、Logon.aspxに到達する認証済みユーザーを常にリダイレクトするという利点があります。認証済みユーザーはそこにいるべきではありません。TempDataにメッセージがある場合は、ホームページに出力されます。そうでない場合は、少なくともリダイレクトが実行されます。