首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

.NET MVC的简单OpenID身份验证代码

您好!您提到的是一个关于.NET MVC的简单OpenID身份验证代码。以下是一个简单的示例,使用ASP.NET MVC 5和Owin中间件实现OpenID Connect身份验证。

  1. 首先,确保已安装以下NuGet包:
  • Microsoft.Owin.Security.OpenIdConnect
  • Microsoft.Owin.Security.Cookies
  • Microsoft.Owin.Host.SystemWeb
  1. 在Startup.cs文件中,添加以下代码:
代码语言:csharp
复制
using Microsoft.Owin;
using Owin;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;

[assembly: OwinStartup(typeof(YourNamespace.Startup))]

namespace YourNamespace
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = "your_client_id",
                Authority = "https://sts.windows.net/your_tenant_id",
                RedirectUri = "https://localhost:44300/",
                ResponseType = OpenIdConnectResponseType.CodeIdToken,
                Scope = OpenIdConnectScope.OpenIdProfile,
                PostLogoutRedirectUri = "https://localhost:44300/",
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer = false
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        // 处理身份验证失败的情况
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return System.Threading.Tasks.Task.FromResult(0);
                    }
                }
            });
        }
    }
}
  1. 在Global.asax.cs文件中,添加以下代码:
代码语言:csharp
复制
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace YourNamespace
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}
  1. 在AccountController.cs文件中,添加以下代码:
代码语言:csharp
复制
using System.Web.Mvc;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;

namespace YourNamespace.Controllers
{
    public class AccountController : Controller
    {
        public ActionResult SignIn()
        {
            return new ChallengeResult("OpenIdConnect", Url.Action("SignInCallback", "Account"));
        }

        public ActionResult SignInCallback()
        {
            return View();
        }

        public ActionResult SignOut()
        {
            HttpContext.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
            HttpContext.GetOwinContext().Authentication.SignOut(OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
            return Redirect("/");
        }

        private class ChallengeResult : HttpUnauthorizedResult
        {
            public ChallengeResult(string provider, string redirectUri)
            {
                LoginProvider = provider;
                RedirectUri = redirectUri;
            }

            public string LoginProvider { get; set; }
            public string RedirectUri { get; set; }

            public override void ExecuteResult(ControllerContext context)
            {
                var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
                context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
            }
        }
    }
}
  1. 在Views/Shared文件夹中,创建一个名为_LoginPartial.cshtml的新视图部分,并添加以下代码:
代码语言:html
复制
@if (Request.IsAuthenticated)
{
    using (Html.BeginForm("SignOut", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
    {
        @Html.AntiForgeryToken()
        <ul class="nav navbar-nav navbar-right">
            <li>
                @Html.ActionLink("Hello " + User.Identity.Name + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
            </li>
            <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
        </ul>
    }
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
        <li>@Html.ActionLink("Log in", "SignIn", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
    </ul>
}
  1. 在Views/Shared文件夹中,将以下代码添加到_Layout.cshtml文件中:
代码语言:html
复制

<!DOCTYPE html>

<html>

<head>

代码语言:txt
复制
<meta charset="utf-8" />
代码语言:txt
复制
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>@ViewBag.Title - My ASP.NET Application</title>

代码语言:txt
复制
@Styles.Render("~/Content/css")
代码语言:txt
复制
@Scripts.Render("~/bundles/modernizr")

</head>

<body>

代码语言:txt
复制
<div class="navbar navbar-inverse navbar-fixed-top">
代码语言:txt
复制
    <div class="container">
代码语言:txt
复制
        <div class="navbar-header">
代码语言:txt
复制
           <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
代码语言:txt
复制
                <span class="icon-bar"></span>
代码语言:txt
复制
                <span class="icon-bar"></span>
代码语言:txt
复制
                <span class="icon-bar"></span>
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券