我正在练习使用asp.net webapi,并希望创建一个独立的授权服务。
因此,我基于令牌(owin)和数据提供程序服务实现了授权服务。现在,我想覆盖数据提供程序服务中的Authorize属性。它必须从当前请求获取Bearer令牌,向授权服务发送请求,接收有关用户及其角色的信息。
问题是:如何在自定义属性中获取Bearer令牌,而且可能有更好的方法来进行这种“令牌传递”?
我希望像这样使用它:
//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;
}