abp vnext token

前言:abp版本是4.2,没想到第一步就遇到了难题,那就是token,网上查找资料,

说通过connect/token获取,原文链接:https://blog.csdn.net/liuyonghong159632/article/details/112301317#comments_14518263,

经过我翻天掘地的测试,失败告终。

从长计议后,放弃探索框架自带的token,自己写,当我还没写到解析,竟然连通了,我知道,abp终于把core3的问题完善了,

目前先自定义生成token,也许有人好奇,不是本来那个account/login,不就解决登录问题了么,

首先,我是抛弃session的流派,再次,我必须用我自己写的权限以及本地化,那么开始吧

 

1.搭建jwt的环境,地址:https://mp.weixin.qq.com/s/ZOX9D4ncqqeXxipYapTeBA,这里我没有用外部登录,正常来说,这个链接,完全解决了问题,

但是,我之所以抛弃core3,一个重要的因素就是多租户问题,我发现core3不管如何配置和解析都无法自动处理多租户,最后没办法,我采用了自己解析保存,

一直到响应、仓储都是自己写

2.在4.2中,我直接只需要写好token,多租户自动解析,以下是生成token的代码,

为了测试方便,我直接写死了token值

 1         /// <summary>
 2         /// 根据登录信息获取Token
 3         /// </summary>  
 4         /// <param name="username">登录名</param>
 5         /// <param name="password">密码</param>
 6         /// <returns>Token</returns>
 7         public async Task<ServiceResult<string>> GetTokenByLoginInfo(string username, string password)
 8          {
 9             var result = new ServiceResult<string>();
10 
11             if (string.IsNullOrEmpty(username))
12             {
13                 result.IsFailed("登录名不得为空!");
14                 return result;
15             }    
16             else if (string.IsNullOrEmpty(password))
17             {
18                 result.IsFailed("密码不得为空!");
19                 return result;
20             }
21             // AuthenticationStatus认证状态:(默认值)0代表未认证,1代表认证通过,2代表认证不通过
22             //// DelFlag删除状态:(默认值)0代表未删除,1代表已删除
23             //var jwtUser = await _JWTUserRepository.FindAsync(
24             //    x => x.UserName.Equals(username)
25             //        && x.PassWord.Equals(password)
26             //        && x.AuthenticationStatus == 1);
27             //if (jwtUser == null)
28             //{
29             //    result.IsFailed("登录失败,账号或密码不正确!");
30             //    return result;
31             //}
32             /*
33             if (JWTUser.Id != Pro215UserAPIConfig.UserId)
34             {
35                 result.IsFailed("当前账号未授权");
36                 return result;
37             }*/
38             result.IsSuccess(
39                 CreateJWTToken(
40                     "13F1F1CD-41B6-5C01-AAD4-39FA6ED6441B",
41                     "Com1Admin",
42                     "13F1F1CD-41B6-5C01-AAD4-39FA6ED6441B",
43                     "828BA489-4643-2198-CA0E-39FA6ED64389"));
44             return await Task.FromResult(result);
45         }
46 
47         /// <summary>
48         /// 签发JWT,返回token
49         /// </summary>
50         /// <param name="guid">jwtuser表pkid</param>
51         /// <param name="userName">jwtuser表用户名</param>
52         /// <param name="roleGroupId">jwtuser表权限组id</param>
53         /// <param name="tenantId">jwtuser表租户代码</param>
54         /// <returns></returns>
55         public string CreateJWTToken(string guid, string userName, string roleGroupId, string tenantId)
56         {
57 
58             var claims = new[] {
59                     new Claim(ClaimTypes.NameIdentifier, guid),
60                     new Claim(AbpClaimTypes.UserId, guid),
61                     new Claim(AbpClaimTypes.UserName, userName),
62                     new Claim(ClaimTypes.Name, userName),
63                     new Claim(ClaimTypes.Role, roleGroupId),
64                     new Claim(AbpClaimTypes.TenantId, tenantId),
65                     new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddMinutes(1800)).ToUnixTimeSeconds()}"),
66                     new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}")
67                 };
68 
69             var key = new SymmetricSecurityKey(AppSettings.JWT.SecurityKey.GetBytes());
70             var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
71 
72             var securityToken = new JwtSecurityToken(
73                 issuer: AppSettings.JWT.Domain,
74                 audience: AppSettings.JWT.Domain,
75                 claims: claims,
76                 expires: DateTime.Now.AddMinutes(AppSettings.JWT.Expires),
77                 signingCredentials: creds);
78 
79             var token = new JwtSecurityTokenHandler().WriteToken(securityToken);
80             return token;
81         }

2.获取到token后,测试下效果,记得controller添加属性[Authorize],贴上application逻辑代码,我是用官方的写的demo测试的,这里的CurrentTenant与CurrentUser我就是为了测试切换租户与用户,跳权限操作之类的

 1     public class BookAppService :
 2          CrudAppService<
 3              Book, //The Book entity
 4              BookDto, //Used to show books
 5              Guid, //Primary key of the book entity
 6              PagedAndSortedResultRequestDto, //Used for paging/sorting
 7              CreateUpdateBookDto>, //Used to create/update a book
 8          IBookAppService //implement the IBookAppService
 9     {
10         private readonly BookAppCacheService _bookAppCacheService;
11         private readonly ICurrentTenant _currentTenant;
12         private readonly ICurrentUser _currentUser;
13         public BookAppService(IRepository<Book, Guid> repository,
14             BookAppCacheService bookAppCacheService,
15              ICurrentTenant _ICurrentTenant
16             , ICurrentUser currentUser)
17             : base(repository)
18         {
19             _bookAppCacheService = bookAppCacheService;
20             _currentTenant = _ICurrentTenant;
21             _currentUser = currentUser;
22 
23         }
24         public Task<BookDto> CreateAsync11(CreateUpdateBookDto input)
25         {
26             //1.逻辑中判断权限,手动抛出或者截停逻辑代码
27             /*
28                 var result = await AuthorizationService
29                     .AuthorizeAsync("Book_Author_Create");
30                 if (result.Succeeded == false)
31                 {
32                     //throw exception
33                     throw new AbpAuthorizationException("...");
34                 }
35 
36              */
37             /* 2.可以不使用但推荐用[Authorize("Book")]的方式,在代码中主动检查
38              * 如果未授权 CheckAsync 扩展方法会抛出 AbpAuthorizationException 异常. 
39              * 还有一个 IsGrantedAsync 扩展方法会返回 true 或 false.
40              * IAuthorizationService 中有多个 AuthorizeAsync 方法重载. 
41              * ASP.NET Core 授权文档中有详细的解释.
42              * 提示: 尽可能使用声明式的 Authorize attribute,因为它比较简单不会侵入方法内部. 
43              * 如果你需要在业务代码中有条件的检查权限,那么请使用 IAuthorizationService.
44              * 示例:await AuthorizationService.CheckAsync("Author_Management_Create_Books");
45             */
46             return base.CreateAsync(input);
47         }
48         /// <summary>
49         /// (缓存)获取书本分页数据
50         /// </summary>
51         /// <param name="input">查询条件</param>
52         /// <returns></returns>
53         public async Task<PagedResultDto<BookDto>> GetListCacheAsync(PagedAndSortedResultRequestDto input)
54         {
55             return await _bookAppCacheService.GetListCacheAsync(input, () =>
56             {
57                 return base.GetListAsync(input);
58             });
59         }
60 
61     }

3.看看数据库的数据,

 

posted @ 2021-02-08 11:32  0Behavior  阅读(1847)  评论(0编辑  收藏  举报