public async void GetRefreshTokenByUserIdWithWrongId() { string id = "id"; RefreshTokenService refreshService = new RefreshTokenService(_repo); var result = await refreshService.GetRefreshTokenByUserId(id); Assert.Null(result); }
public RecordCacheHelper(IPageDialogService dialogService, SystemEnvironmentsService systemEnvironmentsService, SystemStatusService systemStatusService, AppStatus appStatus, RefreshTokenService refreshTokenService) { this.dialogService = dialogService; this.systemEnvironmentsService = systemEnvironmentsService; this.systemStatusService = systemStatusService; this.appStatus = appStatus; this.refreshTokenService = refreshTokenService; }
public async Task <IActionResult> Logout([FromBody] ActionLogout data) { if (data.token == null || data.token == "") { return(NoContent()); } await RefreshTokenService.RevokeToken(data.token); return(Ok()); }
public RefreshTokenCommandHandler( IUowGeneral uowGeneral, IAccessTokenService accessTokenService, RefreshTokenService refreshTokenService ) { _uowGeneral = uowGeneral; _accessTokenService = accessTokenService; _refreshTokenService = refreshTokenService; }
public LoginUserCommandHandler( IUowGeneral uowGeneral, IPasswordService passwordService, IAccessTokenService accessTokenService, RefreshTokenService refreshTokenService) { _uowGeneral = uowGeneral; _passwordService = passwordService; _accessTokenService = accessTokenService; _refreshTokenService = refreshTokenService; }
public async void DeleteRefreshTokenWithWrongToken() { string token = "token"; _repo.DeleteRefreshToken(token).Returns(false); RefreshTokenService refreshService = new RefreshTokenService(_repo); var result = await refreshService.DeleteRefreshToken(token); Assert.False(result); }
public async void DeleteRefreshTokenWithRightToken() { string token = "token"; _repo.DeleteRefreshToken(token).Returns(true); RefreshTokenService refreshService = new RefreshTokenService(_repo); var result = await refreshService.DeleteRefreshToken(token); Assert.True(result); }
public LogoutCleanHelper(IPageDialogService dialogService, SystemEnvironmentsService systemEnvironmentsService, SystemStatusService systemStatusService, AppStatus appStatus, RefreshTokenService refreshTokenService, ExceptionRecordsService exceptionRecordsService, AppExceptionsService appExceptionsService) { this.dialogService = dialogService; this.systemEnvironmentsService = systemEnvironmentsService; this.systemStatusService = systemStatusService; this.appStatus = appStatus; this.refreshTokenService = refreshTokenService; this.exceptionRecordsService = exceptionRecordsService; this.appExceptionsService = appExceptionsService; }
public AuthController( ILogger logger, IMapper mapper, RefreshTokenService refreshTokenService, JwTokenService jwTokenService, AuthService authService) { _logger = logger; _mapper = mapper; _refreshTokenService = refreshTokenService; _jwTokenService = jwTokenService; _authService = authService; }
public async void CreateRefreshTokenWithNullUserId() { RefreshTokenService refreshService = new RefreshTokenService(_repo); var token = new RefreshToken { TokenValue = "value", UserId = null }; var result = await refreshService.CreateRefreshToken(token); Assert.False(result); }
public async void CreateRefreshTokenWithNonNull() { var token = new RefreshToken { TokenValue = "value", UserId = "userId" }; RefreshTokenService refreshService = new RefreshTokenService(_repo); var result = await refreshService.CreateRefreshToken(token); Assert.True(result); }
public RefreshTokenServiceTests() { _fixture = new Fixture(); _fixture.Behaviors.OfType <ThrowingRecursionBehavior>().ToList() .ForEach(b => _fixture.Behaviors.Remove(b)); _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); _dateTimeProvider = Substitute.For <IDateTimeProvider>(); _refreshTokenFactory = Substitute.For <RefreshTokenFactory>(new Rng(), _dateTimeProvider); _refreshTokenRepository = Substitute.For <IRefreshTokenRepository>(); _jwtHandler = Substitute.For <IJwtHandler>(); _userService = Substitute.For <IUserService>(); _sut = new RefreshTokenService(_refreshTokenRepository, _userService, _refreshTokenFactory, _dateTimeProvider, _jwtHandler); }
public WorkingLogDetailPageViewModel(INavigationService navigationService, IPageDialogService dialogService, WorkingLogDetailService workingLogDetailService, ProjectService projectService, RefreshTokenService refreshTokenService, SystemStatusService systemStatusService, AppStatus appStatus) { this.navigationService = navigationService; this.dialogService = dialogService; this.workingLogDetailService = workingLogDetailService; this.projectService = projectService; this.refreshTokenService = refreshTokenService; this.systemStatusService = systemStatusService; this.appStatus = appStatus; #region 新增紀錄 AddCommand = new DelegateCommand(async() => { NavigationParameters paras = new NavigationParameters(); var fooObject = new WorkingLogDetailDto(); fooObject.WorkingLogId = MasterItem.Id; paras.Add(MagicStringHelper.CurrentSelectdItemParameterName, fooObject); paras.Add(MagicStringHelper.CrudActionName, MagicStringHelper.CrudAddAction); paras.Add(MagicStringHelper.MasterRecordActionName, MasterItem); await navigationService.NavigateAsync("WorkingLogDetailRecordPage", paras); }); #endregion #region 點選某筆紀錄觸發命令 ItemTappedCommand = new DelegateCommand(async() => { NavigationParameters paras = new NavigationParameters(); var fooObject = SelectedItem.Clone(); paras.Add(MagicStringHelper.CurrentSelectdItemParameterName, fooObject); paras.Add(MagicStringHelper.CrudActionName, MagicStringHelper.CrudEditAction); paras.Add(MagicStringHelper.MasterRecordActionName, MasterItem); await navigationService.NavigateAsync("WorkingLogDetailRecordPage", paras); }); #endregion #region 更新遠端紀錄命令 RefreshCommand = new DelegateCommand(async() => { IsRefresh = true; await ReloadData(); IsRefresh = false; }); #endregion }
public IdentityService(IIdentityContext identityContext, ILoggingService loggingService, IUserService userService, ClientService clientService, RefreshTokenService refreshTokenService) { _dbContext = identityContext.GetContext as DbContext; //account _clientService = new ClientService(identityContext); _refreshTokenService = new RefreshTokenService(identityContext); _roleService = new RoleService(new RoleStore <Role>(_dbContext)); _accountService = new AccountService(new UserStore <Account>(_dbContext)); //entity _userService = userService; //logging _loggingService = loggingService; }
public async Task ShouldThrow_InvalidRefreshTokenException_OnNotFoundRefreshToken() { var request = FakeRequest(); var uowGeneralMock = new Mock <IUowGeneral>(); uowGeneralMock.Setup(x => x.RefreshTokenRepository.FindByToken(It.IsAny <string>())) .ReturnsAsync(default(RefreshToken)); var accessTokenService = new Mock <IAccessTokenService>(); var refreshTokenService = new RefreshTokenService(uowGeneralMock.Object); var handler = new RefreshTokenCommandHandler( uowGeneralMock.Object, accessTokenService.Object, refreshTokenService); await Assert.ThrowsAsync <InvalidRefreshTokenException>(() => handler.Handle(request, default)); }
public async Task ShouldThrow_InvalidAccountException_OnNotFoundUser() { var request = FakeRequest(); var uowGeneralMock = new Mock <IUowGeneral>(); uowGeneralMock.Setup(x => x.UserRepository.FindByEmail(request.Email)).ReturnsAsync(default(User)); var passwordServiceMock = new Mock <IPasswordService>(); var accessTokenServiceMock = new Mock <IAccessTokenService>(); var refreshTokenService = new RefreshTokenService(uowGeneralMock.Object); var handler = new LoginUserCommandHandler(uowGeneralMock.Object, passwordServiceMock.Object, accessTokenServiceMock.Object, refreshTokenService); await Assert.ThrowsAsync <InvalidAccountException>(() => handler.Handle(request, default)); }
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context) { var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin"); context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); string refreshTokenId = context.Token; RefreshTokenService refreshTokenService = new RefreshTokenService(); var refreshToken = await refreshTokenService.FindRefreshToken(refreshTokenId); if (refreshToken.Success) { //Get protectedTicket from refreshToken class context.DeserializeTicket(refreshToken.Data.ProtectedTicket); var result = await refreshTokenService.RemoveRefreshToken(refreshToken.Data); } }
public void SetUp() { RefreshToken = "4wjRDjmSi9YfgFYAVM2QWjJxY8w1Ao6U7S6ZWX9VDCQ="; DaysToExpire = 3; AccessToken = "4wjRDjmSi9YfgFYAVM2QWjJxY8w1Ao6U7S6ZWX9VDCQ"; Size = 32; UserId = 91; _userService = new Mock <IUserService>(); _tokenService = new Mock <ITokenService>(); theaterScheduleUnitOfWorkMock = new Mock <ITheaterScheduleUnitOfWork>(); _refreshTokenRepositoryMock = new Mock <IRefreshTokenRepository>(); _refreshTokenService = new RefreshTokenService(_refreshTokenRepositoryMock.Object, _tokenService.Object, _userService.Object, theaterScheduleUnitOfWorkMock.Object); _applicationUserDTO = new ApplicationUserDTO() { Id = 91, FirstName = "Volodya", LastName = "Khydzik", City = "Lviv", Country = "Lviv", Email = "*****@*****.**", PhoneNumber = "0672530997", DateOfBirth = "20.07.2000" }; _refreshTokenDTO = new RefreshTokenDTO() { Id = 1, IsActive = true, UserId = 91, RefreshToken = "4wjRDjmSi9YfgFYAVM2QWjJxY8w1Ao6U7S6ZWX9VDCQ =", DaysToExpire = DateTime.Now.AddDays(3) }; _refreshTokenModel = new RefreshTokenModel() { RefreshToken = "4wjRDjmSi9YfgFYAVM2QWjJxY8w1Ao6U7S6ZWX9VDCQ=" }; _tokenService.Setup(service => service.GenerateAccessToken(_applicationUserDTO, RefreshToken)).Returns(() => { return(AccessToken); }); }
// Based on https://stackoverflow.com/a/44322425/1249506 public async Task <IdentityServerToken> GetIdentityServerTokenForUserAsync(User user) { var request = new TokenCreationRequest(); var identityPricipal = await PrincipalFactory.CreateAsync(user); var identityUser = new IdentityServerUser(user.Id.ToString()) { AdditionalClaims = identityPricipal.Claims.ToArray(), DisplayName = user.UserName, AuthenticationTime = DateTime.UtcNow, IdentityProvider = IdentityServerConstants.LocalIdentityProvider }; request.Subject = identityUser.CreatePrincipal(); request.IncludeAllIdentityClaims = true; request.ValidatedRequest = new ValidatedRequest { Subject = request.Subject, }; var client = await ClientStore.FindClientByIdAsync(ClientId); request.ValidatedRequest.SetClient(client); request.Resources = new Resources(await ResourceStore.FindEnabledIdentityResourcesByScopeAsync(client.AllowedScopes), await ResourceStore.FindApiResourcesByScopeAsync(client.AllowedScopes)) { OfflineAccess = client.AllowOfflineAccess }; request.ValidatedRequest.Options = Options; request.ValidatedRequest.ClientClaims = identityUser.AdditionalClaims; var token = await TokenService.CreateAccessTokenAsync(request); var accessToken = await TokenService.CreateSecurityTokenAsync(token); var refreshToken = await RefreshTokenService.CreateRefreshTokenAsync(request.Subject, token, client); return(new IdentityServerToken(token, accessToken, refreshToken)); }
public async Task ShouldThrow_InvalidAccountException_OnDisabledAccount() { var request = FakeRequest(); var user = new UserFake().Builder .RuleFor(x => x.DisabledAccountAt, f => f.Date.Recent()) .Generate(); var uowGeneralMock = new Mock <IUowGeneral>(); uowGeneralMock.Setup(x => x.UserRepository.FindByEmail(request.Email)).ReturnsAsync(user); var passwordServiceMock = new Mock <IPasswordService>(); var accessTokenServiceMock = new Mock <IAccessTokenService>(); var refreshTokenService = new RefreshTokenService(uowGeneralMock.Object); var handler = new LoginUserCommandHandler(uowGeneralMock.Object, passwordServiceMock.Object, accessTokenServiceMock.Object, refreshTokenService); await Assert.ThrowsAsync <InvalidAccountException>(() => handler.Handle(request, default)); }
public async void GetRefreshTokenByValueWithRightId() { string tokenValue = "tokenValue"; var token = new RefreshToken { TokenValue = tokenValue, UserId = "id" }; _repo.GetRefreshTokenByValue(tokenValue).Returns(token); RefreshTokenService refreshService = new RefreshTokenService(_repo); var result = await refreshService.GetRefreshTokenByValue(tokenValue); Assert.NotNull(result); Assert.IsType <RefreshToken>(result); Assert.NotNull(result.TokenValue); Assert.NotNull(result.UserId); Assert.Equal(result.TokenValue, tokenValue); }
public async Task ShouldThrow_InvalidRefreshTokenException_OnExpiredRefreshToken() { var request = FakeRequest(); var refreshTokenFakeBuilder = new RefreshTokenFake().Builder; refreshTokenFakeBuilder.RuleFor(x => x.ExpiresAt, f => f.Date.Past()); var refreshToken = refreshTokenFakeBuilder.Generate(); var uowGeneralMock = new Mock <IUowGeneral>(); uowGeneralMock.Setup(x => x.RefreshTokenRepository.FindByToken(request.Token)) .ReturnsAsync(refreshToken); var accessTokenService = new Mock <IAccessTokenService>(); var refreshTokenService = new RefreshTokenService(uowGeneralMock.Object); var handler = new RefreshTokenCommandHandler( uowGeneralMock.Object, accessTokenService.Object, refreshTokenService); await Assert.ThrowsAsync <InvalidRefreshTokenException>(() => handler.Handle(request, default)); }
public static async Task <bool> CheckAndRefreshToken(IPageDialogService dialogService, RefreshTokenService refreshTokenService, SystemStatusService systemStatusService, AppStatus appStatus) { if (appStatus.SystemStatus.TokenExpireDatetime > DateTime.Now) { #region Token 尚在有效期限 return(true); #endregion } else { #region Token 已經失效了,需要更新 var fooResult = await refreshTokenService.GetAsync(); if (fooResult.Status != true) { await dialogService.DisplayAlertAsync("發生錯誤", fooResult.Message, "確定"); return(false); } systemStatusService.SingleItem = appStatus.SystemStatus; systemStatusService.SingleItem.IsLogin = true; systemStatusService.SingleItem.LoginedTime = DateTime.Now; systemStatusService.SingleItem.Token = refreshTokenService.SingleItem.Token; systemStatusService.SingleItem.RefreshToken = refreshTokenService.SingleItem.RefreshToken; systemStatusService.SingleItem.TokenExpireMinutes = refreshTokenService.SingleItem.TokenExpireMinutes; systemStatusService.SingleItem.RefreshTokenExpireDays = refreshTokenService.SingleItem.RefreshTokenExpireDays; systemStatusService.SingleItem.SetExpireDatetime(); #endregion } //await systemStatusService.WriteToFileAsync(); await AppStatusHelper.WriteAndUpdateAppStatus(systemStatusService, appStatus); return(true); }
public OnCallPhonePageViewModel(INavigationService navigationService, IPageDialogService dialogService, OnCallPhoneService onCallPhoneService, MyUserService myUserService, RefreshTokenService refreshTokenService, SystemStatusService systemStatusService, AppStatus appStatus) { this.navigationService = navigationService; this.dialogService = dialogService; this.onCallPhoneService = onCallPhoneService; this.myUserService = myUserService; this.refreshTokenService = refreshTokenService; this.systemStatusService = systemStatusService; this.appStatus = appStatus; #region 點選某筆紀錄觸發命令 ItemTappedCommand = new DelegateCommand(async() => { try { PhoneDialer.Open(SelectedItem.PhoneNumber); } catch (Exception ex) { await dialogService.DisplayAlertAsync("錯誤", $"發生例外異常:{ex.Message}", "確定"); } }); #endregion #region 更新遠端紀錄命令 RefreshCommand = new DelegateCommand(async() => { IsRefresh = true; await ReloadData(); IsRefresh = false; }); #endregion }
public TravelExpenseDetailRecordPageViewModel(INavigationService navigationService, IPageDialogService dialogService, TravelExpenseDetailService travelExpenseDetailService, RefreshTokenService refreshTokenService, SystemStatusService systemStatusService, AppStatus appStatus) { this.navigationService = navigationService; this.dialogService = dialogService; this.travelExpenseDetailService = travelExpenseDetailService; this.refreshTokenService = refreshTokenService; this.systemStatusService = systemStatusService; this.appStatus = appStatus; #region 新增 儲存 按鈕命令 SaveCommand = new DelegateCommand(async() => { #region 進行資料完整性檢查 var checkResult = SelectedItem.Validation(); if (!string.IsNullOrEmpty(checkResult)) { await dialogService.DisplayAlertAsync("錯誤", $"請檢查並且修正錯誤{Environment.NewLine}{Environment.NewLine}" + $"{checkResult}", "確定"); return; } #endregion #region 進行記錄儲存 APIResult apiResult = new APIResult(); using (IProgressDialog fooIProgressDialog = UserDialogs.Instance.Loading($"請稍後,儲存資料中...", null, null, true, MaskType.Black)) { await AppStatusHelper.ReadAndUpdateAppStatus(systemStatusService, appStatus); #region 檢查 Access Token 是否還可以使用 bool refreshTokenResult = await RefreshTokenHelper .CheckAndRefreshToken(dialogService, refreshTokenService, systemStatusService, appStatus); if (refreshTokenResult == false) { return; } #endregion if (CrudAction == MagicStringHelper.CrudAddAction) { #region 新增 差旅費用明細紀錄 fooIProgressDialog.Title = "請稍後,新增 差旅費用明細紀錄"; SelectedItem.Id = 0; apiResult = await travelExpenseDetailService.PostAsync(SelectedItem); if (apiResult.Status == true) { ToastHelper.ShowToast($"差旅費用明細紀錄 已經新增"); NavigationParameters paras = new NavigationParameters(); paras.Add(MagicStringHelper.CrudActionName, MagicStringHelper.CrudRefreshAction); await navigationService.GoBackAsync(paras); } else { await dialogService.DisplayAlertAsync("錯誤", $"差旅費用明細紀錄 儲存失敗:{apiResult.Message}", "確定"); } #endregion } else { #region 儲存 差旅費用明細紀錄 fooIProgressDialog.Title = "請稍後,儲存 差旅費用明細紀錄"; apiResult = await travelExpenseDetailService.PutAsync(SelectedItem); if (apiResult.Status == true) { ToastHelper.ShowToast($"差旅費用明細紀錄 已經儲存"); NavigationParameters paras = new NavigationParameters(); paras.Add(MagicStringHelper.CrudActionName, MagicStringHelper.CrudRefreshAction); await navigationService.GoBackAsync(paras); } else { await dialogService.DisplayAlertAsync("錯誤", $"差旅費用明細紀錄 儲存失敗:{apiResult.Message}", "確定"); } #endregion } #region 取得 差旅費用明細紀錄 fooIProgressDialog.Title = "請稍後,取得 差旅費用明細紀錄"; apiResult = await travelExpenseDetailService.GetAsync(MasterItem.Id); if (apiResult.Status == true) { await travelExpenseDetailService.WriteToFileAsync(); } else { await dialogService.DisplayAlertAsync("錯誤", $"取得 差旅費用明細紀錄 失敗:{apiResult.Message}", "確定"); } #endregion } #endregion }); #endregion #region 刪除 按鈕命令 DeleteCommand = new DelegateCommand(async() => { #region 進行記錄刪除 var confirm = await dialogService.DisplayAlertAsync( "警告", "是否要刪除這筆紀錄?", "確定", "取消"); if (confirm == false) { return; } APIResult apiResult = new APIResult(); using (IProgressDialog fooIProgressDialog = UserDialogs.Instance.Loading($"請稍後,刪除資料中...", null, null, true, MaskType.Black)) { await AppStatusHelper.ReadAndUpdateAppStatus(systemStatusService, appStatus); #region 檢查 Access Token 是否還可以使用 bool refreshTokenResult = await RefreshTokenHelper .CheckAndRefreshToken(dialogService, refreshTokenService, systemStatusService, appStatus); if (refreshTokenResult == false) { return; } #endregion #region 刪除 差旅費用明細紀錄 fooIProgressDialog.Title = "請稍後,刪除 差旅費用明細紀錄"; apiResult = await travelExpenseDetailService.DeleteAsync(SelectedItem); if (apiResult.Status == true) { ToastHelper.ShowToast($"差旅費用明細紀錄 已經刪除"); NavigationParameters paras = new NavigationParameters(); paras.Add(MagicStringHelper.CrudActionName, MagicStringHelper.CrudRefreshAction); await navigationService.GoBackAsync(paras); } else { await dialogService.DisplayAlertAsync("錯誤", $"差旅費用明細紀錄 刪除失敗:{apiResult.Message}", "確定"); } #endregion #region 取得 差旅費用明細紀錄 fooIProgressDialog.Title = "請稍後,取得 差旅費用明細紀錄"; apiResult = await travelExpenseDetailService.GetAsync(MasterItem.Id); if (apiResult.Status == true) { await travelExpenseDetailService.WriteToFileAsync(); } else { await dialogService.DisplayAlertAsync("錯誤", $"取得 差旅費用明細紀錄 失敗:{apiResult.Message}", "確定"); } #endregion } #endregion }); #endregion }
private async Task <TokenResponse> ProcessArbitraryTokenTokenResponse(TokenRequestValidationResult validationResult) { var subject = validationResult.ValidatedRequest.Subject.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject); var form = validationResult.ValidatedRequest.Raw; var resultClaims = new List <Claim>() { subject }; resultClaims.AddRange(_scopedOptionalClaims.Claims); var issuer = validationResult.ValidatedRequest.Raw.Get("issuer"); if (string.IsNullOrEmpty(issuer)) { issuer = _contextAccessor.HttpContext.GetIdentityServerIssuerUri(); } var atClaims = resultClaims.Distinct(new ClaimComparer()).ToList(); bool createRefreshToken; var offlineAccessClaim = atClaims.FirstOrDefault(x => x.Type == JwtClaimTypes.Scope && x.Value == IdentityServerConstants.StandardScopes.OfflineAccess); createRefreshToken = offlineAccessClaim != null; var authorizedScopes = (from c in atClaims where c.Type == JwtClaimTypes.Scope select c.Value).ToList(); var accessTokenLifetimeOverride = form.Get(Constants.AccessTokenLifetime); int accessTokenLifetime = validationResult.ValidatedRequest.AccessTokenLifetime; if (!string.IsNullOrWhiteSpace(accessTokenLifetimeOverride)) { int.TryParse(accessTokenLifetimeOverride, out accessTokenLifetime); } var at = new Token(OidcConstants.TokenTypes.AccessToken) { CreationTime = Clock.UtcNow.UtcDateTime, Issuer = issuer, Lifetime = accessTokenLifetime, Claims = atClaims, ClientId = validationResult.ValidatedRequest.ClientId, // Description = request.Description, AccessTokenType = validationResult.ValidatedRequest.AccessTokenType, AllowedSigningAlgorithms = validationResult.ValidatedRequest.Client.AllowedIdentityTokenSigningAlgorithms, }; var accessToken = await TokenService.CreateSecurityTokenAsync(at); string refreshToken = null; if (createRefreshToken) { var refreshTokenCreationRequest = new RefreshTokenCreationRequest { Subject = validationResult.ValidatedRequest.Subject, AccessToken = at, Client = validationResult.ValidatedRequest.Client, AuthorizedScopes = authorizedScopes }; refreshToken = await RefreshTokenService.CreateRefreshTokenAsync(refreshTokenCreationRequest); } var tokenResonse = new TokenResponse { AccessToken = accessToken, IdentityToken = null, RefreshToken = $"1_{refreshToken}", AccessTokenLifetime = accessTokenLifetime }; return(tokenResonse); }
protected async override Task <(string accessToken, string refreshToken)> CreateAccessTokenAsync(ValidatedTokenRequest request) { var formCollection = _scopedHttpContextRequestForm.GetFormCollection(); var grantType = formCollection["grant_type"]; var tokenRequest = new TokenCreationRequest { Subject = request.Subject, ValidatedResources = request.ValidatedResources, ValidatedRequest = request }; bool createRefreshToken; var authorizedScopes = Enumerable.Empty <string>(); IEnumerable <string> authorizedResourceIndicators = null; if (request.AuthorizationCode != null) { createRefreshToken = request.ValidatedResources.Resources.OfflineAccess; // createRefreshToken = request.AuthorizationCode.RequestedScopes.Contains(IdentityServerConstants.StandardScopes.OfflineAccess); // load the client that belongs to the authorization code Client client = null; if (request.AuthorizationCode.ClientId != null) { // todo: do we need this check? client = await Clients.FindEnabledClientByIdAsync(request.AuthorizationCode.ClientId); } if (client == null) { throw new InvalidOperationException("Client does not exist anymore."); } tokenRequest.Subject = request.AuthorizationCode.Subject; tokenRequest.Description = request.AuthorizationCode.Description; authorizedScopes = request.AuthorizationCode.RequestedScopes; authorizedResourceIndicators = request.AuthorizationCode.RequestedResourceIndicators; } else if (request.DeviceCode != null) { createRefreshToken = request.DeviceCode.AuthorizedScopes.Contains(IdentityServerConstants.StandardScopes.OfflineAccess); Client client = null; if (request.DeviceCode.ClientId != null) { // todo: do we need this check? client = await Clients.FindEnabledClientByIdAsync(request.DeviceCode.ClientId); } if (client == null) { throw new InvalidOperationException("Client does not exist anymore."); } tokenRequest.Subject = request.DeviceCode.Subject; tokenRequest.Description = request.DeviceCode.Description; authorizedScopes = request.DeviceCode.AuthorizedScopes; } else { createRefreshToken = request.RequestedScopes.Contains(IdentityServerConstants.StandardScopes.OfflineAccess); authorizedScopes = request.ValidatedResources.RawScopeValues; } var at = await TokenService.CreateAccessTokenAsync(tokenRequest); object obj; if (_scopedStorage.TryGetValue(Constants.ScopedRequestType.OverrideTokenIssuedAtTime, out obj)) { DateTime issuedAtTime = obj is DateTime ? (DateTime)obj : default; at.CreationTime = issuedAtTime; } var finalScopes = at.Scopes.ToList(); if (createRefreshToken) { if (!finalScopes.Contains(IdentityServerConstants.StandardScopes.OfflineAccess)) { finalScopes.Add(IdentityServerConstants.StandardScopes.OfflineAccess); } } else { if (finalScopes.Contains(IdentityServerConstants.StandardScopes.OfflineAccess)) { finalScopes.Remove(IdentityServerConstants.StandardScopes.OfflineAccess); } } var accessToken = await TokenService.CreateSecurityTokenAsync(at); string refreshToken = null; if (createRefreshToken) { var rtRequest = new RefreshTokenCreationRequest { Client = request.Client, Subject = tokenRequest.Subject, Description = tokenRequest.Description, AuthorizedScopes = authorizedScopes, AuthorizedResourceIndicators = authorizedResourceIndicators, AccessToken = at, RequestedResourceIndicator = request.RequestedResourceIndicator, }; refreshToken = await RefreshTokenService.CreateRefreshTokenAsync(rtRequest); } if (_scopedStorage.TryGetValue(Constants.ScopedRequestType.ExtensionGrantValidationContext, out obj)) { var extensionGrantValidationContext = obj as ExtensionGrantValidationContext; if (extensionGrantValidationContext.Request.GrantType == FluffyBunny4.Constants.GrantType.TokenExchangeMutate) { var refreshTokenStoreGrantStoreHashAccessor = _refreshTokenStore as IGrantStoreHashAccessor; var referenceTokenStoreGrantStoreHashAccessor = _referenceTokenStore as IGrantStoreHashAccessor; _scopedStorage.TryGetValue(Constants.ScopedRequestType.PersistedGrantExtra, out obj); var persistedGrantExtra = _scopedStorage.Get <PersistedGrantExtra>(Constants.ScopedRequestType.PersistedGrantExtra); var subjectToken = _scopedStorage.Get <string>(Constants.ScopedRequestType.SubjectToken); var fixedSubjectToken = subjectToken.Substring(2); var newKey = referenceTokenStoreGrantStoreHashAccessor.GetHashedKey(accessToken); var originalKey = referenceTokenStoreGrantStoreHashAccessor.GetHashedKey(fixedSubjectToken); await _persistedGrantStore.CopyAsync(newKey, originalKey); await _persistedGrantStore.RemoveAsync(newKey); if (!createRefreshToken && !string.IsNullOrWhiteSpace(persistedGrantExtra.RefreshTokenKey)) { // need to kill the old refresh token, as this mutate didn't ask for a new one. await _persistedGrantStore.RemoveAsync(persistedGrantExtra.RefreshTokenKey); } else { newKey = refreshTokenStoreGrantStoreHashAccessor.GetHashedKey(refreshToken); await _persistedGrantStore.CopyAsync(newKey, persistedGrantExtra.RefreshTokenKey); await _persistedGrantStore.RemoveAsync(newKey); } // we need to point the old access_token and refresh_token to this new set; return(subjectToken, null); // mutate doesn't get to get the refresh_token back, the original holder of it is the only owner. } } switch (grantType) { case FluffyBunny4.Constants.GrantType.ArbitraryIdentity: case FluffyBunny4.Constants.GrantType.ArbitraryToken: case OidcConstants.GrantTypes.DeviceCode: case FluffyBunny4.Constants.GrantType.TokenExchange: case FluffyBunny4.Constants.GrantType.TokenExchangeMutate: if (!accessToken.Contains('.')) { accessToken = $"1_{accessToken}"; } if (!string.IsNullOrWhiteSpace(refreshToken)) { refreshToken = $"1_{refreshToken}"; } break; default: if (!accessToken.Contains('.')) { accessToken = $"0_{accessToken}"; } if (!string.IsNullOrWhiteSpace(refreshToken)) { refreshToken = $"0_{refreshToken}"; } break; } return(accessToken, refreshToken); // return (accessToken, null); }
public async Task <IHttpActionResult> GetRefreshTokens([FromUri] Pagination paginationModel) => Ok(await RefreshTokenService.GetAllAsync(paginationModel.Page, paginationModel.PageSize));
public TravelExpensePageViewModel(INavigationService navigationService, IPageDialogService dialogService, TravelExpenseService travelExpenseService, MyUserService myUserService, TravelExpenseDetailService travelExpenseDetailService, RefreshTokenService refreshTokenService, SystemStatusService systemStatusService, AppStatus appStatus) { this.navigationService = navigationService; this.dialogService = dialogService; this.travelExpenseService = travelExpenseService; this.myUserService = myUserService; this.travelExpenseDetailService = travelExpenseDetailService; this.refreshTokenService = refreshTokenService; this.systemStatusService = systemStatusService; this.appStatus = appStatus; #region 新增紀錄 AddCommand = new DelegateCommand(async() => { NavigationParameters paras = new NavigationParameters(); var fooObject = new TravelExpenseDto(); fooObject.ApplyDate = DateTime.Now.Date; #region 設定該使用者為預設紀錄申請者 var myUser = myUserService.Items .FirstOrDefault(x => x.Id == appStatus.SystemStatus.UserID); if (myUser != null) { fooObject.MyUserId = myUser.Id; fooObject.MyUserName = myUser.Name; } #endregion paras.Add(MagicStringHelper.CurrentSelectdItemParameterName, fooObject); paras.Add(MagicStringHelper.CrudActionName, MagicStringHelper.CrudAddAction); await navigationService.NavigateAsync("TravelExpenseRecordPage", paras); }); #endregion #region 點選某筆紀錄觸發命令 ItemTappedCommand = new DelegateCommand(async() => { NavigationParameters paras = new NavigationParameters(); var fooObject = SelectedItem.Clone(); paras.Add(MagicStringHelper.CurrentSelectdItemParameterName, fooObject); paras.Add(MagicStringHelper.CrudActionName, MagicStringHelper.CrudEditAction); await navigationService.NavigateAsync("TravelExpenseRecordPage", paras); }); #endregion #region 更新遠端紀錄命令 RefreshCommand = new DelegateCommand(async() => { IsRefresh = true; await ReloadData(); IsRefresh = false; }); #endregion #region 顯示明細頁面 ShowDetailCommand = new DelegateCommand <TravelExpenseDto>(async x => { #region 讀取該筆明細清單 using (IProgressDialog fooIProgressDialog = UserDialogs.Instance.Loading($"請稍後,更新資料中...", null, null, true, MaskType.Black)) { await AppStatusHelper.ReadAndUpdateAppStatus(systemStatusService, appStatus); #region 檢查 Access Token 是否還可以使用 bool refreshTokenResult = await RefreshTokenHelper .CheckAndRefreshToken(dialogService, refreshTokenService, systemStatusService, appStatus); if (refreshTokenResult == false) { return; } #endregion #region 取得 差旅費用明細紀錄 fooIProgressDialog.Title = "請稍後,取得 差旅費用明細紀錄"; var apiResultssss = await travelExpenseDetailService.GetAsync(x.Id); if (apiResultssss.Status == true) { await travelExpenseDetailService.WriteToFileAsync(); NavigationParameters paras = new NavigationParameters(); paras.Add(MagicStringHelper.MasterRecordActionName, x); await navigationService.NavigateAsync("TravelExpenseDetailPage", paras); } else { await DialogHelper.ShowAPIResultIsFailureMessage(dialogService, apiResultssss); return; } #endregion } #endregion }); #endregion }
public async Task <IHttpActionResult> GetRefreshToken(string clientId) => Ok(await RefreshTokenService.GetByClientIdAsync(clientId));