gpt4 book ai didi

authentication - 具有自定义身份验证的 Web API 2 OAuth 不记名 token

转载 作者:行者123 更新时间:2023-12-05 01:35:27 25 4
gpt4 key购买 nike

我对 C# Web API 2 服务有以下要求:

该服务通过电子邮件和发送到收件箱的临时密码的组合对用户进行身份验证,作为身份验证的一个因素。
我需要将此身份验证机制与生成 OAuth 不记名 token 以保护服务并使用标准 ASP.NET 授权机制通过某种 [Authorize] 属性检查每个请求是否与 token 相匹配。

我已成功实现这些步骤

  • 用户请求密码
  • 系统生成密码并通过电子邮件发送给用户,有效期为 30 天
  • 用户使用电子邮件 + 密码进行身份验证
  • 系统检查密码的有效性

  • 但我不确定如何开始实现剩余的步骤
  • 如果密码有效,系统生成 OAuth 不记名 token
  • OAuth 不记名 token 的持续时间与密码到期日期一样长
  • 使用 ASP.NET Identity 授权属性执行身份验证和授权检查
  • 使用 OWIN Security 和 OAuth Middleware 创建 token
  • 使用基于声明的授权并将声明序列化为 token

  • 引用的过程仅描述了使用 ASP.NET Identity 个人用户帐户作为身份验证的一种方式,这不是我想要的身份验证方式。

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

    我实际上需要通过检查电子邮件和密码来进行身份验证。

    最佳答案

    我在类似的场景中工作并实现了一个身份验证过滤器( IAuthenticationFilter )和一个从 OAuthAuthorizationServerProvider 继承的自定义类。 .就我而言,我需要使用 OAuth 和旧 token 对请求进行身份验证。我相信在您的情况下,您需要自定义 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

    关于authentication - 具有自定义身份验证的 Web API 2 OAuth 不记名 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37732907/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com