96

I am using form authentication with below method in my ASP.NET application

FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);

How do I check whether user is logged in or not? And how can I get the user name of a logged in user?

ryanyuyu
  • 6,366
  • 10
  • 48
  • 53
Muneer
  • 7,384
  • 7
  • 38
  • 62

4 Answers4

206

I managed to find the correct one. It is below.

bool val1 = System.Web.HttpContext.Current.User.Identity.IsAuthenticated

EDIT

The credit of this edit goes to @Gianpiero Caretti who suggested this in comment.

bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated
Community
  • 1
  • 1
Muneer
  • 7,384
  • 7
  • 38
  • 62
  • 35
    Just a little fix for safer code: bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated – Gianpiero May 30 '13 at 04:30
  • 17
    In newer versions of C#, you can use `User?.Identity.IsAuthenticated == true`. – bradlis7 Mar 17 '16 at 20:29
  • 5
    or `User?.Identity.IsAuthenticated ?? false`, but @bradlis7's code is probably easier to read. – Michael Dec 19 '17 at 19:19
  • or `(User?.Identity.IsAuthenticated).GetValueOrDefault()` – Stacey Jun 03 '21 at 10:37
15

The simplest way:

if (Request.IsAuthenticated) ...
Keith
  • 20,636
  • 11
  • 84
  • 125
15
if (User.Identity.IsAuthenticated)
{
    Page.Title = "Home page for " + User.Identity.Name;
}
else
{
    Page.Title = "Home page for guest user.";
}
Yanga
  • 2,885
  • 1
  • 29
  • 32
  • 1
    Seeing that this approach doesn't have that many upvotes, are there any drawbacks / issues to watch out for when using this approach? Ive decided to use this and it seems to work, so far. – pnizzle Jan 07 '19 at 03:13
  • It's almost the same as the top voted answer but we are not using namespaces here – mai Mar 29 '19 at 11:26
7

Easiest way to check if they are authenticated is Request.User.IsAuthenticated I think (from memory)

gdoron
  • 147,333
  • 58
  • 291
  • 367
isNaN1247
  • 17,793
  • 12
  • 71
  • 118
  • 1
    well "Request.LogonUserIdentity" class gives all these methods and properties. Thanks for the tip. – Muneer May 22 '11 at 07:04
  • 1
    No @beardtwizzle. This is showing the windows account logged in or not. Even if your cookies removed you can see the user name of window account and login. This one worked for me. "bool val1 = System.Web.HttpContext.Current.User.Identity.IsAuthenticated" – Muneer May 22 '11 at 07:31