4

I am creating a MVC Web API application with forms authentication for the Web API Controllers as well as the regular MVC controllers. In the form authentication cookie I am storing user information which I need to read and pass it to the Web API action methods. I am trying to do this by creating a custom Authorization attribute and adding this value to ActionArguments. However I don't know how to access this data in the Web API action. Below is the code block

public class MyAuthorization : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var isAuthorised = base.IsAuthorized(actionContext);

            if (isAuthorised)
            {
                var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                var ticket = FormsAuthentication.Decrypt(cookie.Value);
                var identity = new GenericIdentity(ticket.Name);
                actionContext.ActionArguments["UserInfo"] = ticket.UserData;

            }
        }
    }

And here is the controller code

[RoutePrefix("api/test")]
    [MyAuthorization]
    public class TestWebAPIController : ApiController
    {
        [HttpGet]
        [Route("")]       
        public IHttpActionResult Get() {
            //How to get it here
            return Ok();
        }
    }

1 Answer 1

2

It was really stupid of me. As the name suggests it is the ActionArgument (actionContext.ActionArguments). So this can be easily accessed in the Web API control by means of an ActionContext.ActionArguments or directly by passing an action argument.

Here is code sample by ActionContext.ActionArguments

public IHttpActionResult Post() {
            var userInfo = ActionContext.ActionArguments["UserInfo"];
            return Ok();
        }

And here is by means of action argument

  public IHttpActionResult Post(UserInfo userinfo) {
       //Code here
        return Ok();
     }
Sign up to request clarification or add additional context in comments.

1 Comment

hi, it possible to add the company/tenant name as well for a multitenant app. I am wondering if this is the same information the http context provides when checking authorization

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.