Asp.Net Core2.0 中 OAuth2.0

Security and Authorization

由于项目中需要使用到core2.0中才提供的一些方法及类库。故将web项目从netcoreapp1.1升级到2.0,类库项目从netstandard1.6升级到netstandard2.0。很多之前比较麻烦的事情也是迎刃而解了,比如 Type类 相关的反射在旧版1.6中是没有直接获取到特性Attributes的方法GetCustomAttributes()的。2.0中比之前的更加完善 。更新完配置,还原完包,也带来了不少的问题哦。本章主要就是分享一下 security and authorization 遇到的问题。花了我三四个小时去更新代码。

StartUp

1.1 版本的写法

netcoreapp1.1中,用户身份验证模块是通过中间件的形式。

//OAuth2.0 配置
app.UseLyAuthentication(new LyOptions()
{
   ClientId = Configuration.GetSection(nameof(LyOptions))["ClientId"],
   ClientSecret = Configuration.GetSection(nameof(LyOptions))["ClientSecret"],
   AuthorizationEndpoint = Configuration.GetSection(nameof(LyOptions))["AuthorizationEndpoint"],
   TokenEndpoint = Configuration.GetSection(nameof(LyOptions))["TokenEndpoint"],
   UserInformationEndpoint = Configuration.GetSection(nameof(LyOptions))["UserInformationEndpoint"]
});

2.0 版本的写法

netcoreapp2.0 中, 用户身份验证模块是通过服务加入的形式。

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(opt =>{
    opt.LoginPath = new PathString("/signin");
    opt.LogoutPath = new PathString("/signout");
    //  opt.Cookie = new CookieBuilder
    //  {
    //      Domain = "oauthsecrets",
    //      Path = "/",
    //      Expiration = new System.TimeSpan(8, 0, 0)
    //  };
})
.AddTongCheng(opt =>
{
    opt.ClientId = Configuration.GetSection("LyOptions")["ClientId"];
    opt.ClientSecret = Configuration.GetSection("LyOptions")["ClientSecret"];
    opt.AuthorizationEndpoint = Configuration.GetSection("LyOptions")["AuthorizationEndpoint"];
    opt.TokenEndpoint = Configuration.GetSection("LyOptions")["TokenEndpoint"];
    opt.UserInformationEndpoint = Configuration.GetSection("LyOptions")["UserInformationEndpoint"];
    opt.TicketCreated = ClaimsExtensions.SetWalleUser;
    opt.SaveTokens = true;
});