程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> ASP.NET 5中使用AzureAD實現單點登錄

ASP.NET 5中使用AzureAD實現單點登錄

編輯:ASP.NET基礎

題記:在ASP.NET 5中雖然繼續可以沿用ASP.NET Identity來做驗證授權,不過也可以很容易集成支持標准協議的第三方服務,比如Azure Active Directory。

其實,在ASP.NET 5中集成AzureAD,利用其進行驗證和授權,是非常簡單的。因為:首先Azure Active Directory提供了OAuth2.0、OpenId Connect 1.0、SAML和WS-Federation 1.2標准協議接口;其次微軟在ASP.NET 5中移植了集成OpenId Connect的OWIN中間件。所以,只要在ASP.NET 5項目中引用"Microsoft.AspNet.Authentication.OpenIdConnect"這個包,並正確配置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");
  }
}

以上代碼也可以到我Fork的完整示例項目中找到:https://github.com/heavenwing/WebApp-OpenIdConnect-AspNet5

【更新:2015-07-16】
如果你遇到添加了 [Authorize] ,但是不能自動轉到登錄頁面的情況,那麼需要:

app.UseOpenIdConnectAuthentication(options => {
  options.AutomaticAuthentication = true;
});

具體見:https://github.com/aspnet/Security/issues/357#issuecomment-120834369

以上所述就是本文的全部內容了,希望大家能夠喜歡。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved