Mat*_*hew 7 .net authentication authorization claims-based-identity asp.net-web-api
我正在编写一个示例文件存储系统(仅用于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; }
}
Run Code Online (Sandbox Code Playgroud)
我写的代码是为了创建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" });
}
Run Code Online (Sandbox Code Playgroud)
在我的系统中,用户可以添加文件,他们也可以检索,删除和更新文件,但是,需要注意的是用户只能检索和修改自己的文件(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;
}
}
Run Code Online (Sandbox Code Playgroud)
也许使用Claims不是工作的正确工具,但希望这说明了问题.
我应该如何连接我的控制器以确保当前登录的用户有权访问特定的操作,更具体地说,某些资源?
我不确定索赔是否是您正在做的事情的正确方法.你真正想要表示的是权限.声明通常表示身份属性,例如用户名,电子邮件或其所属的角色,但不表示权限.您可以使用声明来表示权限,但根据应用程序的大小,您可能需要大量权限.一种典型的方法是将角色映射到一组权限(在您的情况下,添加文件将是一种权限).您还可以创建从AuthorizeAttribute派生的自定义授权过滤器,以检查当前主体是否具有执行操作的正确权限.该过滤器可能会获得执行操作作为参数所需的权限.
巴勃罗是对的 - 声称描述身份.您使用该身份来做出授权决定.有一个名为ClaimsAuthorizationManager的独立抽象.
看看这里:http: //leastprivilege.com/2012/10/26/using-claims-based-authorization-in-mvc-and-web-api/
| 归档时间: |
|
| 查看次数: |
3173 次 |
| 最近记录: |