我正在编写一个示例文件存储系统(仅用于 stackoverflow 的示例)。
我当前的域模型如下所示:
public class User
{
public int ID { get; set; }
public string LoginIdentifier { get; set; }
public string Password { get; set; }
}
public class File
{
public int ID { get; set; }
public int UserID { get; set; }
public string FileName { get; set; }
public byte[] Data { get; set; }
}
我正在编写的创建 IPrincipal 的代码:
private static IPrincipal CreatePrincipal(User user)
{
Debug.Assert(user != null);
var identity = new GenericIdentity(user.LoginIdentifier, "Basic");
// TODO: add claims
identity.AddClaim(new Claim("Files", "Add"));
return new GenericPrincipal(identity, new[] { "User" });
}
在我的系统中,用户可以添加文件,也可以检索、删除和更新文件,但是需要注意的是用户只能检索和修改自己的文件(其中File.UserID
应与登录用户的身份匹配) .
我的文件控制器如下所示。
[Authorize]
public class FilesController : ApiController
{
private readonly FileRepository _fileRepository = new FileRepository();
public void Post(File file)
{
// not sure what to do here (...pseudo code...)
if (!CheckClaim("Files", "Add"))
{
throw new HttpError(HttpStatusCode.Forbidden);
}
// ... add the file
file.UserID = CurrentPrincipal.UserID; // more pseudo code...
_fileRepository.Add(file);
}
public File Get(int id)
{
var file = _fileRepository.Get(id);
// not sure what to do here (...pseudo code...)
if (!CheckClaim("UserID", file.UserID))
{
throw new HttpError(HttpStatusCode.Forbidden);
}
return file;
}
}
也许使用Claim
s 不是适合这项工作的工具,但希望这能说明问题。
我应该如何连接我的控制器以确保当前登录的用户有权执行特定操作,更具体地说,某些资源?