2016-06-09 92 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

    相关问题