.NET MVC 如何获取 openid
时间: 2024-05-15 22:12:39 浏览: 107
Programming+ASP.NET+MVC+4
要获取 OpenID,您需要使用 OpenID Connect 协议。下面是使用 .NET MVC 框架获取 OpenID 的一般步骤:
1. 注册 OpenID 提供者并获取客户端 ID 和客户端密钥。
2. 在 MVC 应用程序中安装 Microsoft.Owin.Security.OpenIdConnect NuGet 包。
3. 在 Startup.cs 文件中添加以下代码:
```csharp
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
using System.Configuration;
using System.Security.Claims;
using System.Threading.Tasks;
[assembly: OwinStartup(typeof(MyApp.Startup))]
namespace MyApp
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// 添加 cookie 认证中间件
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
// 添加 OpenID Connect 认证中间件
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = ConfigurationManager.AppSettings["ClientId"],
ClientSecret = ConfigurationManager.AppSettings["ClientSecret"],
Authority = ConfigurationManager.AppSettings["Authority"],
RedirectUri = ConfigurationManager.AppSettings["RedirectUri"],
ResponseType = "code id_token",
Scope = "openid profile email",
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name"
},
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = context =>
{
var identity = context.AuthenticationTicket.Identity;
var subjectClaim = identity.FindFirst(ClaimTypes.NameIdentifier);
var issuerClaim = identity.FindFirst("iss");
var nameClaim = identity.FindFirst(ClaimTypes.Name);
var emailClaim = identity.FindFirst(ClaimTypes.Email);
// 在这里将上述信息保存到数据库或 cookie 中
// ...
return Task.FromResult(0);
}
}
});
}
}
}
```
4. 在 AppSettings 中添加以下配置:
```xml
<appSettings>
<add key="ClientId" value="YOUR_CLIENT_ID" />
<add key="ClientSecret" value="YOUR_CLIENT_SECRET" />
<add key="Authority" value="https://YOUR_AUTHORITY_URL" />
<add key="RedirectUri" value="http://localhost:port/YOUR_REDIRECT_URI" />
</appSettings>
```
5. 在控制器中添加以下代码以启动 OpenID Connect 认证流程:
```csharp
public class AccountController : Controller
{
public void SignIn()
{
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
public void SignOut()
{
HttpContext.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
HttpContext.GetOwinContext().Authentication.SignOut(OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
}
```
这些步骤应该可以帮助您在 .NET MVC 应用程序中获取 OpenID。
阅读全文