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# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16
- .NET CORE DI 依赖注入 2023-09-27
- c# 模拟线性回归的示例 2023-03-14
- 如何使用C# 捕获进程输出 2023-03-10
- 在C# 8中如何使用默认接口方法详解 2023-03-29
- Unity Shader实现模糊效果 2023-04-27
- WPF使用DrawingContext实现绘制刻度条 2023-07-04
- Unity3D实现渐变颜色效果 2023-01-16
- Oracle中for循环的使用方法 2023-07-04
- user32.dll 函数说明小结 2022-12-26
