【发布时间】:2018-04-30 15:36:51
【问题描述】:
我在练习asp.net webapi,想做独立的授权服务。
所以我实现了基于令牌(owin)的授权服务和数据提供者服务。现在我想覆盖数据提供者服务中的 Authorize 属性。它必须从当前请求中获取不记名令牌,向授权服务发出请求,接收有关用户及其角色的信息。
问题是:如何在我的自定义属性中获取不记名令牌,也许有更好的方法来进行这种“令牌转移”?
我想这样使用它:
//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;
}
【问题讨论】:
-
你看过这个吗? stackoverflow.com/questions/12629530/… Bearer 令牌应与客户端一起存储,并与每个请求一起发送给数据提供者。
-
“自定义属性”是什么意思?
-
我的意思是 System.Web.Mvc.AuthorizeAttribute 具有重写方法 OnAuthorization(AuthorizationContext context)
标签: c# asp.net-web-api2