我有这个测试客户端发送RequestToken:
var tokenResponse = await client.RequestTokenAsync(new TokenRequest
{
Address = disco.TokenEndpoint,
GrantType = "password",
ClientId = "My_Client",
ClientSecret = "mysecret",
Parameters =
{
{ "username", "user@entity.com" },
{ "password", "userpassword" },
{ "logged_entity_id", "143" },
{ "scope", "MyAPI" }
}
});
现在每个用户都有一个实体列表,并且如果用户的实体列表中不存在参数“ logged_entity_id”中的值,我想拒绝令牌请求。
我最初计划在CustomProfileService中通过IsActiveSync对其进行检查,但似乎无法访问IsActiveSync方法中的原始参数。
public class CustomProfileService : IProfileService
{
protected UserManager<User> _userManager;
public CustomProfileService(UserManager<User> userManager)
{
_userManager = userManager;
}
public Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var claims = new List<Claim>
{
new Claim("LoggedEntityId", context.ValidatedRequest.Raw["logged_entity_id"])
};
context.IssuedClaims.AddRange(claims);
return Task.FromResult(0);
}
public Task IsActiveAsync(IsActiveContext context)
{
var user = _userManager.GetUserAsync(context.Subject).Result;
// var entityId = Can't access logged_entity_id parameter here
context.IsActive = user != null && user.DeletingDate == null && user.entities.Contains(entityId);
return Task.FromResult(0);
}
}
我不太确定这是我应该检查并拒绝的地方。
答案 0 :(得分:1)
在asp.net核心中,您可以使用内置的依赖项注入容器注册依赖项。依赖项注入容器将IHttpContextAccessor
提供给在其构造函数中将其声明为依赖项的任何类:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddHttpContextAccessor();
...
}
然后在您的课程中,例如在IProfileService
的实现中:
private readonly IHttpContextAccessor _httpContextAccessor;
public CustomProfileService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
然后在IsActiveAsync方法中通过以下方式获取值:
var id = _httpContextAccessor.HttpContext.Request.Form["logged_entity_id"].ToString();
答案 1 :(得分:0)
您可以实施ICustomTokenValidator来以自己的方式验证令牌的请求
您可以在令牌端点上将自定义代码作为令牌发行管道的一部分运行。这允许例如为
添加其他验证逻辑
动态更改某些参数(例如令牌寿命)
public class CustomValidator : ICustomTokenRequestValidator
{
public Task<TokenValidationResult> ValidateAccessTokenAsync(TokenValidationResult result)
{
throw new NotImplementedException();
}
public Task<TokenValidationResult> ValidateIdentityTokenAsync(TokenValidationResult result)
{
throw new NotImplementedException();
}
}
并在您的startup.cs中:
services.AddIdentityServer(options =>
{
...
})
.AddCustomTokenRequestValidator<CustomValidator>();