OAuth是一个关于授权(authorization)的开放网络标准,它无法提供完善的身份认证功能,OpenID Connect是一个以用户为中心的数字身份识别框架,两组组合成为OIDC服务,它在OAuth2上构建了一个身份层,我们自己也能定义一个属于自己的OIDC服务
- OIDC使得身份认证可以作为一个服务存在。
- OIDC可以很方便的实现SSO(跨顶级域)。
- OIDC兼容OAuth2,可以使用Access Token控制受保护的API资源。
- OIDC可以兼容众多的IDP作为OIDC的OP来使用。
- OIDC的一些敏感接口均强制要求TLS,除此之外,得益于JWT,JWS,JWE家族的安全机制,使得一些敏感信息可以进行数字签名、加密和验证,进一步确保整个认证过程中的安全保障。
1.Auth运行流程
(A)用户打开客户端以后,客户端要求用户给予授权。
(B)用户同意给予客户端授权。
(C)客户端使用上一步获得的授权,向认证服务器申请令牌。
(D)认证服务器对客户端进行认证以后,确认无误,同意发放令牌。
(E)客户端使用令牌,向资源服务器申请获取资源。
(F)资源服务器确认令牌无误,同意向客户端开放资源。
3.在.net core中实现 Microsoft 身份验证登录 其他服务商都原理都一样 只是参数会发生一些变化
https://portal.azure.com/ 登录创建租户后即可
首先注册一个Azure app,获取对应的参数 添加到appsetting.json当中
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "",
"TenantId": "",
"ClientId": "",
"CallbackPath": "/signin-oidc"
}
创建配置类
public class AzureAdOption
{
public string ClientId { get; set; }
public string Instance { get; set; }
public string Domain { get; set; }
public string TenantId { get; set; }
public string CallbackPath { get; set; }
}
配置Azure选项
private class ConfigureAzureOptions : IConfigureNamedOptions<OpenIdConnectOptions>
{
private readonly AzureAdOption _azureOptions;
public ConfigureAzureOptions(IOptions<AzureAdOption> azureOptions)
{
_azureOptions = azureOptions.Value;
}
public void Configure(string name, OpenIdConnectOptions options)
{
options.ClientId = _azureOptions.ClientId;
options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}";
options.UseTokenLifetime = true;
options.CallbackPath = _azureOptions.CallbackPath;
options.RequireHttpsMetadata = false;
}
public void Configure(OpenIdConnectOptions options)
{
Configure(Options.DefaultName, options);
}
}
接下来开始授权验证
public static void AddMicrosoftAuthentication(this IServiceCollection services, IConfiguration configuration)
{
var authentication = new AzureAdOption();
configuration.Bind("AzureAd", authentication);
services.Configure<AzureAdOption>(configuration.GetSection("AzureAd"));
services.Configure<AzureAdOption>(option =>
{
option.CallbackPath = authentication.CallbackPath;
option.ClientId = authentication.ClientId;
option.Domain = authentication.Domain;
option.Instance = authentication.Instance;
option.TenantId = authentication.TenantId;
}).AddSingleton<IConfigureOptions<OpenIdConnectOptions>, ConfigureAzureOptions>();
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
}).AddOpenIdConnect().AddCookie();
}
最后在启动项ConfigureServices中注入我们的验证 还有Configure开启认证授权 完成后我们在控制器中就可以用 [Authorize] 来验证了
//注入Session
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
});
//注入验证方法
services.AddMicrosoftAuthenticaton(_configuration);