I'm practicing with asp.net webapi, and want to make separated authorization service.
So I implement authorization service based on tokens (owin), and data provider service. Now I want to override Authorize attribute in data provider service. It must take bearer token from current request, make request to authorization service, receive information about user and his roles.
The question is: how I can get bearer token in my custom attribute, and maybe there are better ways to make this "token transfer"?
I want to use it like this:
//data service
[CustomAttribute (Roles = "admin")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
public class CustomAttribute : System.Web.Mvc.AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext context)
{
using (WebClient client = new WebClient())
{
string bearerToken;
//somehow get token
client.Headers.Add("Authorization", "Bearer " + bearerToken);
string userinfo = client.DownloadString("authURL/GetUserInfo");
CustomUser user = JsonConvert.DeserializeObject<CustomUser>(userinfo);
if (!user.Roles == this.Roles)
{
//return 401
}
}
}
}
// authorization service
public async Task<UserInfoResponse> GetUserInfo()
{
var owinContext = HttpContext.Current.GetOwinContext();
int userId = owinContext.Authentication.User.Identity.GetUserId<int>();
var response = new UserInfoResponse()
{
UserId = userId.ToString(),
Roles = await UserManager.GetRolesAsync(userId)
};
return response;
}