我不会“删除”授权。假设您有一个客户,并且 CustomerId 是一个声明,那么您无法测试代码,因为缺少声明。相反,我会选择添加一个身份用于开发目的。
这可能是一个黑客,但我的策略是添加一个过滤器,其中设置当前用户,包括所需的角色:
using System.Security.Principal;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
public class AddIdentityFilter : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity("John"), new[] { "Admin" });
base.OnAuthorization(actionContext);
}
}
在 WebApiConfig.cs 中添加过滤器:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.SuppressDefaultHostAuthentication();
// Add some logic here to determine the environment
var isDevelopment = true;
if (isDevelopment)
config.Filters.Add(new AddIdentityFilter());
// ...
}
这样您就可以在开发时定义多个测试场景。
这是一个类似的方法ASP.NET核心3.0应用程序。在启动.配置中:
if (env.IsDevelopment())
{
// Custom authentication
app.Use(async (context, next) =>
{
// Set claims for the test user.
var claims = new[] { new Claim("role", "Admin"), new Claim("sub", "some guid") };
var id = new ClaimsIdentity(claims, "DebugAuthorizationMiddleware", "name", "role");
// Add the test user as Identity.
context.User.AddIdentity(id);
// User is now authenticated.
await next.Invoke();
});
}
else
{
// use configured authentication
app.UseAuthentication();
}
app.UseAuthorization();