在 WebAPI .net 核心项目中,我创建了一个验证 api 密钥的中间件类。通过验证它,它检索密钥在 invoke 方法中拥有的权限(用户或管理员)。
我通过一个开关来设置原理
GenericIdentity identity = new GenericIdentity("API");
GenericPrincipal principle = null;
//we have a valid api key, so set the role permissions of the key
switch (keyValidatorRes.Role)
{
case Roles.User:
principle = new GenericPrincipal(identity, new[] { "User" });
context.User = principle;
break;
case Roles.Admin:
principle = new GenericPrincipal(identity, new[] { "Admin" });
context.User = principle;
break;
default:
principle = new GenericPrincipal(identity, new[] { "Other" });
context.User = principle;
break;
}
Run Code Online (Sandbox Code Playgroud)
在控制器方法上我有
[Authorize(Roles = …