Instead of catching an โunauthorizedโ event in your code, I suggest you go with user errors. When a user is redirected to the Access denied page, SharePoint actually generates an error with error code "401" (for unauthorized access).
In your web.config, you can customize the behavior of your application for 401 errors. If you have ever made a custom error page in a web application, this is the same. Take a look at the CustomError node in your web.config and change it to something like this:
<customErrors mode="On" defaultRedirect="~/_layouts/CustomErrorPage.aspx"> <error statusCode="401" redirect="~/_layouts/AccessDeniedPage.aspx" /> </customErrors>
Then create your CustomErrorPage.aspx and your AccessDeniedPage.aspx and deploy them in 12 bushes.
In the data code of these pages, you can override the PageLoad event to redirect them to where you want:
protected void Page_Load(object sender, EventArgs e) { bool isLogged = HttpContext.Current.User.Identity.IsAuthenticated; Response.Redirect("wherever"); }
Please note that at this point you will still have access to the SPContext object if you need it (and I assume that you will want to write specific code depending on the membership in the user group).
This is not a specific SharePoint behavior. All ASP.NET applications work that way. Using a configuration at the whole site level will allow you to run your code only when it needs to be executed (i.e. when access is denied) instead of checking permissions for each page load or something like that.
source share