1、添加nuget引用IdentityModelIdentityServer4.AccessTokenValidationMicrosoft.AspNetCore.Authentication.CookiesMicrosoft.AspNetCore.Authentication.OpenIdConnectMicrosoft.AspNetCore.Mvc.Razor.RuntimeComp...
1、添加nuget引用
IdentityModel
IdentityServer4.AccessTokenValidation
Microsoft.AspNetCore.Authentication.Cookies
Microsoft.AspNetCore.Authentication.OpenIdConnect
Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
System.IdentityModel.Tokens.Jwt
2、在Startup类里添加如下代码
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddMvc().AddRazorRuntimeCompilation(); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); services.AddAuthentication(options => { options.DefaultScheme = "Cookies"; options.DefaultChallengeScheme = "oidc"; }) .AddCookie(options => { options.Cookie.Name = "Cookies"; }) .AddOpenIdConnect("oidc", options => { options.SignInScheme = "Cookies"; options.Authority = "http://localhost:5000"; options.RequireHttpsMetadata = false; options.ClientId = "localMvcCore"; options.ClientSecret = "111111"; options.ResponseType = "code id_token"; options.Scope.Clear(); options.Scope.Add("openid"); options.Scope.Add("profile"); options.SaveTokens = true; }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } }
上面的options.ClientSecret对应服务器端的密码,服务器端是:ClientSecrets = { new Secret("111111".Sha256()) },所以这里是:111111
3、添加 [Authorize] 属性
在需要保护的controller或action上添加[Authorize]
4、获取用户id
var userId = HttpContext.User.FindFirst("sub")?.Value;
5、在identityserver4服务器端的appsetting里添加
备注:如果不是我们项目的,就没有这个节点,这个是我们自定义的,方便维护节点用的,添加的时候注意ClientType,不要写"Mvc4",那个是用于.net framework web的。
"MvcClients": [ { "ClientName": "本地.netCoreMvc测试环境", "ClientId": "localMvcCore", "ClientUrl": "https://localhost:44361", "ClientType": "MvcCore" }
至此接入完成。
本文标题为:Identityserver4之.net core web客户端的接入过程
基础教程推荐
- C# List实现行转列的通用方案 2022-11-02
- C#类和结构详解 2023-05-30
- C# windows语音识别与朗读实例 2023-04-27
- unity实现动态排行榜 2023-04-27
- linux – 如何在Debian Jessie中安装dotnet core sdk 2023-09-26
- ZooKeeper的安装及部署教程 2023-01-22
- C# 调用WebService的方法 2023-03-09
- winform把Office转成PDF文件 2023-06-14
- C#控制台实现飞行棋小游戏 2023-04-22
- 一个读写csv文件的C#类 2022-11-06