2016-06-09 51 views
3

我有我的C#的Web API以下要求2服務:的Web API 2個自定義身份驗證的OAuth承載令牌

該服務通過電子郵件的組合,並且被髮送到他們的收件箱的臨時密碼驗證用戶,一個身份驗證的因素。 我需要在這個身份驗證機制中生成OAuth承載標記以保護服務,並使用標準的ASP.NET授權機制通過某種[Authorize]屬性檢查每個請求對應的令牌。

我已經成功地實現了這些步驟

  1. 用戶請求密碼
  2. 系統生成和電子郵件密碼,以用戶30天到期
  3. 用戶與電子郵件+密碼
  4. 系統檢查密碼的有效性驗證

但我不知道如何開始實施剩餘ING步驟

  • 如果密碼有效,系統生成的OAuth承載令牌
  • 的OAuth只要承載令牌持續作爲密碼有效期
  • 使用ASP.NET身份的授權屬性以執行認證和授權檢查
  • 使用OWIN安全和OAuth中間件創建令牌
  • 使用基於聲明的授權和連載債權分爲令牌
  • 引用的過程僅描述瞭如何使用ASP.NET Identity個人用戶帳戶作爲身份驗證手段,而不是我想要如何進行身份驗證。

    http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api

    我確實需要通過檢查電子郵件和密碼進行身份驗證。

    回答

    0

    有關如何在asp.net Web API中設置身份驗證的詳細說明,請參閱此post。這應該給你一個關於如何在Web API中實現對你的需求的認證的好主意。如果您有任何疑問或問題,請告訴我。

    謝謝, Soma。

    +1

    鏈接是很好的補充,但不應該是必要的答案。請回答這裏的問題。 – ricksmt

    4

    我在類似的情況下工作,並實施了驗證過濾器(IAuthenticationFilter)和從OAuthAuthorizationServerProvider繼承的自定義類。就我而言,我需要使用OAuth和傳統令牌對請求進行身份驗證。我相信在你的情況下,你需要定製AuthenticationFilter。請參閱下面的AuthenticationFilter的例子:

    public class MyAuthenticationFilter : IAuthenticationFilter 
    { 
        private readonly string _authenticationType; 
    
        /// <summary>Initializes a new instance of the <see cref="HostAuthenticationFilter"/> class.</summary> 
        /// <param name="authenticationType">The authentication type of the OWIN middleware to use.</param> 
        public MyAuthenticationFilter(string authenticationType) 
        { 
         if (authenticationType == null) 
         { 
          throw new ArgumentNullException("authenticationType"); 
         } 
    
         _authenticationType = authenticationType; 
        } 
    
        /// <summary>Gets the authentication type of the OWIN middleware to use.</summary> 
        public string AuthenticationType 
        { 
         get { return _authenticationType; } 
        } 
    
        /// <inheritdoc /> 
        public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) 
        { 
         if (context == null) 
         { 
          throw new ArgumentNullException("context"); 
         } 
    
         HttpRequestMessage request = context.Request; 
    
         if (request == null) 
         { 
          throw new InvalidOperationException("Request mut not be null"); 
         } 
    
    
         //In my case, i need try autenticate the request with BEARER token (Oauth) 
         IAuthenticationManager authenticationManager = GetAuthenticationManagerOrThrow(request); 
    
         cancellationToken.ThrowIfCancellationRequested(); 
         AuthenticateResult result = await authenticationManager.AuthenticateAsync(_authenticationType); 
         ClaimsIdentity identity = null; 
    
         if (result != null) 
         { 
          identity = result.Identity; 
    
          if (identity != null) 
          { 
           context.Principal = new ClaimsPrincipal(identity); 
          } 
         } 
         else 
         { 
          //If havent success with oauth authentication, I need locate the legacy token 
    //If dont exists the legacy token, set error (will generate http 401) 
          if (!request.Headers.Contains("legacy-token-header")) 
           context.ErrorResult = new AuthenticationFailureResult(Resources.SAUTH_ERROR_LEGACYTOKENNOTFOUND, request); 
          else 
          { 
           try 
           { 
            var queryString = request.GetQueryNameValuePairs(); 
            if (!queryString.Any(x => x.Key == "l")) 
             context.ErrorResult = new AuthenticationFailureResult(Resources.SAUTH_ERROR_USERTYPENOTFOUND, request); 
            else 
            { 
             var userType = queryString.First(x => x.Key == "l").Value; 
             String token = HttpUtility.UrlDecode(request.Headers.GetValues("tk").First()); 
    
             identity = TokenLegacy.ValidateToken(token, userType); 
             identity.AddClaims(userType, (OwinRequest) ((OwinContext)context.Request.Properties["MS_OwinContext"]).Request); 
             if (identity != null) 
             { 
              context.Principal = new ClaimsPrincipal(identity); 
             } 
            } 
    
           } 
           catch (Exception e) 
           { 
            context.ErrorResult = new AuthenticationFailureResult(e.Message, request); 
           } 
          } 
         } 
        } 
    
    
        /// <inheritdoc /> 
        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) 
        { 
         if (context == null) 
         { 
          throw new ArgumentNullException("context"); 
         } 
    
         HttpRequestMessage request = context.Request; 
    
         if (request == null) 
         { 
          throw new InvalidOperationException("Request mut not be null"); 
         } 
    
         IAuthenticationManager authenticationManager = GetAuthenticationManagerOrThrow(request); 
    
         // Control the challenges that OWIN middleware adds later. 
         authenticationManager.AuthenticationResponseChallenge = AddChallengeAuthenticationType(
          authenticationManager.AuthenticationResponseChallenge, _authenticationType); 
    
         return TaskHelpers.Completed(); 
        } 
    
        /// <inheritdoc /> 
        public bool AllowMultiple 
        { 
         get { return true; } 
        } 
    
        private static AuthenticationResponseChallenge AddChallengeAuthenticationType(
         AuthenticationResponseChallenge challenge, string authenticationType) 
        { 
         Contract.Assert(authenticationType != null); 
    
         List<string> authenticationTypes = new List<string>(); 
         AuthenticationProperties properties; 
    
         if (challenge != null) 
         { 
          string[] currentAuthenticationTypes = challenge.AuthenticationTypes; 
    
          if (currentAuthenticationTypes != null) 
          { 
           authenticationTypes.AddRange(currentAuthenticationTypes); 
          } 
    
          properties = challenge.Properties; 
         } 
         else 
         { 
          properties = new AuthenticationProperties(); 
         } 
    
         authenticationTypes.Add(authenticationType); 
    
         return new AuthenticationResponseChallenge(authenticationTypes.ToArray(), properties); 
        } 
    
        private static IAuthenticationManager GetAuthenticationManagerOrThrow(HttpRequestMessage request) 
        { 
         Contract.Assert(request != null); 
    
         var owinCtx = request.GetOwinContext(); 
         IAuthenticationManager authenticationManager = owinCtx != null ? owinCtx.Authentication : null; 
    
         if (authenticationManager == null) 
         { 
          throw new InvalidOperationException("IAuthenticationManagerNotAvailable"); 
         } 
    
         return authenticationManager; 
        } 
    } 
    

    WebApiConfig.cs,你需要添加認證過濾器是這樣的:

    public static class WebApiConfig 
    { 
        public static void Register(HttpConfiguration config) 
        { 
         // Web API configuration and services 
         // Configure Web API to use only bearer token authentication. 
         config.SuppressDefaultHostAuthentication(); 
    
         config.Filters.Add(new MyAuthenticationFilter(OAuthDefaults.AuthenticationType)); 
        } 
    } 
    

    我建議你閱讀官方WEB API海報:

    https://www.asp.net/media/4071077/aspnet-web-api-poster.pdf