public async Task <DeviceAuthorizationResponse> RequestDeviceAuthorizationAsync() { DiscoveryDocumentResponse disco = await DiscoveryCache.GetAsync(); if (disco.IsError) { throw new Exception(disco.Error); } DeviceAuthorizationResponse response = await AuthHttpClient.RequestDeviceAuthorizationAsync(new DeviceAuthorizationRequest { Address = disco.DeviceAuthorizationEndpoint, Scope = Configuration["Scope"], ClientId = Configuration["ClientId"], ClientSecret = Configuration["ClientSecret"], }); string url = $"{ response.VerificationUri}?userCode={ response.UserCode}"; ProcessStartInfo proc = new ProcessStartInfo(url) { UseShellExecute = true }; Process.Start(proc); return(response); }
public async Task <IActionResult> GetRefTokenAsync(IdentityCredentialsModel model) { IDiscoveryCache _discoCache = new DiscoveryCache(model.IdentityServer); var disco = await _discoCache.GetAsync(); if (disco.IsError) { // throw new Exception(disco.Error); model.ReferenceToken = disco.Error; return(View("ReferenceToken", model)); } ; var client = new HttpClient(); var response = await client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = disco.TokenEndpoint, ClientId = model.ClientUserName, ClientSecret = model.ClientSecret, UserName = model.UserUserName, Password = model.UserSecret }); if (response.IsError) { model.ReferenceToken = response.Json.ToString(); } else { model.ReferenceToken = response.Json.ToString(); } return(View("ReferenceToken", model)); }
public async Task <IActionResult> Logout() { DiscoveryCache discoveryCache = (DiscoveryCache)HttpContext .RequestServices.GetService(typeof(IDiscoveryCache)); DiscoveryDocumentResponse discovery = await discoveryCache.GetAsync(); if (!discovery.IsError) { return(Redirect(discovery.EndSessionEndpoint)); } else { _logger.Warning(discovery.Error); } await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignOutAsync("oidc"); foreach (var cookie in Request.Cookies) { Response.Cookies.Delete(cookie.Key); } string url = _appSettings.Authorization.AuthorizationService.MainTrim; url += "/Home/Index"; return(Redirect(url)); }
public async Task <IActionResult> GetClaimsTokenAsync(IdentityCredentialsModel model) { IDiscoveryCache _discoCache = new DiscoveryCache(model.IdentityServer); var disco = await _discoCache.GetAsync(); if (disco.IsError) { // throw new Exception(disco.Error); model.ClaimsToken = disco.Error; return(View("ReferenceToken", model)); } ; var client = new HttpClient(); var response = await client.IntrospectTokenAsync(new TokenIntrospectionRequest { Address = disco.IntrospectionEndpoint, ClientId = model.ApiUserName, ClientSecret = model.ApiSecret, //"Api3Secret", Token = model.ReferenceToken }); if (response.IsError) { model.ClaimsToken = response.Json.ToString(); } else { model.ClaimsToken = response.Json.ToString(); } return(View("ReferenceToken", model)); }
async Task <string> GetTokenAsync() { var httpClient = _defaultHttpClientFactory.HttpClient; TokenResponse tokenResponse = null; if (!_memoryCache.TryGetValue(_cacheKey, out tokenResponse)) { // Key not in cache, so get data. var discoveryResponse = await DiscoveryCache.GetAsync(); tokenResponse = await httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = discoveryResponse.TokenEndpoint, ClientId = _settings.ClientId, ClientSecret = _settings.ClientSecret }); // Set cache options. var cacheEntryOptions = new MemoryCacheEntryOptions() // Keep in cache for this time, reset time if accessed. .SetSlidingExpiration(TimeSpan.FromMinutes(3)); // Save data in cache. _memoryCache.Set(_cacheKey, tokenResponse, cacheEntryOptions); if (tokenResponse.IsError) { _summaryLogger.Add("client_credentials_error", $"clientId:{_settings.ClientId} error:{tokenResponse.Error} endpoint:{discoveryResponse.TokenEndpoint}"); } } return(tokenResponse.AccessToken); }
public IdentityClient( IOptions <AppSettings> configuration, ILogger <IdentityClient> logger, IHttpClientFactory httpClientFactory) { this.appSettings = configuration.Value; this.logger = logger; this.httpClientFactory = httpClientFactory; this.remoteServiceBaseUrl = this.appSettings.Host.AuthServer; this.semaphore = new Semaphore(1, 1); #region Set variables this.secret = DEFAULT_SECRET; this.clientId = this.appSettings?.AuthOptions?.ClientId ?? DEFAULT_CLIENT_ID; #endregion #region Create Discovery Cache client var discoPolicy = this.remoteServiceBaseUrl.StartsWith("https") ? null : new DiscoveryPolicy { RequireHttps = false, }; this.discoCacheClient = new DiscoveryCache( this.remoteServiceBaseUrl, () => this.httpClientFactory.CreateClient(HttpClientNameFactory.AuthHttpClient), discoPolicy); // Set cache duration discoCacheClient.CacheDuration = TimeSpan.FromHours(8); #endregion }
public ApiClient(IHttpClientFactory httpClientFactory, IConfiguration configuration, ILogger <ApiClient> log) { appConfig = configuration.GetSection("booking_facilities"); discoveryCache = new DiscoveryCache(appConfig.GetValue <string>("GatekeeperUrl")); client = httpClientFactory.CreateClient("gatekeeper"); logger = log; }
public async Task <TokenRevocationResponse> RevokeToken(TokenRequestDTO tokenRequest) { try { var client = _clientFactory.CreateClient(); var cache = new DiscoveryCache(_config["AuthApiUrl"]); var disco = await cache.GetAsync() .ConfigureAwait(false); if (disco.IsError) { throw new Exception(disco.Error); } var revokeResult = await client.RevokeTokenAsync(new TokenRevocationRequest { Address = disco.RevocationEndpoint, ClientId = tokenRequest.ClientId, ClientSecret = tokenRequest.ClientSecret, Token = tokenRequest.RefreshToken }).ConfigureAwait(false); return(revokeResult); } catch (Exception ex) { _logger.LogError(ex, nameof(RevokeToken)); throw; } }
protected override void Load(ContainerBuilder builder) { builder.RegisterType <IdentityQueryInput>(); builder.RegisterType <AccessCodeDocumentType>(); var configuration = GlobalConfigurationRoot.Configuration; var authority = configuration["oauth2:norton:authority"]; var additionalEndpointBaseAddresses = new List <string>(); configuration.GetSection("oauth2:norton:additionalEndpointBaseAddresses").Bind(additionalEndpointBaseAddresses); var discoveryClient = new DiscoveryClient(authority); foreach (var additionalEndpointBaseAddress in additionalEndpointBaseAddresses) { discoveryClient.Policy.AdditionalEndpointBaseAddresses.Add(additionalEndpointBaseAddress); } var nortonDiscoveryCache = new DiscoveryCache(discoveryClient); builder.Register(c => nortonDiscoveryCache) .As <DiscoveryCache>() .SingleInstance(); // builder.RegisterType<MyFieldRecordRegistration>().As<IFieldRecordRegistration>(); // builder.RegisterType<MyFieldRecordRegistration2>().As<IFieldRecordRegistration>(); }
/// <summary> /// Initializes a new instance of the <see cref="CompanyCommunicatorBotFilterMiddleware"/> class. /// </summary> /// <param name="configuration">ASP.NET Core <see cref="IConfiguration"/> instance.</param> public CompanyCommunicatorBotFilterMiddleware(IConfiguration configuration, DiscoveryCache discoveryCache, AtWorkRioIdentityOptions atWorkRioIdentityOptions) { this.configuration = configuration; this.discoveryCache = discoveryCache; this.atWorkRioIdentityOptions = atWorkRioIdentityOptions; }
public async Task Old_initialization_should_work() { var client = new DiscoveryClient(_authority, _successHandler); var cache = new DiscoveryCache(client); var disco = await cache.GetAsync(); disco.IsError.Should().BeFalse(); }
public OidcAuthenticator(OidcSettings oidcSettings) { this.oidcSettings = oidcSettings ?? throw new ArgumentNullException(nameof(oidcSettings)); httpClient = this.oidcSettings.HttpClient ?? new HttpClient(); var discoveryPolicy = this.oidcSettings.DiscoveryPolicy ?? new DiscoveryPolicy(); discoveryCache = new DiscoveryCache(this.oidcSettings.AuthUri?.ToString(), GetHttpClient, discoveryPolicy); }
public SigningKeysProvider(string authority) { var policy = new DiscoveryPolicy { ValidateIssuerName = false }; cache = new DiscoveryCache(authority, () => new HttpClient(), policy); }
public MyQueryFieldRecordRegistrationBase( IHttpContextAccessor httpContextAccessor, IConfiguration configuration, DiscoveryCache discoveryCache) { _httpContextAccessor = httpContextAccessor; _configuration = configuration; _discoveryCache = discoveryCache; }
private async Task <string> GetTokenEndpoint() { var cache = new DiscoveryCache(_restAuth.MetadataAddress, client: null, policy: new DiscoveryPolicy { ValidateEndpoints = false }); var response = await cache.GetAsync(); return(response.TokenEndpoint); }
public WithoutDiscoveryController() { GetParameters(); if (MobileConnect == null) { SessionCache = new SessionCache(); DiscoveryCache = new DiscoveryCache(OperatorParams.maxDiscoveryCacheSize); MobileConnect = new MobileConnectWebInterface(MobileConnectConfig, SessionCache, DiscoveryCache); } }
private async Task <string> GetTokenEndpoint() { var cache = new DiscoveryCache(_settings.MetadataAddress, client: null, policy: new DiscoveryPolicy { ValidateEndpoints = false }); var discovery = await cache.GetAsync(); return(discovery.TokenEndpoint); }
public AuthService(IGenericRepository genericRepository, AuthenticationStateProvider authProvider, HttpClient httpClient, IJSRuntime JSRuntime, ILanguageContainerService translator) { _genericRepository = genericRepository; _authProvider = authProvider; _httpClient = httpClient; baseUrl = _httpClient.BaseAddress.AbsoluteUri; Discovery = new DiscoveryCache(_httpClient.BaseAddress.AbsoluteUri); JsRuntime = JSRuntime; _translate = translator; }
public async Task <TokenResponse> RequestTokenAsync() { DiscoveryDocumentResponse disco = await DiscoveryCache.GetAsync(); return(await AuthHttpClient.RequestTokenAsync(new TokenRequest() { Address = disco.TokenEndpoint, GrantType = Configuration["GrantType"], ClientId = Configuration["ClientId"], ClientSecret = Configuration["ClientSecret"], })); }
public UserApiClient( IUriHelper uri, HttpClient client, AuthorizationContext authorizationContext, IOptions <UserApiClientOptions> options) { this.uri = uri; this.client = client; this.authorizationContext = authorizationContext; this.options = options.Value; cache = new DiscoveryCache(this.options.Address, client); crypto = new CryptoHelper(); }
internal OpenIdConnectBroker(string authority, string clientId, string clientSecret, string scope, IAuthorizationUriAcquirer authUriAcquirer, DiscoveryPolicy discoveryPolicy) : base(clientId, clientSecret, scope, authUriAcquirer) { Authority = authority; var client = new DiscoveryClient(authority); if (discoveryPolicy != null) { client.Policy = discoveryPolicy; } Discovery = new DiscoveryCache(client); }
public DiscoveryCacheAccessor(IOptions <TokenExchangeOptions> tokenExchangeOptions) { _authorityMap = new ConcurrentDictionary <string, IDiscoveryCache>(); _tokenExchangeOptions = tokenExchangeOptions.Value; foreach (var authority in _tokenExchangeOptions.Authorities) { var dc = new DiscoveryCache(authority.Value, new DiscoveryPolicy() { ValidateEndpoints = false }); _authorityMap[authority.Key] = dc; } }
public HomeController(IHttpContextAccessor httpContextAccessor, IExternalSPAStore externalSpaStore, IConfiguration configuration, DiscoveryCache discoveryCache, IDistributedCache cache, ILogger <HomeController> logger) { _httpContextAccessor = httpContextAccessor; _configuration = configuration; _externalSpaStore = externalSpaStore; _discoveryCache = discoveryCache; _cache = cache; Logger = logger; }
public async Task <TokenResponse> Token(TokenRequestDTO tokenRequest) { try { var client = _clientFactory.CreateClient(); var cache = new DiscoveryCache(_config["AuthApiUrl"]); var disco = await cache.GetAsync() .ConfigureAwait(false); if (disco.IsError) { throw new Exception(disco.Error); } switch (tokenRequest.GrantType) { case "password": var passwordFlow = await client.RequestPasswordTokenAsync(new PasswordTokenRequest() { Address = disco.TokenEndpoint, ClientId = tokenRequest.ClientId, ClientSecret = tokenRequest.ClientSecret, Scope = tokenRequest.Scope, UserName = tokenRequest.Username, Password = tokenRequest.Password }).ConfigureAwait(false); return(passwordFlow); case "client_credentials": var clientCredentialsFlow = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest() { Address = disco.TokenEndpoint, ClientId = tokenRequest.ClientId, ClientSecret = tokenRequest.ClientSecret, Scope = tokenRequest.Scope, }).ConfigureAwait(false); return(clientCredentialsFlow); default: throw new Exception("grant_type is not supported"); } } catch (Exception ex) { _logger.LogError(ex, nameof(Token)); throw; } }
public TokenValidationService(ISettingService settingService, ILoggerService loggerService) { _settingService = settingService; _loggerService = loggerService; _discoveryCache = new DiscoveryCache(settingService.GetAuthorityUrl(), policy: new DiscoveryPolicy { ValidateIssuerName = false, ValidateEndpoints = false }); _audience = settingService.GetApiApplicationId(); _scope = settingService.GetApiScopeName(); AuthEnabled = settingService.EnableAuth(); }
//获取Token //获取Token public async Task <string> GetToken() { var client = _httpClientFactory.CreateClient("MI.Web"); string token = await Untity.StackRedis.Current.Get("ApiToken"); if (!string.IsNullOrEmpty(token)) { return(token); } try { //DiscoveryClient类:IdentityModel提供给我们通过基础地址(如:http://localhost:5000)就可以访问令牌服务端; //当然可以根据上面的restful api里面的url自行构建;上面就是通过基础地址,获取一个TokenClient;(对应restful的url:token_endpoint "http://localhost:5000/connect/token") //RequestClientCredentialsAsync方法:请求令牌; //获取令牌后,就可以通过构建http请求访问API接口;这里使用HttpClient构建请求,获取内容; DiscoveryPolicy discoveryPolicy = new DiscoveryPolicy { RequireHttps = false }; var cache = new DiscoveryCache(_configuration["ServiceAddress:Service.Identity"], client, discoveryPolicy); var disco = await cache.GetAsync(); if (disco.IsError) { throw new Exception(disco.Error); } var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = disco.TokenEndpoint, ClientId = "MI.Web", ClientSecret = "miwebsecret", Scope = "MI.Service" }); if (tokenResponse.IsError) { throw new Exception(tokenResponse.Error); } token = tokenResponse.AccessToken; int minute = tokenResponse.ExpiresIn / 60; await Untity.StackRedis.Current.Set("ApiToken", token, minute); } catch (Exception ex) { throw new Exception(ex.Message); } return(token); }
/// <summary> /// Get user makes a async calls to Identity server Userinfo of logged in user based on Bearer token. /// </summary> /// <returns>String email of the logged in user</returns> public async Task <string> GetUser() { var discoveryClient = new DiscoveryCache("http://localhost:5000"); var doc = await discoveryClient.GetAsync(); var client = new HttpClient(); var token = this._httpContextAccessor.HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", string.Empty);; var response = await client.GetUserInfoAsync(new UserInfoRequest { Address = doc.UserInfoEndpoint, Token = token }); return(response.Json != null?response.Json.TryGetString("email") : null); }
static async Task <DiscoveryDocumentResponse> GetDiscoveryResponse(string domain) { // discover endpoints from metadata var cache = new DiscoveryCache(domain); var disco = await cache.GetAsync(); if (disco.IsError) { Log.Error("Discovery error: {Error}", disco.Error); throw new Exception(disco.Error); } Log.Information("Issuer: {Issuer}", disco.Issuer); return(disco); }
public async Task <TokenIntrospectionResponse> IntrospectTokenAsync(string accessToken) { DiscoveryDocumentResponse disco = await DiscoveryCache.GetAsync(); if (disco.IsError) { throw new Exception(disco.Error); } TokenIntrospectionResponse result = await AuthHttpClient.IntrospectTokenAsync( new TokenIntrospectionRequest { Address = disco.IntrospectionEndpoint, ClientId = Configuration["ClientId"], ClientSecret = Configuration["ClientSecret"], Token = accessToken }); return(result); }
public async Task <UserInfoResponse> GetUserinfoAsync() { DiscoveryDocumentResponse disco = await DiscoveryCache.GetAsync(); if (disco.IsError) { throw new Exception(disco.Error); } UserInfoResponse response = await AuthHttpClient.GetUserInfoAsync(new UserInfoRequest { Address = disco.UserInfoEndpoint, Token = await ReadAsync() });; if (response.IsError) { throw new Exception(response.Error); } return(response); }