AspNetCore中的IdentityServer4客户端认证模式实现

1 AuthorizationServer

using IdentityServer4;
using IdentityServer4.Models;

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryApiResources(Config.GetResource())
                .AddInMemoryClients(Config.GetClients());
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }


            app.UseIdentityServer();
        }
    }

    public class Config
    {
        public static IEnumerable<ApiResource> GetResource()
        {
            return new List<ApiResource>
            {
                new ApiResource("api","My Api"),
            };
        }

        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                new Client{
                    ClientId="client",
                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    ClientSecrets = {
                        new Secret("secret".Sha256())
                    },
                    AllowedScopes={ "api"},
                     },
            };
        }
    }

  2  AspNetCore RequestClient

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using IdentityServer4;
namespace IdentityServer.Client
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication("Bearer").AddIdentityServerAuthentication(options =>
            {
                options.Authority = "http://localhost:5000";
                options.RequireHttpsMetadata = false;
                options.ApiName = "api";
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();
            app.UseMvc();
        }
    }
}

  3 Console Client

using System;
using System.Net;
using System.Net.Http;
using IdentityModel;
using IdentityModel.Client;
using static IdentityModel.OidcConstants;

namespace ThirdPartyDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new HttpClient();
            var result = client.GetDiscoveryDocumentAsync("http://localhost:5000").Result;

            var token = client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest()
            {
                Address = result.TokenEndpoint,
                Scope = "api",
                ClientId = "client",
                ClientSecret = "secret",
                GrantType = GrantTypes.ClientCredentials
            }).Result;

            client.SetBearerToken(token.AccessToken);

            var r = client.GetAsync("http://localhost:5001/api/values").Result;
            Console.WriteLine("Hello World!");
        }

    }
}

  

原文地址:https://www.cnblogs.com/a121984376/p/10026717.html