IdentityServer4实战详解

一、参考文章

注意IDS4的版本与之前的版本有所不同,这些文档有些是旧版本,需要细微调整,会在下文给予标注

1.OAuth2.0和OCID讲解

IDS4官方文档
IDS4官方文档

晓晨Master的概念详解
概念理解

*Hunter的项目实战
实战项目

阮一峰的网络日志
阮一峰的网络日志

二、个人总结

基于使用的net6版本

1.Implicit隐式流程认证服务器端

Nuget包安装
在这里插入图片描述

(1)创建IDS4认证服务器和客户端

创建认证服务器MVC模板
创建MVC客户端(两个都选择MVC模板)
在这里插入图片描述
分别打开认证服务器和客户端的Propertieswen文件中launchSetting.json修改启动地址
客户端是5001 ,认证服务器设置为5000
在这里插入图片描述

项目启动以项目启动
在这里插入图片描述

(2)修改IDS4认证服务器的视图UI

  1. 进入认证服务器的项目的根目录,键入CMD界面
    在这里插入图片描述
  2. 创建Ids4的UI界面
    执行dotnet new is4ui --force,–force是强制覆盖原有的mvc文件,
    如果没有模板,先下载模板, 1)安装模板命令:dotnet new -i IdentityServer4.Templates
  3. 现在的目录结构
    在这里插入图片描述
    删除Controller文件因为Quickstart文件中也有HomeController,会有多个端点,出现错误

(3)添加资源配置

  1. 创建Config.cs文件
    public static class Config
    {
        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>
            {
                new ApiResource("api1", "My API")
            };
        }
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>()
            {
                 new Client(){
                    ClientId="client1",
                    ClientName="mvc client",
                    AllowedGrantTypes=GrantTypes.Implicit,
                    RedirectUris={"http://localhost:5001/signin-oidc"},
                    PostLogoutRedirectUris={"http://localhost:5001/signout-callback-oidc"},
                    FrontChannelLogoutUri = "http://localhost:5000/signout-idsrv",
                    AllowAccessTokensViaBrowser=true,
                    AllowedScopes=new List<string>{
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile
                    }
                }
            };
        }

        public static List<TestUser> GetUsers()
        {
            return new List<TestUser>
            {
                new TestUser
                {
                    SubjectId = "1",
                    Username = "alice",
                    Password = "password"
                },
                new TestUser
                {
                    SubjectId = "2",
                    Username = "bob",
                    Password = "password"
                }
            };
        }
        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
            };
        }
    }

(4)Program配置(相当与3.1的Startup配置,6.0Startup类被删了)

Program.CS


var builder = WebApplication.CreateBuilder(args);

//部分浏览器版本较新SameSite不设置会出现报错,
builder.Services.Configure<CookiePolicyOptions>(options =>
{
    options.MinimumSameSitePolicy = SameSiteMode.Lax;
    options.OnAppendCookie = cookieContext =>
       CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
    options.OnDeleteCookie = cookieContext =>
       CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
});
static void CheckSameSite(HttpContext httpContext, CookieOptions options)
{
    if (options.SameSite == SameSiteMode.None)
    {
        var userAgent = httpContext.Request.Headers["User-Agent"].ToString();

        options.SameSite = SameSiteMode.Lax;
    }
}


// Add services to the container.

//添加mvc,后面登录需要
builder.Services.AddMvc();
builder.Services.AddControllersWithViews();

//这部分是对资源的配置
builder.Services.AddIdentityServer()
    //添加身份资源配置
    .AddInMemoryIdentityResources(Config.GetIdentityResources())
      //设置证书
      .AddDeveloperSigningCredential()
      //添加API资源设置
      .AddInMemoryApiResources(Config.GetApiResources())
      //推荐测试用户
      .AddTestUsers(Config.GetUsers())
      //添加客户端
      .AddInMemoryClients(Config.GetClients());
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseCookiePolicy();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();


2.Implicit隐式流客户端

(1)修改Program


var builder = WebApplication.CreateBuilder(args);

builder.Services.Configure<CookiePolicyOptions>(options =>
{
    options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
    options.OnAppendCookie = cookieContext =>
        SetSameSite(cookieContext.Context, cookieContext.CookieOptions);
    options.OnDeleteCookie = cookieContext =>
        SetSameSite(cookieContext.Context, cookieContext.CookieOptions);
});
//部分浏览器版本较新SameSite不设置会出现报错,
void SetSameSite(HttpContext httpContext, CookieOptions options)
{
    if (options.SameSite == SameSiteMode.None)
    {
        if (httpContext.Request.Scheme != "https")
        {
            options.SameSite = SameSiteMode.Unspecified;
        }
    }
}
builder.Services.Configure<CookiePolicyOptions>(options =>
{
    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
    options.CheckConsentNeeded = context => true;
    options.MinimumSameSitePolicy = SameSiteMode.None;
});

builder.Services.AddMvc();
//AddAuthentication将认证服务添加到DI
builder.Services.AddAuthentication(options => {
    options.DefaultScheme = "Cookies";//设置Cookies为主要认证手段
    options.DefaultChallengeScheme = "oidc";//当需要登录时使用OpenID Connect方案
})
.AddCookie("Cookies")//使用AddCookie添加可以处理cookie的处理程序。
.AddOpenIdConnect("oidc", options => {
    options.SignInScheme = "Cookies";
    options.Authority = "http://localhost:5000";
    options.RequireHttpsMetadata = false;
    options.ClientId = "client1";
    options.SaveTokens = true;
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

//添加Cookie,不让报错,无法正常使用
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
// 看登录的用户是否有权限
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();


(2)添加认证特性

自带的HomeController中添加,当未登录用户访问触发认证流程
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有诗亦有远方

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值