Well... better late than never. I ran into this same problem today. The problems comes when you publish .ASPX pages in the _Layouts folder, and then, when using Forms or Claims auth, make that custom page your first hit in a session (with no previously remembered login). SharePoint authentication isn't fired by default (even if you inherit from the LayoutsPageBase class). If you navigate to some other SharePoint page (such as _Layouts/15/Settings.aspx) and then come back, then the CurrentUser is filled in. I had to use Reflector to get a better clue of what was going on, and how to fix it. The short answer is, once you realize that the CurrentUser == null, you need to add this line of code:
Microsoft.SharePoint.Utilities.SPUtility.HandleAccessDenied(new UnauthorizedAccessException());
In my case, this code generates a challenge/response to the browser, which I used to log in, and immediately following this line of code, the CurrentUser object is filled in correctly. Here is what my entire function ended up looking like:
public static bool isAdminAuthorized()
{
Microsoft.SharePoint.SPContext oContext ;
Microsoft.SharePoint.SPWeb oWeb ;
Microsoft.SharePoint.SPUser oUser ;
try
{
oContext = Microsoft.SharePoint.SPContext.Current;
}
catch { throw new Exception("Can't obtain Sharepoint Context!"); }
try
{
oWeb = oContext.Web;
}
catch { throw new Exception("Can't obtain Sharepoint web!"); }
try
{
oUser = oWeb.CurrentUser;
}
catch { throw new Exception("Can't obtain Sharepoint current user!"); }
if (oUser == null)
{
Microsoft.SharePoint.Utilities.SPUtility.HandleAccessDenied(new UnauthorizedAccessException());
oUser = oWeb.CurrentUser;
}
foreach (Microsoft.SharePoint.SPGroup oGroup in oUser.Groups)
{
if (oGroup.Name.ToUpper().Contains("OWNER"))
{
return true;
}
}
return false;
}