IdentityServer4

这里呢只是简单的记录一下步骤,具体还是要阅读官方文档的>>直达官方文档

这里是代码部分:

第一部分:验证服务器

PowerShell中使用的代码=>

dotnet new -i IdentityServer4.Templates // install templates :select (IdentityServer4 with In-Memory Stores and Test Users===>is4inmem)
dotnet new is4inmem --name IdentityProvider //然后打开配置好的工程即可
</font size = 5>

第二部分:代理请求客户端

static async Task Main(string[] args)
{

var httpRequest = new HttpClient();
var httpResponse = await httpRequest.GetDiscoveryDocumentAsync("https://localhost:5001/");
//Console.WriteLine(httpResponse.Json.ToString());
if (httpResponse.IsError)
{
Console.WriteLine(httpResponse.Error);
return;
}
//var tokenResponse = await httpRequest.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest()
//{
// Address=httpResponse.TokenEndpoint,
// ClientId= "m2m.client",
// ClientSecret = "511536EF-F270-4058-80CA-1C89C192F69A"
//});
var tokenResponseForPassword = await httpRequest.RequestPasswordTokenAsync(new PasswordTokenRequest()
{
Address=httpResponse.TokenEndpoint,
ClientId="client",
ClientSecret = "secret",
Scope="api1",
UserName="lihuahua",
Password="666666+"
});
Console.WriteLine(tokenResponseForPassword.Json);
if (tokenResponseForPassword.IsError)
{
return;
}
for (int i = 0; i < 1000; i++)
{
var httpApiRequest = new HttpClient();
httpApiRequest.SetBearerToken(tokenResponseForPassword.AccessToken);
var response = await httpApiRequest.GetAsync("http://localhost:5003/identity");
if (!response.IsSuccessStatusCode)
{
return;
}
else
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
httpApiRequest.Dispose();
}
httpRequest.Dispose();
Console.WriteLine("Finshed!");
Console.ReadLine();
}

第三部分:api服务器端:StartUp配置

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.AddControllers();
services.AddMvcCore()
.AddAuthorization();

services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://localhost:5001";
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
// options.Audience = "api1";
});
}

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

//app.UseHttpsRedirection();

app.UseRouting();
//adds the authentication middleware to the pipeline so authentication will be performed automatically on every call into the host.
log.LogInformation("身份验证");
app.UseAuthentication();
//adds the authorization middleware to make sure, our API endpoint cannot be accessed by anonymous clients
log.LogInformation("授权验证");
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}

api服务器端:Program配置(在这里修改了监听的端口,和控制台日志的修改)

public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
.Enrich.FromLogContext()
// uncomment to write to Azure diagnostics stream
//.WriteTo.File(
// @"D:\home\LogFiles\Application\identityserver.txt",
// fileSizeLimitBytes: 1_000_000,
// rollOnFileSizeLimit: true,
// shared: true,
// flushToDiskInterval: TimeSpan.FromSeconds(1))
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Code)
.CreateLogger();
CreateHostBuilder(args).Build().Run();

}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup()
.UseUrls("http://localhost:5003");
});
}

api服务器端:控制器里的代码是官方文档的

[Authorize]
[Route("identity")]
public class HomeController : Controller
{

[HttpGet]
public IActionResult Get()
{
return new JsonResult(
from c in User.Claims select new { c.Type, c.Value });
}
}

posted @ 2020-12-06 19:29  李花花小番茄  阅读(91)  评论(0)    收藏  举报