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#中 Json 序列化去掉null值的方法 2022-11-18
- Unity shader实现高斯模糊效果 2023-01-16
- C# 解析XML和反序列化的示例 2023-04-14
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C#中的Linq to JSON操作详解 2023-06-08
- C#调用摄像头实现拍照功能的示例代码 2023-03-09