Zapnologica
Zapnologica

Reputation: 22556

Pass a variable from a Custom Filter to controller action method

I have a Web Api project.

I have implemented a custom Authentication Attribute like so:

public class TokenAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        // In auth web method you should implement functionality of authentication
        // so that client app could be able to get token
        if (actionContext.Request.RequestUri.AbsolutePath.Contains("api/auth/login"))
        {
            return;
        }

        // Receive token from the client. Here is the example when token is in header:
        var token = HttpContext.Current.Request.Headers["Token"];

        // Put your secret key into the configuration
        var secretKey = ConfigurationManager.AppSettings["JWTSecurityKey"];

        try
        {
            string jsonPayload = JWT.JsonWebToken.Decode(token, secretKey);

            int separatorIndex = jsonPayload.IndexOf(';');

            string userId = "";
            DateTime timeIssued = DateTime.MinValue;

            if (separatorIndex >= 0)
            {
                //userId = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(jsonPayload.Substring(0, separatorIndex)));
                userId = jsonPayload.Substring(0, separatorIndex);
                timeIssued = DateTime.Parse(jsonPayload.Substring(separatorIndex + 1));
            }

            short TokenTTL = 10;
            //try{
            //Int16.TryParse(ConfigurationManager.AppSettings["TokenTTL"],TokenTTL);
            //}catch(Exception e){           //}

            if ((DateTime.Now.Subtract(timeIssued).TotalMinutes >= TokenTTL))
            {
                throw new HttpResponseException(HttpStatusCode.Forbidden);
            }

            //Save user in context                
            var claims = new List<Claim>()
              {
                   new Claim(ClaimTypes.Name, userId)
              };
            var id = new ClaimsIdentity(claims, "Basic");
            var principal = new ClaimsPrincipal(new[] { id });

            actionContext.Request.GetRequestContext().Principal = principal;

        }
        catch (JWT.SignatureVerificationException)
        {
            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        }
    }
}

Now how do I get hold of that user in my actionmethod?

[BasicHttpAuthorizeAttribute]
[httpGet]
public void Login()
{
 // how do i get user here
}

Upvotes: 2

Views: 2120

Answers (1)

/////// Save the string username to the context so that I can acess it in the controler.

var claims = new List<Claim>()
{
    new Claim(ClaimTypes.Name, "john")
};
var id = new ClaimsIdentity(claims, "Basic");
var principal = new ClaimsPrincipal(new[] { id });
actionContext.Request.GetRequestContext().Principal = principal;

// how do i get user here

var name = User.Identity.Name;

BTW, use an authentication filter instead of an authorization filter to perform authentication. See my blog post - http://lbadri.wordpress.com/2014/02/13/basic-authentication-with-asp-net-web-api-using-authentication-filter/.

Upvotes: 2

Related Questions