ABP-VNext 用户权限管理系统实战05----扩展授权类型(单点登录)

 一、适合场景:

1、我方系统在集成到别人的集成本台时一般是拿别的平台的用户名,在我方系统进行登录

2、我方系统是前后端分离,前端要拿到token

 

二、解决方案:自定义授权类型

我们知道Identityserver4有四种授权类型:用户名密码授权不适合单点登录,因为拿不到密码;其它类型也不适合,因为拿不到用户信息。

1、继承IExtensionGrantValidator接口

public class UserNameGrantValidator : IExtensionGrantValidator
{
public string GrantType => "username";
//1q2w3e* 进行sha256编码后结果
public string ClientSecret => "E5Xd4yMqjP5kjWFKrYgySBju6JVfCzMyFp7n2QmMrME=";
private readonly UserManager<Volo.Abp.Identity.IdentityUser> _usermanager;
private readonly IdentityUserManager _identityUserManager;
private readonly IConfiguration _configuration;
public UserNameGrantValidator(UserManager<Volo.Abp.Identity.IdentityUser> usermanager, IdentityUserManager identityUserManager, IConfiguration configuration)
{
_configuration = configuration;
_usermanager = usermanager;
this._identityUserManager = identityUserManager;
}
public Task ValidateAsync(ExtensionGrantValidationContext context)
{
var username = context.Request.Raw.Get("username");
var auth_code = context.Request.Raw.Get("client_key");
var authcodeconfig = _configuration["ClientAuthKey"];
if (string.IsNullOrEmpty(auth_code) || string.IsNullOrEmpty(authcodeconfig) || auth_code != authcodeconfig.Sha256())
{
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "客户端授权码无效");
return Task.FromResult(1);
}
//var user = _userRepository.FirstOrDefaultAsync(x => x.Name == username);
var user = _usermanager.FindByNameAsync(username).Result;
if (user == null)
{
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "用户未注册");
return Task.FromResult(1);

}

//var claims = new List<Claim>();
//foreach (var itemClaim in user.Result.Claims)
//{
// var claim = new Claim(itemClaim.ClaimType, itemClaim.ClaimValue);
// claims.Add(claim);
//}

context.Result = new GrantValidationResult(
subject: user.Id.ToString(),
authenticationMethod: GrantType);
return Task.FromResult(0);
}
}

2、在AuthServerDataSeeder.cs文件中增加授权客户端

 

3、注入授权类型

在AuthServerHostModule.cs类下增加方法:

 public override void PreConfigureServices(ServiceConfigurationContext context)
 {
     context.Services.PreConfigure<IIdentityServerBuilder>(builder =>
     {
         builder.AddExtensionGrantValidator<UserNameGrantValidator>();
     });
 }

4、postman请求并拿到access_token

 

posted @ 2023-11-22 15:19  爱生活,爱代码  阅读(341)  评论(0编辑  收藏  举报