Exemple #1
0
    protected virtual Task AddParametersToRequestAsync(IdentityClientConfiguration configuration, ProtocolRequest request)
    {
        foreach (var pair in configuration.Where(p => p.Key.StartsWith("[o]", StringComparison.OrdinalIgnoreCase)))
        {
            request.Parameters.Add(pair);
        }

        return(Task.CompletedTask);
    }
Exemple #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var server   = LinkedServerConfiguration.Load(Configuration);
            var idClient = IdentityClientConfiguration.Load(Configuration);

            ConfigureIdentityServices(server, idClient, services);

            ConfigureClientServices(server, services);

            services.AddScoped <IIdentityDataGetter, IdentityDataGetter>();

            ConfigureFinalServices(Configuration, services);
        }
Exemple #3
0
    public async Task DeviceLoginAsync()
    {
        var configuration = new IdentityClientConfiguration(
            CliUrls.AccountAbpIo,
            "role email abpio abpio_www abpio_commercial openid offline_access",
            "abp-cli",
            "1q2w3e*",
            OidcConstants.GrantTypes.DeviceCode
            );

        var accessToken = await AuthenticationService.GetAccessTokenAsync(configuration);

        File.WriteAllText(CliPaths.AccessToken, accessToken, Encoding.UTF8);
    }
 protected virtual async Task <DiscoveryDocumentResponse> GetDiscoveryResponse(IdentityClientConfiguration configuration)
 {
     using (var httpClient = HttpClientFactory.CreateClient(HttpClientName))
     {
         var request = new DiscoveryDocumentRequest
         {
             Address = configuration.Authority,
             Policy  =
             {
                 RequireHttps = configuration.RequireHttps
             }
         };
         IdentityModelHttpRequestMessageOptions.ConfigureHttpRequestMessage?.Invoke(request);
         return(await httpClient.GetDiscoveryDocumentAsync(request));
     }
 }
Exemple #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            Utils.Linked         = LinkedServerConfiguration.Load(Configuration);
            Utils.IdentityClient = IdentityClientConfiguration.Load(Configuration);

            services.AddHttpClient();

            services.AddMvc().AddNewtonsoftJson();

            services.AddResponseCompression(opts =>
            {
                opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                    new[] { "application/octet-stream" });
            });
        }
Exemple #6
0
        public async Task <IActionResult> GetAccessToken(UserLoginInfo login)
        {
            await ReplaceEmailToUsernameOfInputIfNeeds(login);

            var config = new IdentityClientConfiguration
            {
                Authority    = _configuration["AuthServer:Authority"],
                ClientId     = _configuration["AuthServer:ClientId"],
                ClientSecret = _configuration["AuthServer:ClientSecret"],
                GrantType    = OidcConstants.GrantTypes.Password,
                UserName     = login.UserNameOrEmailAddress,
                UserPassword = login.Password,
                Scope        = "offline_access IdentityService BackendAdminAppGateway AuditLogging BaseManagement OrganizationService"
            };

            string token = await _authenticator.GetAccessTokenAsync(config);

            return(Json(new { code = 1, data = token }));
        }
Exemple #7
0
    public async Task LoginAsync(string userName, string password, string organizationName = null)
    {
        var configuration = new IdentityClientConfiguration(
            CliUrls.AccountAbpIo,
            "role email abpio abpio_www abpio_commercial offline_access",
            "abp-cli",
            "1q2w3e*",
            OidcConstants.GrantTypes.Password,
            userName,
            password
            );

        if (!organizationName.IsNullOrWhiteSpace())
        {
            configuration["[o]abp-organization-name"] = organizationName;
        }

        var accessToken = await AuthenticationService.GetAccessTokenAsync(configuration);

        File.WriteAllText(CliPaths.AccessToken, accessToken, Encoding.UTF8);
    }
Exemple #8
0
        public static void ConfigureApp(IConfiguration configuration, IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            if (env?.IsDevelopment() == true)
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            app.UseAuthentication();

            app.UseOpenApi();

            var idClient = IdentityClientConfiguration.Load(configuration);

            app.UseSwaggerUi3(config =>
            {
                config.OAuth2Client = new NSwag.AspNetCore.OAuth2ClientSettings
                {
                    ClientId     = idClient?.ClientId ?? "",
                    ClientSecret = idClient?.ClientSecret ?? "",
                };
            });

            app.UseReDoc();

            app.UseCors();
            app.UseMvc();
        }
    protected virtual Task <ClientCredentialsTokenRequest> CreateClientCredentialsTokenRequestAsync(string tokenEndpoint, IdentityClientConfiguration configuration)
    {
        var request = new ClientCredentialsTokenRequest
        {
            Address      = tokenEndpoint,
            Scope        = configuration.Scope,
            ClientId     = configuration.ClientId,
            ClientSecret = configuration.ClientSecret
        };

        IdentityModelHttpRequestMessageOptions.ConfigureHttpRequestMessage?.Invoke(request);

        AddParametersToRequestAsync(configuration, request);

        return(Task.FromResult(request));
    }
Exemple #10
0
        public static void ConfigureIdentityServices(LinkedServerConfiguration server, IdentityClientConfiguration idClient, IServiceCollection services)
        {
            services.AddAuthorization();

            Helpers.UserHelper.RegisterUrl       = $"{server.Identity}/Identity/Account/Register";
            Helpers.UserHelper.IdentityManageUrl = $"{server.Identity}/Identity/Account/Manage";

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme          = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })
            .AddCookie("Cookies", options =>
            {
                options.Events = new Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationEvents
                {
                    // Auto refresh token when auth cookies
                    OnValidatePrincipal = async context =>
                    {
                        if (context.Properties?.Items[".Token.expires_at"] == null)
                        {
                            return;
                        }
                        var now = DateTimeOffset.UtcNow;

                        var tokenExpireTime = DateTime.Parse(context.Properties.Items[".Token.expires_at"]).ToUniversalTime();
                        var timeElapsed     = now.Subtract(context.Properties.IssuedUtc.Value);
                        var timeRemaining   = tokenExpireTime.Subtract(now.DateTime);
                        if (timeElapsed > timeRemaining)
                        {
                            // var oldAccessToken = context.Properties.Items[".Token.access_token"];
                            var oldRefreshToken = context.Properties.Items[".Token.refresh_token"];
                            var oldIdToken      = context.Properties.Items[".Token.id_token"];

                            using (HttpClient httpclient = new HttpClient {
                                BaseAddress = new Uri(server.Identity)
                            })
                            {
                                var tokenClient = new SDK.Identity.TokenClient(httpclient);
                                var tokens      = await tokenClient.RefreshToken(idClient.ClientId, idClient.ClientSecret, oldRefreshToken, oldIdToken);

                                if (tokens == null)
                                {
                                    context.RejectPrincipal();
                                }
                                else
                                {
                                    context.Properties.StoreTokens(tokens);
                                    context.ShouldRenew = true;
                                }
                            }
                        }
                    },
                };
            })
            .AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme         = "Cookies";
                options.Authority            = server.Identity;
                options.RequireHttpsMetadata = false;
                // options.UseTokenLifetime = true;

                options.ClientId     = idClient.ClientId;
                options.ClientSecret = idClient.ClientSecret;
                options.ResponseType = "code id_token";
                options.SaveTokens   = true;
                options.GetClaimsFromUserInfoEndpoint = true;

                options.Scope.Add("api");
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("email");
                options.Scope.Add("offline_access");
            });
        }
Exemple #11
0
 protected virtual string CalculateTokenCacheKey(IdentityClientConfiguration configuration)
 {
     return(IdentityModelTokenCacheItem.CalculateCacheKey(configuration));
 }
Exemple #12
0
 protected virtual string CalculateDiscoveryDocumentCacheKey(IdentityClientConfiguration configuration)
 {
     return(IdentityModelDiscoveryDocumentCacheItem.CalculateCacheKey(configuration));
 }
 public static string CalculateCacheKey(IdentityClientConfiguration configuration)
 {
     return(string.Join(",", configuration.Select(x => x.Key + ":" + x.Value)).ToMd5());
 }
Exemple #14
0
    protected virtual async Task <TokenResponse> RequestDeviceAuthorizationAsync(HttpClient httpClient, IdentityClientConfiguration configuration)
    {
        var discoveryResponse = await GetDiscoveryResponse(configuration);

        var request = new DeviceAuthorizationRequest()
        {
            Address      = discoveryResponse.DeviceAuthorizationEndpoint,
            Scope        = configuration.Scope,
            ClientId     = configuration.ClientId,
            ClientSecret = configuration.ClientSecret,
        };

        IdentityModelHttpRequestMessageOptions.ConfigureHttpRequestMessage?.Invoke(request);

        await AddParametersToRequestAsync(configuration, request);

        var response = await httpClient.RequestDeviceAuthorizationAsync(request);

        if (response.IsError)
        {
            throw new AbpException(response.ErrorDescription);
        }

        Logger.LogInformation($"First copy your one-time code: {response.UserCode}");
        Logger.LogInformation($"Open {response.VerificationUri} in your browser...");

        for (var i = 0; i < ((response.ExpiresIn ?? 300) / response.Interval + 1); i++)
        {
            await Task.Delay(response.Interval * 1000);

            var tokenResponse = await httpClient.RequestDeviceTokenAsync(new DeviceTokenRequest
            {
                Address      = discoveryResponse.TokenEndpoint,
                ClientId     = configuration.ClientId,
                ClientSecret = configuration.ClientSecret,
                DeviceCode   = response.DeviceCode
            });

            if (tokenResponse.IsError)
            {
                switch (tokenResponse.Error)
                {
                case "slow_down":
                case "authorization_pending":
                    break;

                case "expired_token":
                    throw new AbpException("This 'device_code' has expired. (expired_token)");

                case "access_denied":
                    throw new AbpException("User denies the request(access_denied)");
                }
            }

            if (!tokenResponse.IsError)
            {
                return(tokenResponse);
            }
        }

        throw new AbpException("Timeout!");
    }
Exemple #15
0
    protected virtual async Task <ClientCredentialsTokenRequest> CreateClientCredentialsTokenRequestAsync(IdentityClientConfiguration configuration)
    {
        var discoveryResponse = await GetDiscoveryResponse(configuration);

        var request = new ClientCredentialsTokenRequest
        {
            Address      = discoveryResponse.TokenEndpoint,
            Scope        = configuration.Scope,
            ClientId     = configuration.ClientId,
            ClientSecret = configuration.ClientSecret
        };

        IdentityModelHttpRequestMessageOptions.ConfigureHttpRequestMessage?.Invoke(request);

        await AddParametersToRequestAsync(configuration, request);

        return(request);
    }
Exemple #16
0
    protected virtual async Task <IdentityModelDiscoveryDocumentCacheItem> GetDiscoveryResponse(IdentityClientConfiguration configuration)
    {
        var tokenEndpointUrlCacheKey   = CalculateDiscoveryDocumentCacheKey(configuration);
        var discoveryDocumentCacheItem = await DiscoveryDocumentCache.GetAsync(tokenEndpointUrlCacheKey);

        if (discoveryDocumentCacheItem == null)
        {
            DiscoveryDocumentResponse discoveryResponse;
            using (var httpClient = HttpClientFactory.CreateClient(HttpClientName))
            {
                var request = new DiscoveryDocumentRequest
                {
                    Address = configuration.Authority,
                    Policy  =
                    {
                        RequireHttps = configuration.RequireHttps
                    }
                };
                IdentityModelHttpRequestMessageOptions.ConfigureHttpRequestMessage?.Invoke(request);
                discoveryResponse = await httpClient.GetDiscoveryDocumentAsync(request);
            }

            if (discoveryResponse.IsError)
            {
                throw new AbpException($"Could not retrieve the OpenId Connect discovery document! " +
                                       $"ErrorType: {discoveryResponse.ErrorType}. Error: {discoveryResponse.Error}");
            }

            discoveryDocumentCacheItem = new IdentityModelDiscoveryDocumentCacheItem(discoveryResponse.TokenEndpoint, discoveryResponse.DeviceAuthorizationEndpoint);
            await DiscoveryDocumentCache.SetAsync(tokenEndpointUrlCacheKey, discoveryDocumentCacheItem,
                                                  new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(configuration.CacheAbsoluteExpiration)
            });
        }

        return(discoveryDocumentCacheItem);
    }
 public static string CalculateCacheKey(IdentityClientConfiguration configuration)
 {
     return(configuration.Authority.ToLower().ToMd5());
 }
        protected virtual async Task <IdentityModelAuthenticationCacheItem> GetCacheItemAsync(IdentityClientConfiguration configuration)
        {
            var cacheKey = IdentityModelAuthenticationCacheItem.CalculateCacheKey(configuration.GrantType, configuration.ClientId, configuration.UserName);

            Logger.LogDebug($"IdentityModelCachedAuthenticationService.GetCacheItemAsync: {cacheKey}");

            var cacheItem = await Cache.GetAsync(cacheKey);

            if (cacheItem != null)
            {
                Logger.LogDebug($"Found in the cache: {cacheKey}");
                return(cacheItem);
            }

            Logger.LogDebug($"Not found in the cache: {cacheKey}");

            var tokenResponse = await GetAccessTokenResponseAsync(configuration);

            cacheItem = new IdentityModelAuthenticationCacheItem(tokenResponse.AccessToken);
            var cacheEntryOptions = new DistributedCacheEntryOptions
            {
                // 缓存前两分钟过期
                AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(tokenResponse.ExpiresIn - 120)
            };

            Logger.LogDebug($"Setting the cache item: {cacheKey}");
            await Cache.SetAsync(cacheKey, cacheItem, cacheEntryOptions);

            Logger.LogDebug($"Finished setting the cache item: {cacheKey}");

            return(cacheItem);
        }
 public static void Configure(IdentityClientConfiguration config)
 {
     Configure(config.ApplicationId, config.Address);
 }