RuoVea.OAuthServer 6.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package RuoVea.OAuthServer --version 6.0.0                
NuGet\Install-Package RuoVea.OAuthServer -Version 6.0.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="RuoVea.OAuthServer" Version="6.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add RuoVea.OAuthServer --version 6.0.0                
#r "nuget: RuoVea.OAuthServer, 6.0.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install RuoVea.OAuthServer as a Cake Addin
#addin nuget:?package=RuoVea.OAuthServer&version=6.0.0

// Install RuoVea.OAuthServer as a Cake Tool
#tool nuget:?package=RuoVea.OAuthServer&version=6.0.0                

RuoVea.OAuthServer

OAuth2.0 授权中心

使用示例

builder.Services.AddOAuthServerSetup<OAuthServerDemos>();

添加 鉴权方式

builder.Services
    .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme+1)
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
    {
        o.LoginPath = "/login";
    });

添加使用OAuth2.0授权 (这边的cookie和上面的cookie保持一致)

app.UseAuthentication();
app.UseAuthorization();

app.UseOAuthServerUri(CookieAuthenticationDefaults.AuthenticationScheme);/*添加使用OAuth2.0授权 */

配置文件
{
  /* Jwt配置 */
  "Jwt": {
    "ValidateIssuerSigningKey": true, // 是否验证密钥,bool 类型,默认true
    "IssuerSigningKey": "3c1cbc3f546eda35168c3aa3cb91780fbe703f0996c6d123ea96dc85c70bbc0a", // 密钥,string 类型,必须是复杂密钥,长度大于16
    "ValidateIssuer": true, // 是否验证签发方,bool 类型,默认true
    "ValidIssuer": "SecurityDemo.Authentication.JWT", // 签发方,string 类型
    "ValidateAudience": true, // 是否验证签收方,bool 类型,默认true
    "ValidAudience": "jwtAudience", // 签收方,string 类型
    "ValidateLifetime": true, // 是否验证过期时间,bool 类型,默认true,建议true
    "ExpiredTime": 1440, // 过期时间,long 类型,单位分钟,默认1440分钟(24小时)
    "ClockSkew": 5 // 过期时间容错值,long 类型,单位秒,默认5秒
  },
  /* OAuthServer配置 */
  "OAuthServer": [
    {
      "ClientUri": "https://host.docker.internal:5001", /* 客户端地址 */
      "ClientId": "liya00", /* 客户端Id */
      "ClientSecret": "12345678",
      "SignOutUrl": "/sign-out", /* 客户端登出地址 */
      "Score": "api1,api2"
    }
  ]
}

OAuthServerDemos继承重写 IOAuthServers 类的IssueUser方法userId是登录时候的用户id

public class OAuthServerDemos : IOAuthServers
{
   public OAuthServerDemos(IJwtHelper jwtHelper) : base(jwtHelper)
   {
   }
   /// <summary>
   /// 
   /// </summary>
   /// <param name="userId">已经登录的用户id,可以用此获取用户信息</param>
   /// <returns></returns>
   public override Dictionary<string, object> IssueUser(string userId)
   {
       Dictionary<string, object> claims = new Dictionary<string, object>();
       claims.Add(RuoVea.ExDto.ClaimConst.CLAINM_USERID, RuoVea.ExIdGen.IdGenerator.IdStr());
       claims.Add(ClaimTypes.Sid, userId);
       claims.Add(ClaimTypes.Role, "admin");
       claims.Add(RuoVea.ExDto.ClaimConst.CLAINM_NAME, "admin");
       return claims;
   }
}

登录实现代码参考

public class LoginController : Controller
{
    [HttpGet]
    public IActionResult Index(string returnUrl)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
        ViewBag.ReturnUrl = HttpUtility.UrlEncode(returnUrl);
        return View();
    }


    [HttpPost]
    public async Task<IActionResult> Index(string returnUrl, string type)
    {
        returnUrl = returnUrl ?? Url.Content("~/"); // 默认返回主页
        //cookie
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme+2, new ClaimsPrincipal(
                new ClaimsIdentity(
                        new Claim[]
                        {
                            new Claim(ClaimTypes.Sid,IdGenerator.Id+"",ClaimValueTypes.Integer64 ),
                            new Claim(ClaimTypes.Name,"admin"),
                            new Claim(ClaimTypes.NameIdentifier,Guid.NewGuid().ToString())
                        }, CookieAuthenticationDefaults.AuthenticationScheme + 2
                    )
                )
            );

        // todo 判断参数 合法就跳转 ,不合法就转首页
        return Redirect(returnUrl);
    }
}

API资源保护 使用如下

builder.Services
    .AddAuthenticationSetup();

builder.Services.AddAuthorization(options =>/* 添加授权策略 */
    {
        options.AddPolicy("OAuthAPI", policy =>/*OAuthAPI是策略名称 可在对于api接口使用 [Authorize("OAuthAPI")]*/
        {
            policy.RequireAuthenticatedUser();
            policy.RequireClaim("scope", "api2");/* api2是当前api资源的名称 */
        });
});

/* 注意app中需要添加如下 */
app.UseAuthentication();
app.UseAuthorization();

MVC客户端使用

请参考 RuoVea.OAuthClient 组件使用说明
Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
6.0.0.2 146 3/23/2024
6.0.0.1 126 3/23/2024
6.0.0 127 3/22/2024