/// <summary> /// Configures a token cache using the provide <see cref="IAuthContext"/>. /// </summary> /// <param name="tokenCache">MSAL's token cache to configure.</param> /// <param name="authContext">The <see cref="IAuthContext"/> to get configure an token cache for.</param> private static void ConfigureTokenCache(ITokenCache tokenCache, IAuthContext authContext) { tokenCache.SetBeforeAccess((TokenCacheNotificationArgs args) => { try { _cacheLock.EnterReadLock(); args.TokenCache.DeserializeMsalV3(TokenCacheStorage.GetToken(authContext), shouldClearExistingCache: true); } finally { _cacheLock.ExitReadLock(); } }); tokenCache.SetAfterAccess((TokenCacheNotificationArgs args) => { if (args.HasStateChanged) { try { _cacheLock.EnterWriteLock(); TokenCacheStorage.SetToken(authContext, args.TokenCache.SerializeMsalV3()); } finally { _cacheLock.ExitWriteLock(); } } }); }
/// <summary> /// Deletes an access token from the host OS. /// </summary> /// <param name="appId">An app/client id.</param> public static void DeleteToken(IAuthContext authContext) { if (string.IsNullOrEmpty(authContext.ClientId)) { throw new ArgumentNullException(string.Format( CultureInfo.CurrentCulture, ErrorConstants.Message.NullOrEmptyParameter, nameof(authContext.ClientId))); } if (authContext.ContextScope == ContextScope.Process) { GraphSession.Instance.MSALToken = null; } else { if (Helpers.OperatingSystem.IsWindows()) { WindowsTokenCache.DeleteToken(authContext.ClientId); } else if (Helpers.OperatingSystem.IsMacOS()) { MacTokenCache.DeleteToken(authContext.ClientId); } else { LinuxTokenCache.DeleteToken(authContext.ClientId); } } }
/// <summary> /// Encrypts and saves an access token buffer to the host platform OS. /// </summary> /// <param name="appId">An app/client id.</param> /// <param name="accessToken">An access token.</param> public static void SetToken(IAuthContext authContext, byte[] accessToken) { if (string.IsNullOrEmpty(authContext.ClientId)) { throw new ArgumentNullException(string.Format( CultureInfo.CurrentCulture, ErrorConstants.Message.NullOrEmptyParameter, nameof(authContext.ClientId))); } if (accessToken == null || accessToken.Length == 0) { return; } if (authContext.ContextScope == ContextScope.Process) { GraphSession.Instance.MSALToken = accessToken; } else if (authContext.ContextScope == ContextScope.CurrentUser) { if (Helpers.OperatingSystem.IsWindows()) { WindowsTokenCache.SetToken(authContext.ClientId, accessToken); } else if (Helpers.OperatingSystem.IsMacOS()) { MacTokenCache.SetToken(authContext.ClientId, accessToken); } else { LinuxTokenCache.SetToken(authContext.ClientId, accessToken); } } }
internal static IAuthenticationProvider GetAuthProvider(IAuthContext authConfig) { if (authConfig.AuthType == AuthenticationType.Delegated) { IPublicClientApplication publicClientApp = PublicClientApplicationBuilder .Create(authConfig.ClientId) .WithTenantId(authConfig.TenantId) .Build(); ConfigureTokenCache(publicClientApp.UserTokenCache, authConfig.ClientId); return(new DeviceCodeProvider(publicClientApp, authConfig.Scopes, async(result) => { await Console.Out.WriteLineAsync(result.Message); })); } else { IConfidentialClientApplication confidentialClientApp = ConfidentialClientApplicationBuilder .Create(authConfig.ClientId) .WithTenantId(authConfig.TenantId) .WithCertificate(string.IsNullOrEmpty(authConfig.CertificateThumbprint) ? GetCertificateByName(authConfig.CertificateName) : GetCertificateByThumbprint(authConfig.CertificateThumbprint)) .Build(); ConfigureTokenCache(confidentialClientApp.AppTokenCache, authConfig.ClientId); return(new ClientCredentialProvider(confidentialClientApp)); } }
internal static void Logout(IAuthContext authConfig) { lock (FileLock) { TokenCacheStorage.DeleteToken(authConfig.ClientId); } }
private void DecodeJWT(string token, IAccount account, ref IAuthContext authContext) { JwtPayload jwtPayload = JwtHelpers.DecodeToObject <JwtPayload>(token); if (authContext.AuthType == AuthenticationType.UserProvidedAccessToken) { if (jwtPayload == null) { throw new Exception(string.Format( CultureInfo.CurrentCulture, ErrorConstants.Message.InvalidUserProvidedToken, nameof(AccessToken))); } if (jwtPayload.Exp <= JwtHelpers.ConvertToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromMinutes(Constants.TokenExpirationBufferInMinutes))) { throw new Exception(string.Format( CultureInfo.CurrentCulture, ErrorConstants.Message.ExpiredUserProvidedToken, nameof(AccessToken))); } } authContext.ClientId = jwtPayload?.Appid ?? authContext.ClientId; authContext.Scopes = jwtPayload?.Scp?.Split(' ') ?? jwtPayload?.Roles; authContext.TenantId = jwtPayload?.Tid ?? account?.HomeAccountId?.TenantId; authContext.AppName = jwtPayload?.AppDisplayname; authContext.Account = jwtPayload?.Upn ?? account?.Username; }
protected override void ProcessRecord() { base.ProcessRecord(); IAuthContext authConfig = GraphSession.Instance.AuthContext; WriteObject(authConfig as IAuthContext); }
public ProcessTokenCacheStorageTests() { _testAppContext1 = new AuthContext { ClientId = "test_app_id_1" }; GraphSessionInitializer.InitializeSession(); }
public PostsController( IMediator mediator, IAuthContext authContext) { _authContext = authContext ?? throw new ArgumentNullException(nameof(authContext)); _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator)); }
public DeleteUserInfoResponse DeleteUserInfo(DeleteUserInfoRequest request, IAuthContext authContext) { DeleteUserInfoResponse response = new DeleteUserInfoResponse(); var userProviderRepo = _unitOfWork.GetRepository <UserProvider>(); var accountRepo = _unitOfWork.GetRepository <Account>(); var userProviderRecord = userProviderRepo.Get(x => x.UserId.ToString() == authContext.UserId && x.Provider.ToString() == request.ProviderId); if (userProviderRecord != null) { userProviderRepo.Delete(userProviderRecord); var obsoleteAccounts = accountRepo.GetList(x => x.UserId.ToString() == authContext.UserId && x.ProviderId.ToString() == request.ProviderId); foreach (Account acc in obsoleteAccounts) { accountRepo.Delete(acc); } var result = _unitOfWork.SaveChanges(); if (result > 0) { response.Status = "Deleted " + authContext.UserId + " " + Provider.GetInstance(int.Parse(request.ProviderId)).Text; return(response); } } response.Status = "Could not find given provider information for the user"; return(response); }
public GetAccountsResponse GetAccounts(GetAccountsRequest request, IAuthContext authContext) { var accountRepo = _unitOfWork.GetRepository <Account>(); var accounts = accountRepo.GetAsyncQueryable(x => x.UserId.ToString() == authContext.UserId, w => w.AccountIdentifications).Result.ToList(); GetAccountsResponse response = new GetAccountsResponse(); response.Items = new List <GetAccountsResponseItem>(); foreach (Account acc in accounts) { var account = new GetAccountsResponseItem() { AccountId = acc.Id.ToString(), AccountType = AccountType.GetInstance(acc.AccountType).Text, CurrencyType = CurrencyType.GetInstance(acc.CurrencyType).Text, Name = acc.Name, ProviderAccountId = acc.ProviderAccountId, ProviderName = Provider.GetInstance(acc.ProviderId).Text }; foreach (AccountIdentification ai in acc.AccountIdentifications) { account.AccountIdentification.Add(AccountIdentificationType.GetInstance(ai.AccountIdentificationTypeId).Text + ": " + ai.Identification); } response.Items.Add(account); } return(response); }
public MessageRepository(IAuthContext authContext, IChatRepository chatRepository, IUserRepository userRepository) { _authContext = authContext ?? throw new ArgumentNullException(nameof(authContext)); _chatRepository = chatRepository ?? throw new ArgumentNullException(nameof(chatRepository)); _userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository)); }
public GetHomeadminInfoStrategy(IEnumerable <IGetHomeadminInfoQuery> queries , IAuthContext authContext ) { this.authContext = authContext ?? throw new NotImplementedException(nameof(IAuthContext)); this.queries = queries ?? throw new NotImplementedException(nameof(IEnumerable <IGetHomeadminInfoQuery>)); }
public virtual async Task <IAuthContext> GetAuthContextAsync(CancellationToken cancellationToken = default) { if (_authContext == null) { _authContext = await CreateAuthContextAsync(cancellationToken); } return(_authContext); }
public GetProjectDetailsStrategy(IEnumerable <IGetProjectDetailsQuery> queries , IAuthContext authContext ) { this.queries = queries ?? throw new NotImplementedException(nameof(IEnumerable <IGetProjectDetailsQuery>)); this.authContext = authContext ?? throw new NotImplementedException(nameof(IAuthContext)); }
public virtual IAuthContext GetAuthContext() { if (_authContext == null) { _authContext = CreateAuthContext(); } return(_authContext); }
public AccountController(IAuthContext authContext, IHttpClientFactory httpClientFactory, IAccountDataService accountDataService, IIntegrationEventService integrationEventService, IServiceProvider serviceProvider, IUnitOfWork uow) { _authContext = authContext; _httpClientFactory = httpClientFactory; _accountDataService = accountDataService; _integrationEventService = serviceProvider.GetRequiredService <IIntegrationEventService>(); _uow = uow; }
public UploadController(IEventService eventService, ITokensService tokenService, IAuthContext authContext, IHostingEnvironment appEnvironment, IVideoService videoService) : base(authContext) { _eventService = eventService; _tokenService = tokenService; _authContext = authContext; _appEnvironment = appEnvironment; _videoService = videoService; }
public UserGetTasksQuery(DataContext dataContext , IMapper mapper , IAuthContext authContext ) { this.dataContext = dataContext ?? throw new NotImplementedException(nameof(DataContext)); this.mapper = mapper ?? throw new NotImplementedException(nameof(IMapper)); this.authContext = authContext ?? throw new NotImplementedException(nameof(IAuthContext)); }
public SignInCommandHandler( IUnitOfWork unitOfWork, IAuthContext authContext, IPasswordHasher passwordHasher) { _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork)); _authContext = authContext ?? throw new ArgumentNullException(nameof(authContext)); _passwordHasher = passwordHasher ?? throw new ArgumentNullException(nameof(passwordHasher)); }
// Parameterless extension methods should return Task.CompletedTask so that you // don't have to do this: // // return QueryAsync( // () => // { // Authorize.AnyUser(); // return Task.CompletedTask; // }, // () => { /* ... */ } // ); public static Task AnyUser(this IAuthContext auth) { if (!auth.IsAuthenticated) { throw new NotAuthorizedException(); } return(Task.CompletedTask); }
public UserGetProjectDetailsQuery(DataContext dataContext , IMapper mapper , IAuthContext authContext ) { this.dataContext = dataContext; this.mapper = mapper; this.authContext = authContext; }
/// <summary> /// Gets an <see cref="IAuthenticationProvider"/> using the provide <see cref="IAuthContext"/>. /// </summary> /// <param name="authContext">The <see cref="IAuthContext"/> to get an auth provider for.</param> /// <returns>A <see cref="IAuthenticationProvider"/> based on provided <see cref="IAuthContext"/>.</returns> public static IAuthenticationProvider GetAuthProvider(IAuthContext authContext) { if (authContext is null) { throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext); } IAuthenticationProvider authProvider = null; string authorityUrl = GetAuthorityUrl(authContext); switch (authContext.AuthType) { case AuthenticationType.Delegated: { IPublicClientApplication publicClientApp = PublicClientApplicationBuilder .Create(authContext.ClientId) .WithTenantId(authContext.TenantId) .WithAuthority(authorityUrl) .WithClientCapabilities(new[] { "cp1" }) .Build(); ConfigureTokenCache(publicClientApp.UserTokenCache, authContext); authProvider = new DeviceCodeProvider(publicClientApp, authContext.Scopes, async(result) => { await Console.Out.WriteLineAsync(result.Message); }); break; } case AuthenticationType.AppOnly: { IConfidentialClientApplication confidentialClientApp = ConfidentialClientApplicationBuilder .Create(authContext.ClientId) .WithTenantId(authContext.TenantId) .WithAuthority(authorityUrl) .WithCertificate(GetCertificate(authContext)) .Build(); ConfigureTokenCache(confidentialClientApp.AppTokenCache, authContext); string graphBaseUrl = GraphSession.Instance.Environment?.GraphEndpoint ?? "https://graph.microsoft.com"; authProvider = new ClientCredentialProvider(confidentialClientApp, $"{graphBaseUrl}/.default"); break; } case AuthenticationType.UserProvidedAccessToken: { authProvider = new DelegateAuthenticationProvider((requestMessage) => { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", new NetworkCredential(string.Empty, GraphSession.Instance.UserProvidedToken).Password); return(Task.CompletedTask); }); break; } } return(authProvider); }
public ProjectAdministratorGetUsersQuery(DataContext dataContext , IMapper mapper , IAuthContext authContext ) { this.dataContext = dataContext ?? throw new NotImplementedException(nameof(DataContext)); this.mapper = mapper ?? throw new NotImplementedException(nameof(IMapper)); this.authContext = authContext ?? throw new NotImplementedException(nameof(IAuthContext)); }
public AuthService(IProducer producer, IAuthContext authContext, ITokenVerifier tokenVerifier, IMapper mapper, ILogger <AuthService> logger) { _producer = producer; _authContext = authContext; _tokenVerifier = tokenVerifier; _mapper = mapper; _logger = logger; }
public ChangeTaskStatusCommand(DataContext dataContext , IMapper mapper , IAuthContext authContext ) { this.dataContext = dataContext ?? throw new NotImplementedException(nameof(DataContext)); this.mapper = mapper ?? throw new NotImplementedException(nameof(IMapper)); this.authContext = authContext ?? throw new NotImplementedException(nameof(IAuthContext)); }
public NatWestClientOperationsBusinessLogic(INatWestClientOperationsService bankService, IDistributedCachingService cachingService, IAuthContext authContext, IOptions <ClientInformations> clientInformations, IIntegrationEventService integrationEventService) { _bankService = bankService; _cachingService = cachingService; _authContext = authContext; _rackleClientCacheKey = clientInformations.Value.RackleClientCacheKey; _natWestRedirectUri = clientInformations.Value.NatWest.ClientInfo.RedirectUri; _integrationEventService = integrationEventService; }
public async Task Invoke(HttpContext context, IAuthContext userContext, IOptions <JwtOption> optionContainer) { //检查当前url是否可以匿名访问,如果可以就直接通过,不做验证了;如果不是可以匿名访问的路径,那就继续 if (userContext.IsAllowAnonymous(context.Request.Path)) { await next(context); return; } var option = optionContainer.Value; #region 设置自定义jwt 的秘钥 if (!string.IsNullOrEmpty(option.SecurityKey)) { JwtHandler.securityKey = option.SecurityKey; } #endregion #region 身份验证,并设置用户Ruser值 //获取当前http头部携带的jwt(存放在头部的 Authorization中) var result = context.Request.Headers.TryGetValue("Authorization", out StringValues authStr); if (!result || string.IsNullOrEmpty(authStr.ToString())) { throw new UnauthorizedAccessException("未授权"); } result = JwtHandler.Validate(authStr.ToString().Substring("Bearer ".Length).Trim(), payLoad => { var success = true; //可以添加一些自定义验证,用法参照测试用例 //验证是否包含aud 并等于 roberAudience success = success && payLoad["aud"]?.ToString() == option.Audience; if (success) { //在获取jwt的时候把当前用户存放在payLoad的user键中 //如果用户信息比较多,建议放在缓存中,payLoad中存放缓存的Key值 //获取当前访问用户信息,把用户的基本信息放在payLoad["user"]中 userContext.TryInit(payLoad["user"]?.ToString()); } return(success); }); if (!result) { throw new UnauthorizedAccessException("未授权"); } #endregion #region 权限验证 if (!userContext.Authorize(context.Request.Path)) { throw new UnauthorizedAccessException("未授权"); } #endregion await next(context); }
public GetProjectsCommand(DataContext dataContext , GetProjectsStrategy getProjectsStrategy , IAuthContext authContext ) { this.dataContext = dataContext; this.getProjectsStrategy = getProjectsStrategy; this.authContext = authContext; }
public GetProvidersResponse GetProviders(GetProvidersRequest request, IAuthContext authContext) { GetProvidersResponse response = new GetProvidersResponse(); response.Items = Market.MarketEnumList.SingleOrDefault(x => !request.MarketId.HasValue || x.Value == request.MarketId.Value).Providers.Select(x => new ProviderItem { Value = x.Value, Text = x.Text, FlagUrl = x.FlagUrl, LoginUrl = _providerUrls.GetUrl(_providerUrls, x.Text) }).ToList(); return(response); }
///<summary> /// Initializes a new instance of <see cref="CookieSessionStore"/> class with specified <see cref="HttpContext"/> and <see cref="IAuthContext"/> ///</summary> ///<param name="httpContext">The http context the response of which is used to store the cookie with session data.</param> ///<param name="authContext">The authentication context.</param> ///<exception cref="ArgumentNullException">either <paramref name="httpContext"/> or <paramref name="authContext"/> is null.</exception> public CookieSessionStore([NotNullAttribute] HttpContext httpContext, [NotNullAttribute] IAuthContext authContext) { if (httpContext == null) throw FacebookApi.Nre("httpContext"); if (authContext == null) throw FacebookApi.Nre("authContext"); _httpContext = httpContext; _authContext = authContext; }
/// <summary> /// Initializes a new instance of <see cref="Identity"/> class with specified authentication context. /// </summary> /// <param name="context">The context to initialize with.</param> /// <exception cref="ArgumentNullException"><paramref name="context"/> is null.</exception> public Identity([NotNull] IAuthContext context) { if (context == null) throw FacebookApi.Nre("context"); _context = context; }
public AuthRepository(IAuthContext context) { Context = context; }