以下是一个使用ASP.NET OAuth实现Microsoft单租户登录的示例代码:
在Visual Studio中创建一个新的ASP.NET Web应用程序项目。
在App_Start文件夹中创建一个名为"Startup.Auth.cs"的新类文件,并添加以下代码:
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
[assembly: OwinStartup(typeof(YourAppName.Startup))]
namespace YourAppName
{
public class Startup
{
// 配置应用程序的OAuth验证
public void Configuration(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = "YourClientId", // 替换为你的应用程序的Client ID
Authority = "https://login.microsoftonline.com/YourTenantId/v2.0", // 替换为你的租户ID
RedirectUri = "http://localhost:xxxxx", // 替换为你的重定向URI
Scope = "openid email profile", // 替换为你的所需范围
ResponseType = "id_token",
TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false // 禁用Issuer验证
}
});
}
}
}
using Microsoft.Owin.Security;
using System.Web;
using System.Web.Mvc;
namespace YourAppName.Controllers
{
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,
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
}
using System.Web.Mvc;
namespace YourAppName.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
@{
Layout = null;
}
SignIn
Sign in to YourAppName
@{
Layout = null;
}
Index
Welcome to YourAppName
现在你可以运行应用程序,点击"Sign in with Microsoft"按钮进行登录,然后在首页点击"Sign out"按钮进行登出。注意替换代码中的"YourClientId"、"YourClientSecret"、"YourTenantId"和重定向URI为你自己的值。