Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Authorize Attribute not working asp.net

In my c# app I am adding a custom attribute like this

public class CheckLogIn : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (!httpContext.Request.IsAuthenticated)
            return false;
        return (Auth.UserLoggedIn || Auth.AdminLoggedIn);
    }
}

I am calling this attribute like this

[CheckLogIn]
public dynamic Create(String projectName, String organizationId)
{
    Project pro = Project.Create(organizationId, projectName).Save();

    return new
    {
        organizationId = pro.OrganizationId,
        name = pro.Name,
        id = pro.Id
    };
}

The AuthorizeCore is not being called. I have a break point there but it seems like it never gets called. Am I missing something here?

I have tried calling [CheckLogIn] from a regular controller it works, from an api controller it doesn't.

like image 741
mohsinali1317 Avatar asked Dec 04 '22 04:12

mohsinali1317


1 Answers

The System.Web.Http.AuthorizeAttribute for WebApi is a different type than the System.Web.Mvc.AuthorizeAttribute for MVC.

The reason why it doesn't work with WebApi is because WebApi doesn't know about MVC types. You need to create a type that inherits System.Web.Http.AuthorizeAttribute for that purpose.

like image 70
NightOwl888 Avatar answered Dec 21 '22 16:12

NightOwl888