技术归档文章随笔一句话导航搜索关于

在 .NET Framework + MVC 中配置 OpenId 客户端

日期: 2021-01-15 分组: .NET 标签: .NET 2分钟 278字

Microsoft for.NET Framework 4发布的OpenID Connect标准库与OpenKeystone不兼容。OpenAthens已经发布了一个更新的库,可以连接到.NET4.5或更高版本的OpenAthens Keystone。其不支持早期版本。

开始

新建项目

首先我们建立一个 ASP.Net MVC 的项目并安装下列包.

1
Install-Package Microsoft.AspNet.Identity.Owin
2
Install-Package Microsoft.Owin.Host.SystemWeb
3
Install-Package OpenAthens.Owin.Security.OpenIdConnect

添加StartUp启动类

在项目根目录下添加 StartUp 类.

添加 > 新建项 搜索 startup,选择 OWIN StartUp 类 选型新建。

1
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
2
using Microsoft.Owin;
3
using Microsoft.Owin.Security;
4
using Microsoft.Owin.Security.Cookies;
5
using Owin;
6
using OpenAthens.Owin.Security.OpenIdConnect;
7
using System.Configuration;
8
9
[assembly: OwinStartup(typeof(WebApplication1.Startup))]
10
namespace WebApplication1
11
{
12
public partial class Startup
13
{
14
public void Configuration(IAppBuilder app)
15
{
22 collapsed lines
16
ConfigureAuth(app);
17
}
18
19
public void ConfigureAuth(IAppBuilder app)
20
{
21
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
22
app.UseCookieAuthentication(new CookieAuthenticationOptions());
23
var oidcOptions = new OpenIdConnectAuthenticationOptions
24
{
25
Authority = "授权服务器地址",
26
ClientId = "客户端Id",
27
ClientSecret = "客户端秘钥",
28
GetClaimsFromUserInfoEndpoint = true,
29
PostLogoutRedirectUri = "登出重定向uri",
30
RedirectUri = "重定向Uri",
31
ResponseType = OpenIdConnectResponseType.Code,
32
Scope = OpenIdConnectScope.OpenId // 按自己需要自行添加即可
33
};
34
app.UseOpenIdConnectAuthentication(oidcOptions);
35
}
36
}
37
}

如果启动时StartUp类没有加载,可在Web.config 配置文件 appSettings 节点下添加下列配置

1
<appSettings>
2
<add key="owin:AppStartup" value="<namespace>.Startup, <assembly>" />
3
</appSettings>

读取用户Claims信息

1
var claims = System.Security.Claims.ClaimsPrincipal.Current.Claims;

参考 https://docs.openathens.net/pages/releaseview.action?pageId=2228523#app-switcher

人应当是有理想的.
文章目录