怎么在ASP.NET 5中利用AzureAD实现一个单点登录功能?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
1,在config.json文件中添加AzureAD的配置信息:
"AzureAd": {
"ClientId": "[Enter the clientId of your application as obtained from portal, e.g. ba74781c2-53c2-442a-97c2-3d60re42f403]",
"Tenant": "[Enter the name of your tenant, e.g. contoso.onmicrosoft.com]",
"AadInstance": "https://login.microsoftonline.com/{0}", // This is the public instance of Azure AD
"PostLogoutRedirectUri": https://localhost:44322/
}2,修改project.json,引入OpenIdConnect的中间件:
"Microsoft.AspNet.Authentication.OpenIdConnect": "1.0.0-*"
3,在Startup中的ConfigureServices方法里面添加:
// OpenID Connect Authentication Requires Cookie Auth
services.Configure<ExternalAuthenticationOptions>(options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});4,在Startup中的Configure方法里面添加:
// Configure the OWIN Pipeline to use Cookie Authentication
app.UseCookieAuthentication(options =>
{
// By default, all middleware are passive/not automatic. Making cookie middleware automatic so that it acts on all the messages.
options.AutomaticAuthentication = true;
});
// Configure the OWIN Pipeline to use OpenId Connect Authentication
app.UseOpenIdConnectAuthentication(options =>
{
options.ClientId = Configuration.Get("AzureAd:ClientId");
options.Authority = String.Format(Configuration.Get("AzureAd:AadInstance"), Configuration.Get("AzureAd:Tenant"));
options.PostLogoutRedirectUri = Configuration.Get("AzureAd:PostLogoutRedirectUri");
options.Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = OnAuthenticationFailed,
};
});5,Startup的OnAuthenticationFailed方法为:
private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
notification.HandleResponse();
notification.Response.Redirect("/Home/Error?message=" + notification.Exception.Message);
return Task.FromResult(0);
}6,添加一个名为AccountController的Controller:
public class AccountController : Controller
{
// GET: /Account/Login
[HttpGet]
public IActionResult Login()
{
if (Context.User == null || !Context.User.Identity.IsAuthenticated)
return new ChallengeResult(OpenIdConnectAuthenticationDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = "/" });
return RedirectToAction("Index", "Home");
}
// GET: /Account/LogOff
[HttpGet]
public IActionResult LogOff()
{
if (Context.User.Identity.IsAuthenticated)
{
Context.Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationScheme);
Context.Authentication.SignOut(OpenIdConnectAuthenticationDefaults.AuthenticationScheme);
}
return RedirectToAction("Index", "Home");
}
}如果你遇到添加了 [Authorize] ,但是不能自动转到登录页面的情况,那么需要:
app.UseOpenIdConnectAuthentication(options => {
options.AutomaticAuthentication = true;
});看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。