简体   繁体   中英

If user is not authenticated go to login page

task: If user is not authenticated go to login page!

I want this behavior in every action of every controller.

But offcourse I do not want to have logic in every action for this

if (User == null || User.Identity == null || !User.Identity.IsAuthenticated)
{
    return RedirectToAction("Index","Authentication");
}

What is good practive for this?


I added to web config:

<authentication mode="Forms">
  <forms loginUrl="~/Authentication" timeout="2880"/>
</authentication>

Controllers have attribute [authorize], except AuthenticationController where I have[AllowAnonymous]

But still not redirect to login page (just show error: HTTP Error 401.0 - Unauthorized)


Edit2: Solved!

I had

 <remove name="FormsAuthentication" /> 

in web.cofig

When I remove this line everything was fine

you should define membership provider or something provides Identity for your system. Then you should use Authorize attribute for your controller.

Authorize attiribute redirects action to login view if user is not authenticated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM