Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if user is authorized inside Action

Usually I protect my Actions with [Authorize] but this time I need to check if a user is authorized inside the action.

Eg

if(userIsAuthorized) {     //do stuff } else {     //return to login page } 

I believe I am using 'Forms Authentication'

This question is kind of similar to this but none of the answers given seemed to work.

EDIT: I have done some more digging- it seems if I breakpoint on an Action that has [Authorize], the User.Identity is set, but on Actions without it, the User.Identity is empty, even if I am logged in

like image 552
elwyn Avatar asked Feb 05 '10 03:02

elwyn


2 Answers

If you just want to know if the user is logged in:

if (User.Identity.IsAuthenticated) { ... } 

If you are trying to do anything role-specific:

if (User.IsInRole("Administrators")) { ... } 

The User instance is a public property of the Controller class, so you always have access to it from a Controller you write. If no user is logged in you should have a GenericPrincipal for the User and a GenericIdentity for the User.Identity, so don't worry about checking for nulls.

like image 193
Aaronaught Avatar answered Sep 29 '22 12:09

Aaronaught


Request.IsAuthenticated should work for what you're trying to do.

like image 22
Esteban Araya Avatar answered Sep 29 '22 12:09

Esteban Araya