Web API 基於ASP.NET Identity的Basic Authentication

來源:互聯網
上載者:User

標籤:

  今天給大家分享在Web API下,如何利用ASP.NET Identity實現基本認證(Basic Authentication),在部落格園子搜尋了一圈Web API的基本認證,基本都是做的Forms認證,很少有Claims認證(聲明式認證),而我們在用ASP.NET Identity實現登入,認證,授權的時候採用的是Claims認證。

  在Web API2.0中認證介面為IAuthenticationFilter,我們只需實現該介面就行。建立BasicAuthenticationAttribute抽象基類,實現IAuthenticationFilter介面:

 1 public abstract class BasicAuthenticationAttribute : Attribute, IAuthenticationFilter  2     { 3         protected abstract Task<IPrincipal> AuthenticateAsync(string userName, string password, HttpAuthenticationContext context, 4             CancellationToken cancellationToken); 5         public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) 6         { 7             context.Principal = null; 8             AuthenticationHeaderValue authenticationHeader = context.Request.Headers.Authorization; 9             if (authenticationHeader != null && authenticationHeader.Scheme == "Basic")10             {11                 if (!string.IsNullOrEmpty(authenticationHeader.Parameter))12                 {13                     Tuple<string, string> data = GetUserNameAndPassword(authenticationHeader.Parameter);14                     context.Principal = await AuthenticateAsync(data.Item1, data.Item2,context, cancellationToken);15                 }16             }17 18             if (context.Principal == null)19             {20                 context.ErrorResult = new UnauthorizedResult(new[] {new AuthenticationHeaderValue("Basic")},21                     context.Request);22             }23         }24         public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)25         {26             return Task.FromResult(0);27         }28         public bool AllowMultiple29         {30             get { return false; }31         }32         private Tuple<string, string> GetUserNameAndPassword(string authenticationParameter)33         {34             if (!string.IsNullOrEmpty(authenticationParameter))35             {36                 var data = Encoding.ASCII.GetString(Convert.FromBase64String(authenticationParameter)).Split(‘:‘);37                 return new Tuple<string, string>(data[0], data[1]);38             }39             return null;40         }41     }
View Code

其中Task<IPrincipal> AuthenticateAsync(string userName, string password, HttpAuthenticationContext context, CancellationToken cancellationToken)方法為抽象方法,使用者可以重載實現自己的認證方式,Forms認證,Windows認證,Claims認證等等都可以。

 AuthenticationHeaderValue authenticationHeader= context.Request.Headers.Authorization用於擷取HTTP要求標頭部的認證資訊。

 authenticationHeader.Scheme == "Basic"用於指定認證模式為基本認證。

authenticationHeader.Parameter使用者擷取使用者加密過後的使用者名稱和密碼。

如果認證不為空白,且是Basic認證,頭部參數不為空白,則調用認證的具體代碼,如果認證不通過,則調用HTTP認證內容相關的ErroResult屬性:

 context.ErrorResult = new UnauthorizedResult(new[] {new AuthenticationHeaderValue("Basic")},context.Request);設定了該屬性,瀏覽器則自動彈出使用者登入的視窗。要想瀏覽器自動彈出登入視窗,必須在WebApiConfig配置類中指定令牌身分識別驗證,即調用如下代碼:config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));否則無法彈出登入表單。

Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)方法在認證通過成功和失敗後都會調用此方法,你可以在這裡實現自己想要的邏輯,比如設定context.ErrorResult屬性,在這裡就不做處理了,因為AuthenticateAsync方法已經做了處理了。

GetUserNameAndPassword方法用於處理加密過後的使用者名稱和密碼。

接下來就是實現自己的認證邏輯了,這裡採用Asp.net Identity的Claims認證。

 1  public class IdentityBasicAuthenticationAttribute : BasicAuthenticationAttribute 2     { 3         protected override async Task<IPrincipal> AuthenticateAsync(string userName, string password, 4             HttpAuthenticationContext context, CancellationToken cancellationToken) 5         { 6             IPrincipal principal = null; 7             var userManager = context.Request.GetOwinContext().GetUserManager<AppUserManager>(); 8             var user = await userManager.FindAsync(userName, password); 9             if (user != null)10             {11                 ClaimsIdentity identity =12                     await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);13                 ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);14                 principal = claimsPrincipal;15             }16             return principal;17         }18     }
View Code

var userManager = context.Request.GetOwinContext().GetUserManager<AppUserManager>()用於當前的使用者管理員,使用者的增刪改查操作都依賴於此對象。

var user = await userManager.FindAsync(userName, password)使用者根據使用者名稱和密碼找到使用者。

ClaimsIdentity identity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie)建立使用者,然後 通過ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity)建立聲明,並且返回認證類型。

至於如何建立UserManager,如何通過Entityframwork來產生Asp.net Identity使用者,角色和認證相關表,這裡就不多說了,園子裡面多的去了。

記得在登入代碼中把使用者名稱和密碼加密後放到Cookie中,登陸後,在訪問某個需要認證的Action時候記得在HTTP要求標頭部中寫入Cookie資訊,這樣認證的Filter才能取到使用者資訊,登入建立Cookie程式碼片段如下:

            CookieHeaderValue cookie = new CookieHeaderValue("userToken", authorization)                    {                        Path = "/",                        Domain = Request.RequestUri.Host,                        Expires = DateTimeOffset.Now.AddDays(7)                    };                    responseMessage.Headers.AddCookies(new[] {cookie});

 客戶短AJax調用需要驗證的Action方法如下:

    function ajaxOp(url, type, data) {        $.ajax({            url: url,            type: type,            data: data,            beforeSend: function(xhr) {                xhr.setRequestHeader(‘Authorization‘, ‘Basic ‘ + $.cookie("userToken"));            }        });    }

 其中  beforeSend: function(xhr) {xhr.setRequestHeader(‘Authorization‘, ‘Basic ‘ + $.cookie("userToken"))屬性設定用於擷取Cookie資訊放到要求標頭部。

需要調用的Action記得加上  [IdentityBasicAuthentication]特性。

好了,就到這裡吧。

 

Web API 基於ASP.NET Identity的Basic Authentication

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.