c#自定义授权与Web API
本文关键字:API Web 授权与 自定义 | 更新日期: 2023-09-27 17:50:48
我正在设计一个WebAPI项目,我的第一个控制器是LoginController。用户登录如下:
[ActionName("Login")]
[AcceptVerbs("PUT")]
[HttpPost]
public HttpResponseMessage Login(DTO.LoginDetails loginDetails)
{
HttpResponseMessage response = null;
DTO.User user = null;
try
{
string connectionString = string.Empty;
//Login the user
user = Mapper.Map<DTO.User>(loginService.Login(loginDetails.Username,
Md5.Encrypt(loginDetails.Password));
if (user != null)
{
//Create session for the user
DTO.Session session = new DTO.Session()
{
User = user,
Token = Guid.NewGuid().ToString()
};
//Create collection to store the cookie values
var nv = new NameValueCollection(3);
nv[SessionHandler.UserId] = user.Id.ToString();
//Create a cookie
var cookie = new CookieHeaderValue(SessionHandler.Session, nv)
{
Expires = DateTimeOffset.Now.AddDays(1),
Domain = Request.RequestUri.Host,
Path = "/"
};
response = Request.CreateResponse<DTO.Session>(HttpStatusCode.OK, session);
response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
}
//Login failed
else
{
response = Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("User or connectionstring is null or empty"));
}
}
}
catch (Exception ex)
{
response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
logService.Logger().Error("Login failed", ex);
}
return response;
}
我也有一个DelegatingHandler从每个请求中获取上述cookie。目前它只从请求中获取cookie。
用户存储在数据库表中,并根据该表对其进行验证。表中的每个用户都有4个显式权限(CRUD)来确定他是否可以对实体(客户、产品等)执行操作。
我的问题是:
成功登录后将用户存储在MemoryCache中,以便我避免往返数据库以验证用户是否已经过身份验证,这是一个好主意吗?
如何使用自定义授权属性来确保用户有权对实体执行操作?该代码应该在控制器级别还是服务级别?
Login控制器使用[AllowAnonymous]装饰,而所有其他控制器都没有。然而,我的DelegatingHandler是系统范围的。我是否应该将我的控制器移到它们自己的区域,而将登录控制器留在主区域?
- 确定。这是一个好主意,让用户缓存和获取用户从缓存,如果错过了,然后从数据库(通过键存储在cookie和数据库-像LastSessionId)。
-
最好您的User(或您的代码中的Session)类派生自GenericPrincipal接口并覆盖/添加一些代码来管理角色集合。所以IsInRole方法将为你工作(由AuthorizeAttribute使用)。IUserPrincipal是您自己添加所需行为/数据的接口。所以不管它是不是自定义属性它都会在控制器级别正常工作
class UserPrincipal : GenericPrincipal, IUserPrincipal