c# – Windows窗体中的MVC WebAPI身份验证

前端之家收集整理的这篇文章主要介绍了c# – Windows窗体中的MVC WebAPI身份验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使一个 Windows窗体应用程序插入ASP.NET MVC WebAPI公开的一些服务,但身份验证/登录部分遇到了很多麻烦.

我似乎找不到一个例子,只是演示如何从Windows窗体中做到这一点,我发现的一切似乎是非常复杂的,包括很多非常深的管道,或者似乎针对其他ASP.NET网站,而不是Windows窗体.

有没有我失踪的东西?这是不可能吗?还是只是不打算?我已经看过像这样的.NET WebApi Authentication这样的事情,但是我没有看到如何使用Windows窗体方面的cookie.我也已经过了http://blogs.msdn.com/b/webdev/archive/2012/08/26/asp-net-web-api-and-httpclient-samples.aspx,仍然有很少的运气.

解决方法

只需在服务器端创建身份验证令牌,并将其存储在数据库或甚至缓存中.然后发送这个令牌与您的win表单应用程序的请求. WebApi应该一直检查这个令牌.这足够好,您可以完全控制您的验证过程.

让我分享一下,它对我有用:

对象与Auth详细信息:

public class TokenIdentity
{
    public int UserID { get; set; }

    public string AuthToken { get; set; }

    public ISocialUser SocialUser { get; set; }
}

Web API验证控制器

public class AuthController : ApiController
    {
        public TokenIdentity Post(
            SocialNetwork socialNetwork,string socialUserID,[FromUri]string socialAuthToken,[FromUri]string deviceRegistrationID = null,[FromUri]DeviceType? deviceType = null)
        {
            var socialManager = new SocialManager();

            var user = socialManager.GetSocialUser(socialNetwork,socialUserID,socialAuthToken);

            var tokenIdentity = new AuthCacheManager()
                .Authenticate(
                    user,deviceType,deviceRegistrationID);

            return tokenIdentity;
        }
    }

验证缓存管理器

public class AuthCacheManager : AuthManager
    {
        public override TokenIdentity CurrentUser
        {
            get
            {
                var authToken = HttpContext.Current.Request.Headers["AuthToken"];
                if (authToken == null) return null;

                if (HttpRuntime.Cache[authToken] != null)
                {
                    return (TokenIdentity) HttpRuntime.Cache.Get(authToken);
                }

                return base.CurrentUser;
            }
        }

        public int? CurrentUserID
        {
            get
            {
                if (CurrentUser != null)
                {
                    return CurrentUser.UserID;
                }
                return null;
            }
        }

        public override TokenIdentity Authenticate(
            ISocialUser socialUser,DeviceType? deviceType = null,string deviceRegistrationID = null)
        {
            if (socialUser == null) throw new ArgumentNullException("socialUser");
            var identity = base.Authenticate(socialUser,deviceRegistrationID);

            HttpRuntime.Cache.Add(
                identity.AuthToken,identity,null,DateTime.Now.AddDays(7),Cache.NoSlidingExpiration,CacheItemPriority.Default,null);

            return identity;
        }
    }

验证经理:

public abstract class AuthManager
    {
        public virtual TokenIdentity CurrentUser
        {
            get
            {
                var authToken = HttpContext.Current.Request.Headers["AuthToken"];
                if (authToken == null) return null;

                using (var usersRepo = new UsersRepository())
                {
                    var user = usersRepo.GetUserByToken(authToken);

                    if (user == null) return null;

                    return new TokenIdentity
                    {
                        AuthToken = user.AuthToken,SocialUser = user,UserID = user.ID
                    };
                }
            }
        }

        public virtual TokenIdentity Authenticate(
            ISocialUser socialUser,string deviceRegistrationID = null)
        {
            using (var usersRepo = new UsersRepository())
            {
                var user = usersRepo.GetUserBySocialID(socialUser.SocialUserID,socialUser.SocialNetwork);

                user = (user ?? new User()).CopyFrom(socialUser);

                user.AuthToken = System.Guid.NewGuid().ToString();

                if (user.ID == default(int))
                {
                    usersRepo.Add(user);
                }

                usersRepo.SaveChanges();

                return new TokenIdentity
                {
                    AuthToken = user.AuthToken,UserID = user.ID
                };
            }
        }
    }

全局行动过滤器

public class TokenAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (actionContext.Request.RequestUri.AbsolutePath.Contains("api/auth"))
        {
            return;
        }

        var authManager = new AuthCacheManager();

        var user = authManager.CurrentUser;

        if (user == null)
        {
            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        }

        //Updates the authentication
        authManager.Authenticate(user.SocialUser);
    }
}

Global.asax注册

GlobalConfiguration.Configuration.Filters.Add(new AuthFilterAttribute());

这个想法是AuthCacheManager扩展了AuthManager并修饰了它的方法属性.如果缓存内没有任何内容,请检查数据库.

猜你在找的C#相关文章