asp.net web api添加自定义认证

Posted GUOKUN

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了asp.net web api添加自定义认证相关的知识,希望对你有一定的参考价值。

1、定义认证失败结果生成器

   /// <summary>
    /// 认证失败结果生成器
    /// </summary>
    public class AuthenticationFailureResult : IHttpActionResult
    {
        public AuthenticationFailureResult(string reasonPhrase, HttpRequestMessage request)
        {
            ReasonPhrase = reasonPhrase;
            Request = request;
        }

        public string ReasonPhrase { get; private set; }

        public HttpRequestMessage Request { get; private set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            return Task.FromResult(Execute());
        }

        private HttpResponseMessage Execute()
        {
            return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, this.ReasonPhrase);
        }
    }

2、定义自定义认证过滤器(基于Cookie)

/// <summary>
    /// 自定义认证
    /// </summary>
    public class CustomAuthenticationFilter : Attribute, IAuthenticationFilter
    {
        public virtual bool AllowMultiple
        {
            get { return false; }
        }

        public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            var principal = await this.AuthenticateAsync(context.Request);
            if (principal == null)
            {
                context.Request.Headers.GetCookies().Clear();
                context.ErrorResult = new AuthenticationFailureResult("未授权请求", context.Request);
            }
            else
            {
                context.Principal = principal;
            }
        }

        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
        {
            return Task.FromResult(0);
        }

        private Task<IPrincipal> AuthenticateAsync(HttpRequestMessage request)
        {
            return Task.Run<IPrincipal>(() =>
                {
                    CookieHeaderValue cookieMobile = request.Headers.GetCookies("clientMobile").FirstOrDefault(),
                        cookieToken = request.Headers.GetCookies("clientToken").FirstOrDefault();
                    if (cookieMobile == null || cookieToken == null
                        || string.IsNullOrWhiteSpace(cookieMobile["clientMobile"].Value)
                        || string.IsNullOrWhiteSpace(cookieToken["clientToken"].Value))
                    {
                        return null;
                    }

                    string mobile = cookieMobile["clientMobile"].Value,
                        token = cookieToken["clientToken"].Value;
                    ClientDTO client = null;
            //此处从Redis服务器中取出指定用户,各位可以根据需要自行更换
using (ICache cache = ObjectContainer.Current.Resolve<ICacheFactory>().CreateCache()) { client = cache.Get<ClientDTO>(RedisTables.CLIENT, mobile); }
            //验证用户合法性,如果合法,构建声明式安全主题权限模式并返回,若用户验证不通过返回空
if (client != null && string.Equals(token, Md5Helper.MD5(string.Format("{0}{1}", mobile, client.MsgCode), 32), StringComparison.Ordinal)) { IEnumerable<Claim> claims = new List<Claim>() { new Claim(ClaimTypes.Name, mobile) }; var identity = new ClaimsIdentity("LoanCookie"); identity.AddClaims(claims); return new ClaimsPrincipal(identity); } return null; }); } }

3、将认证特性标记应用于全局、控制器或控制器操作,以控制器操作为例:

 

以上是关于asp.net web api添加自定义认证的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET Web Api 路由自定义

ASP.NET web api - 设置自定义 IIdentity 或 IPrincipal

如何自定义 ASP .NET Web API JWT 令牌响应?

如何在 ASP.NET Web API 中为 Json.NET 设置自定义 JsonSerializerSettings?

如何在 Asp.NET Core WEB API 中使用 .Net (C#) 在 Payload 中创建具有自定义 JSON 声明的 JWT 令牌

ASP.NET WEB API 中自定义对象的序列化 [重复]