Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if user is authenticated in Razor pages of .Net Core 2.0

I would like to check if a user is logged in in an ASP.NET Core 2.0 application in a Razor page. The following code worked in .NET 4.6.1:

@if (!Request.IsAuthenticated) {     <p><a href="@Url.Action("Login", "Account")" class="btn btn1-success btn-lg" role="button" area="">Sign In &raquo;</a></p> } 

How can I do this in Core 2.0?

like image 349
Roddy Balkan Avatar asked Aug 25 '17 19:08

Roddy Balkan


People also ask

How do I Authorize a user in .NET core?

Authorization in ASP.NET Core is controlled with AuthorizeAttribute and its various parameters. In its most basic form, applying the [Authorize] attribute to a controller, action, or Razor Page, limits access to that component to authenticated users. Now only authenticated users can access the Logout function.

How do I Authorize my razor page?

One way to control access in your Razor Pages app is to use authorization conventions at startup. These conventions allow you to authorize users and allow anonymous users to access individual pages or folders of pages. The conventions described in this topic automatically apply authorization filters to control access.

Why is user identity IsAuthenticated false?

isauthenticated is False when a user is already logged in.


1 Answers

Edit: David is right of course.

Just check if User or HttpContext.User.Identity.IsAuthenticated is true or not.

@if(!User.Identity.IsAuthenticated)  {     ... } 
like image 101
Tseng Avatar answered Sep 30 '22 21:09

Tseng