Esempio n. 1
0
        private static void Test1()
        {
            var httpClient = new HttpClient();
            var idClient   = new IdentityServerClient();
            var re         = idClient.GetPasswordTokenAsync(httpClient, "client1", "admin", "123").Result;

            Console.WriteLine("token:" + JsonUtil.SerializeIgnoreNull(re));

            if (re.Success())
            {
                httpClient.SetBearerToken(re.Data.AccessToken);
                var url = "http://localhost:5003/identity";

                var response = httpClient.GetAsync(url).Result;
                if (response.IsSuccessStatusCode)
                {
                    var content = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine(content);
                }
                else
                {
                    Console.WriteLine(response.StatusCode);
                }
            }
            else if ("invalid_grant".Equals(re.Msg))
            {
                Console.WriteLine("用户名或密码不对");
            }
        }
Esempio n. 2
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseCors(builder => builder
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowAnyOrigin()
                        .AllowCredentials());

            app.UseWebSockets();
            app.UseSignalR(routes => routes.MapDotNetifyHub());
            app.UseDotNetify(config =>
            {
                if (env.IsProduction())
                {
                    IEnumerable <SecurityKey> keys;
                    using (var client = HttpClientFactory.Create())
                    {
                        var identityServerSettings = _config.GetSection(IdentityServerSettings.SectionName).Get <IdentityServerSettings>();
                        keys = IdentityServerClient.GetIssuerSigningKeysAsync(client, identityServerSettings).GetAwaiter().GetResult();
                    }

                    // Middleware to do authenticate token in incoming request headers.
                    config.UseJwtBearerAuthentication(new TokenValidationParameters
                    {
                        IssuerSigningKeys        = keys,
                        ValidateIssuerSigningKey = true,
                        ValidateAudience         = false,
                        ValidateIssuer           = false,
                        ValidateLifetime         = true,
                        ClockSkew = TimeSpan.FromSeconds(0)
                    });

                    // Filter to check whether user has permission to access view models with [Authorize] attribute.
                    config.UseFilter <AuthorizeFilter>();
                }
                else
                {
                    config.UseDeveloperLogging();
                }
            });

            if (env.IsDevelopment())
            {
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true,
                    HotModuleReplacementClientOptions = new Dictionary <string, string> {
                        { "reload", "true" }
                    },
                });
            }

            app.UseResponseCompression();
            app.UseFileServer();
            app.Run(async(context) =>
            {
                using (var reader = new StreamReader(File.OpenRead("wwwroot/index.html")))
                    await context.Response.WriteAsync(reader.ReadToEnd());
            });
        }
Esempio n. 3
0
        private static void Test1()
        {
            var httpClient = new HttpClient();
            var idClient   = new IdentityServerClient();
            var re         = idClient.GetClientCredentialsTokenAsync(httpClient, "client1").Result;

            Console.WriteLine("token:" + JsonUtil.SerializeIgnoreNull(re));

            if (re.Success())
            {
                httpClient.SetBearerToken(re.Data.AccessToken);
                var url = "http://localhost:5003/identity";

                var response = httpClient.GetAsync(url).Result;
                if (response.IsSuccessStatusCode)
                {
                    var content = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine(content);
                }
                else
                {
                    Console.WriteLine(response.StatusCode);
                }
            }
        }
Esempio n. 4
0
        private TokenService()
        {
            _identityServerClient = new IdentityServerClient(
                identityServerBaseAddress: "https://localhost:5001",
                clientId: "TimeEntryUno",
                clientSecret: "A2W7aQVFQWRX",
                scope: "TimeEntryApi");

            // starts the initialization
            Initialization = InitializeAsync();
        }
Esempio n. 5
0
        public async Task <IActionResult> Validate([FromForm] string token)
        {
            using (var client = _httpClientFactory.CreateClient())
            {
                var response = await IdentityServerClient.IntrospectTokenAsync(client, _identityServerSettings, token);

                if (response.IsError)
                {
                    throw new Exception(response.Error);
                }

                return(response.IsActive ? new OkResult() : (IActionResult)Unauthorized());
            }
        }
Esempio n. 6
0
        public async Task <object> Post([FromForm] string username, [FromForm] string password)
        {
            if (username != "guest" || password != "dotnetify")
            {
                return(Unauthorized());
            }

            using (var client = _httpClientFactory.CreateClient())
            {
                var tokenResponse = await IdentityServerClient.RequestClientCredentialsTokenAsync(client, _identityServerSettings);

                return(new
                {
                    access_token = tokenResponse.AccessToken,
                    expires_in = tokenResponse.ExpiresIn
                });
            }
        }
        public Task Handle(DeviceRegisteredIntegrationEvent integrationEvent)
        {
            var client = new IdentityServerClient()
            {
                ClientId   = integrationEvent.Id.ToString(),
                ClientName = integrationEvent.Name.ToString(),
                UserId     = integrationEvent.UserCreated,
                AllowAccessTokensViaBrowser = true,
                AllowedGrantTypes           = GrantTypes.DeviceFlow.Select(agt => new ClientGrantType()
                {
                    GrantType = agt
                }).ToList(),
                RequireConsent = true,
                AllowedScopes  = new List <ClientScope>()
                {
                    new ClientScope()
                    {
                        Scope = IdentityServerConstants.StandardScopes.OpenId,
                    },
                    new ClientScope()
                    {
                        Scope = IdentityServerConstants.StandardScopes.Profile,
                    },
                    new ClientScope()
                    {
                        Scope = "smarthub"
                    }
                },
                ClientSecrets = new List <ClientSecret>
                {
                    new ClientSecret()
                    {
                        Value = "device".ToSha256()
                    }
                }
            };

            _repository.Add(client);
            _repository.Context.SaveChanges();
            return(Task.CompletedTask);
        }