How to get request cookies in Web API authorization attribute?
Solution 1
public class Foo : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
var cookie = actionContext.Request.Headers.GetCookies("Bar").FirstOrDefault();
}
}
Solution 2
string sessionId = "";
CookieHeaderValue cookie = Request.Headers.GetCookies("bar").FirstOrDefault();
if (cookie != null)
{
sessionId = cookie["bar"].Value;
}
Solution 3
GetCookies returns collection of cookieS then you will need to get cookie that you need.
public class Foo : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
var cookies = actionContext.Request.Headers.GetCookies("Bar").FirstOrDefault();
var cookie = cookies["Bar"];
}
}
Arkadiusz Kałkus
I’m a full-stack developer specialized in the design, and implementation of corporate web applications. I put emphasis on S.O.L.I.D. craftsmanship and strive to keep my code clean. Because I know how expensive technical debt can be. Because I understand my job is not to write code but to solve problems. Because I want to help people to be more effective through the software.
Updated on July 09, 2022Comments
-
Arkadiusz Kałkus almost 2 years
In .NET there are two
AuthorizeAttribute
classes. One defined inSystem.Web.Http
namespace:namespace System.Web.Http { // Summary: // Specifies the authorization filter that verifies the request's System.Security.Principal.IPrincipal. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizeAttribute : AuthorizationFilterAttribute { // Summary: // Initializes a new instance of the System.Web.Http.AuthorizeAttribute class. public AuthorizeAttribute(); // Summary: // Gets or sets the authorized roles. // // Returns: // The roles string. public string Roles { get; set; } // // Summary: // Gets a unique identifier for this attribute. // // Returns: // A unique identifier for this attribute. public override object TypeId { get; } // // Summary: // Gets or sets the authorized users. // // Returns: // The users string. public string Users { get; set; } // Summary: // Processes requests that fail authorization. // // Parameters: // actionContext: // The context. protected virtual void HandleUnauthorizedRequest(HttpActionContext actionContext); // // Summary: // Indicates whether the specified control is authorized. // // Parameters: // actionContext: // The context. // // Returns: // true if the control is authorized; otherwise, false. protected virtual bool IsAuthorized(HttpActionContext actionContext); // // Summary: // Calls when an action is being authorized. // // Parameters: // actionContext: // The context. // // Exceptions: // System.ArgumentNullException: // The context parameter is null. public override void OnAuthorization(HttpActionContext actionContext); } }
Another defined in
System.Web.Mvc
namespace:namespace System.Web.Mvc { // Summary: // Specifies that access to a controller or action method is restricted to users // who meet the authorization requirement. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter { // Summary: // Initializes a new instance of the System.Web.Mvc.AuthorizeAttribute class. public AuthorizeAttribute(); // Summary: // Gets or sets the user roles that are authorized to access the controller // or action method. // // Returns: // The user roles that are authorized to access the controller or action method. public string Roles { get; set; } // // Summary: // Gets the unique identifier for this attribute. // // Returns: // The unique identifier for this attribute. public override object TypeId { get; } // // Summary: // Gets or sets the users that are authorized to access the controller or action // method. // // Returns: // The users that are authorized to access the controller or action method. public string Users { get; set; } // Summary: // When overridden, provides an entry point for custom authorization checks. // // Parameters: // httpContext: // The HTTP context, which encapsulates all HTTP-specific information about // an individual HTTP request. // // Returns: // true if the user is authorized; otherwise, false. // // Exceptions: // System.ArgumentNullException: // The httpContext parameter is null. protected virtual bool AuthorizeCore(HttpContextBase httpContext); // // Summary: // Processes HTTP requests that fail authorization. // // Parameters: // filterContext: // Encapsulates the information for using System.Web.Mvc.AuthorizeAttribute. // The filterContext object contains the controller, HTTP context, request context, // action result, and route data. protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext); // // Summary: // Called when a process requests authorization. // // Parameters: // filterContext: // The filter context, which encapsulates information for using System.Web.Mvc.AuthorizeAttribute. // // Exceptions: // System.ArgumentNullException: // The filterContext parameter is null. public virtual void OnAuthorization(AuthorizationContext filterContext); // // Summary: // Called when the caching module requests authorization. // // Parameters: // httpContext: // The HTTP context, which encapsulates all HTTP-specific information about // an individual HTTP request. // // Returns: // A reference to the validation status. // // Exceptions: // System.ArgumentNullException: // The httpContext parameter is null. protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext); } }
Main differences between those two are:
System.Web.Http
version can be used by Web APISystem.Web.Mvc
version can be used by ASP.NET MVCHttp
version useHttpActionContext
parameter type in OnAuthorization method whenMvc
version useAuthorizationContext
type.
I want to access request cookies in
Http
version ofAuthorizeAttribute
. InMvc
version it is implemented as follows:public class Foo : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { HttpCookie cookie = filterContext.HttpContext.Request.Cookies.Get("Bar"); } }
Does anybody know how can I do the same with
HttpActionContext
? Is it possible at all? If it's not possible - why it is so? -
Arkadiusz Kałkus almost 8 yearsNot exactly, but close enough ;).
-
Arkadiusz Kałkus over 7 years@Ryan As far as I remember it's all about browsing in a debugger result of GetCookies method executed without any arguments. There should be some arrays and it's relatively straightforward to figure it out how to get the cookies.
-
BornToCode almost 7 years@Ryan - I think the missing piece is this: if for example your cookie has a username=myUserName so you'd need to add a line after what Prasanjit wrote -
string username = cookie.Cookies.Where(c => c.Name == "username").FirstOrDefault().Value;
to extract myUserName -
Vojta Jemelka over 6 years
var cookie = actionContext.Request.Headers.GetCookies("Bar").FirstOrDefault()?["Bar"];
-
RredCat about 6 yearsWhat is a reason that you need to specify "Bar" twice?
-
RredCat about 6 yearsWhat is a reason that you need to specify "Bar" twice?
-
Megha Jaiswal about 5 yearsfirst check indicates whether the required cookie itself is present or not. second code helps in retrieving the value for further processing.