当一个无效或未知的用户想要访问应用程序时,您应该做的是使管道短路。你可以用
middleware
或者通过向授权组件添加过滤器。
最简单的方法可能是使用
Claim-based authorization
为此。您只需要添加一个寻找索赔存在的保险单。
客户端的启动可能如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
// this sets up a default authorization policy for the application
// in this case, authenticated users are required
// (besides controllers/actions that have [AllowAnonymous])
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.RequireClaim("http://mynewapp.com/pilot-tester")
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.GetClaimsFromUserInfoEndpoint = true;
options.ClaimActions.MapAll();
options.Scope.Add("mynewapp");
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "mvc";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
});
}
这将只授予飞行员测试人员访问权限。请注意,所有代码
AllowAnonymous
属性已被使用,仍将对所有人可用!
如果要阻止访问这些方法,则需要使用代码检查用户,例如:
if (User.Identity.IsAuthenticated &&
!User.HasClaim(c => c.Type == "http://mynewapp.com/pilot-tester"))
return Redirect("...");
如何配置IdentityServer:
如果你的应用只是一个没有其他API的网站,那么你需要将声明添加到身份中。
在数据库中,确保添加了以下记录(这些值是示例):
aspnetuserclaims-为每个作为试点测试人员的用户添加一个声明。类型应该是可用于筛选的类型,例如
http://mynewapp.com/pilot-tester
价值
true
.
相同资源-
mynewapp
. 与请求的作用域相对应。
身份声明-
http://mynewapp.com/pilot-tester
(链接到IdentityResource)
MyNeAPP
)
如何运作:
用户是具有声明的资源。为了保持令牌较小,声明被作为请求范围的一部分的声明过滤:openid、profile和mynewapp。
所有按类型匹配的声明都包含在user.identity.claims集合中,该集合在测试策略时使用。
如果您使用的是API,那么您也应该保护该资源。向APIResources添加记录
Api1
. 客户端应用程序应请求范围:
options.Scope.Add("api1");
请注意,在这种情况下,APIResource和APIScope具有相同的名称。但APIResource和APIScope之间的关系是1:N。
将记录添加到apiclaims表(或apiscope以缩小其范围):
APICLALIMS
http://mynewapp.com/pilot-tester
(链接到APIResource
API1
)
用户资源保持不变,但现在IdentityServer也将向访问令牌添加声明。
在API中注册策略
和上面一样。
作为临时用户,您可能希望使过滤器具有条件,从而为您提供启用/禁用过滤器的选项。
但是你可能根本不需要编码。在代理之后意味着您可以首先查看那里的过滤器选项。您可能需要筛选IP地址。这意味着您可以从特定IP地址授予每个人访问权限,而无需更改应用程序。