/// <summary> /// 保存刷新Token信息 /// </summary> /// <param name="tokenInfo">Token信息</param> /// <returns></returns> public async virtual Task <bool> SaveToken(RefreshTokenInfo tokenInfo) { TClientRefreshToken token = new TClientRefreshToken() { Value = tokenInfo.Value, ProtectedTicket = tokenInfo.ProtectedTicket, IssuedUtc = tokenInfo.IssuedUtc, ExpiresUtc = tokenInfo.ExpiresUtc }; TClient client = (await ClientRepository.GetByPredicateAsync(m => m.ClientId == tokenInfo.ClientId)).FirstOrDefault(); if (client == null) { return(false); } token.Client = client; TUser user = (await UserRepository.GetByPredicateAsync(m => m.UserName == tokenInfo.UserName)).FirstOrDefault(); if (user == null) { return(false); } token.User = user; int result = await ClientRefreshTokenRepository.InsertAsync(token); return(result > 0); }
/// <summary> /// 创建RefreshToken,在客户端请求AccessToken的时候自动调用 /// </summary> /// <param name="context"></param> public async override Task CreateAsync(AuthenticationTokenCreateContext context) { string clientId = context.Ticket.Properties.Dictionary["as:client_id"]; if (string.IsNullOrEmpty(clientId)) { return; } DateTime now = DateTime.UtcNow; string userName = context.Ticket.Identity.Name; if (clientId == userName) { return; } RefreshTokenInfo tokenInfo = new RefreshTokenInfo() { Value = Guid.NewGuid().ToString("N"), IssuedUtc = now, ExpiresUtc = now.AddDays(30), UserName = userName, ClientId = clientId }; context.Ticket.Properties.IssuedUtc = tokenInfo.IssuedUtc; context.Ticket.Properties.ExpiresUtc = tokenInfo.ExpiresUtc; tokenInfo.ProtectedTicket = context.SerializeTicket(); if (await _clientRefreshTokenStore.SaveToken(tokenInfo)) { context.SetToken(tokenInfo.Value); } }
/// <summary> /// 移除RefreshToken,在客户端使用RefreshToken请求新的AccessToken的时候自动调用 /// </summary> /// <param name="context"></param> public async override Task ReceiveAsync(AuthenticationTokenReceiveContext context) { RefreshTokenInfo token = await _clientRefreshTokenStore.GetTokenInfo(context.Token); if (token == null) { return; } context.DeserializeTicket(token.ProtectedTicket); await _clientRefreshTokenStore.Remove(context.Token); }