Stefan Gross
Stefan Gross

Reputation: 1

Executing code when accessing API controllers

I have the following code:

CookieHeaderValue cookie = Request.Headers.GetCookies("session").FirstOrDefault();
var isAuthenticated = _userService.IsAuthenticated(cookie);

if (!isAuthenticated) 
    return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "");

I'd like this code to execute as soon as any part of my api is called. I havn't found any good solutions or ways to do this so i thought i would ask here instead.

(what I do now is execute the code in every get/post/put/delete which is horrible).

Upvotes: 0

Views: 76

Answers (3)

Stefan Gross
Stefan Gross

Reputation: 1

So i found the best solution for my problem was the following code:

public class CookieFilterAttribute : AuthorizeAttribute
{
    [Inject]
    public IUserService UserService { get; set; }

    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        CookieHeaderValue cookie = actionContext.Request.Headers.GetCookies("session").FirstOrDefault();
        var isAuthenticated = UserService.IsAuthenticated(cookie);

        return isAuthenticated;
    }
}

Upvotes: 0

CodeCaster
CodeCaster

Reputation: 151604

The best place to solve this would be an authorization filter attribute. See Authentication Filters in ASP.NET Web API 2.

The subject is too broad to repeat here in its entirety, but it comes down to creating an attribute:

public class CookieAuthenticationFilterAttribute : Attribute, IAuthenticationFilter
{
    public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        // your cookie code
    }
}

And applying it to the controller or action methods:

[YourCookieAuthentication]

But be sure to read the link.

Upvotes: 1

Markus
Markus

Reputation: 22481

You can use an ActionFilter or AuthorizationFilter for this purpose. These are attribute classes that you can use on specific controllers/actions or globally. So you don't need to repeat the code for every action.

See this link for details. It shows the general authentication/authorization flow in ASP.NET Web API and how you can customize it.

Upvotes: 0

Related Questions