Reputation: 2393
So my use case is the following: I have created a custom Authorize attribute, which I use only on some specific actions and it works fine for me.
Now when someone is successfully authorized, I want to pass some parameters from the CustomAuthorizeAttribute to the called action. I get those parameters from the token, so they got to the authorize attribute securely.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
// authorizes successfully
}
}
My initial idea was to 'hook' the parameters to HttpContext as headers, but I believe this isn't a secure way to transfer them at all.
Is there a way to transfer them, without the need to encrypt and then decrypt them in the action?
[HttpPost]
[CustomAuthorize]
public async Task<IHttpActionResult> Post()
Upvotes: 1
Views: 139
Reputation: 2071
You might be able to create your own Principal type, which implements IPrincipal
, or extend an existing principal type, like ClaimsPrincipal
.
Then in your CustomAuthorizationAttribute
code, you can set your properties from the decrypted token. Once back in the controller you should be able to access the principal, and retrieve those values which you have set.
References: IPrincipal, Claims Principal
Pseudo code, based loosely on ClaimsPrincipal as I have used that before.
public class CustomPrincipal : ClaimsPrincipal
{
public CustomPrincipal(IEnumerable<ClaimsIdentity> identities, string phone)
: base(identities)
{
this.PhoneNumber = phone;
}
// My properties that I need.
public string PhoneNumber { get; }
}
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
... other code ...
context.Principal = new CustomPrincipal( <stuff to set> );
}
}
Then in your controller actions which are authorized:
CustomPrincipal principal = this.RequestContext.Principal as CustomPrincipal;
... use principal.PhoneNumber etc ...
Upvotes: 1