而是已经登记用户则账号登陆。如果是早已报用户则账号登陆。

临数天,看了有博客园大牛关于webApi项目的之稿子,也来求教师兄一些问题,自己做了个Demo试了尝试,收获颇多。感谢感谢,下面是我有的学学之总,如一旦有错的地方要多多指教!!

守数天,看了一些博客园大牛关于webApi项目的之章,也有要教师兄一些问题,自己举行了单Demo试了试,收获颇多。感谢感谢,下面是自有修之总结,如一旦有摩擦的地方要多多指教!!

 

 

WebApi登陆与身份验证

WebApi登陆与身份验证

因于调用接口的时段都要传sessionKey参数过去,所以必须事先登录验证身份。

坐在调用接口的早晚都不能不传sessionKey参数过去,所以必须事先登录验证身份。

只要是已经登记用户则账号登陆,获得其位标识的
sessionkey,如果是勿账户用户则可以匿名登陆,要输入用户IP地址或者与客户端设备号当为获取sessionkey,然后可以错过挂号。

假定是一度登记用户则账号登陆,获得该身价标识的
sessionkey,如果是休账户用户则可以匿名登陆,要输入用户IP地址或者和客户端设备号当为获得sessionkey,然后可以错过挂号。

澳门娱乐网上平台 1 澳门娱乐网上平台 2

澳门娱乐网上平台 3 澳门娱乐网上平台 4

 

 

 

 

澳门娱乐网上平台 5澳门娱乐网上平台 6

澳门娱乐网上平台 7澳门娱乐网上平台 8

#region  登录API
        /// <summary>
        /// 登录API (账号登陆)
        /// </summary>
        /// <param name="phone">登录帐号手机号</param>
        /// <param name="hashedPassword">加密后的密码,这里避免明文,客户端加密后传到API端</param>
        /// <param name="deviceType">客户端的设备类型</param>
        /// <param name="clientId">客户端识别号, 一般在APP上会有一个客户端识别号</param>
        /// <returns></returns>
        [Route("account/login")]
        public SessionObject Login(string phone, string hashedPassword, int deviceType = 0, string clientId = "") {
            if (string.IsNullOrEmpty(phone))
                throw new ApiException("用户名不能为空。", "RequireParameter_userphone");
            if (string.IsNullOrEmpty(hashedPassword))
                throw new ApiException("hashedPassword 不能为空.", "RequireParameter_hashedPassword");

            int timeout = 60;

            var nowUser = _authenticationService.GetUserByPhone(phone);
            if (nowUser == null)
                throw new ApiException("帐户不存在", "Account_NotExits");

            #region 验证密码
            if (!string.Equals(nowUser.Password, hashedPassword)) {
                throw new ApiException("错误的密码", "Account_WrongPassword");
            }
            #endregion

            if (!nowUser.IsActive)
                throw new ApiException("用户处于非活动状态.", "InactiveUser");

            UserDevice existsDevice = _authenticationService.GetUserDevice(nowUser.UserId, deviceType);

            if (existsDevice == null) {
                string passkey = MD5CryptoProvider.GetMD5Hash(nowUser.UserId + nowUser.Phone + DateTime.UtcNow+ Guid.NewGuid());
                existsDevice = new UserDevice() {
                    UserId = nowUser.UserId,
                    CreateTime = DateTime.UtcNow,
                    ActiveTime = DateTime.UtcNow,
                    ExpiredTime = DateTime.UtcNow.AddMinutes(timeout),
                    DeviceType = deviceType,
                    SessionKey = passkey
                };
                _authenticationService.AddUserDevice(existsDevice);
            }
            else {
                existsDevice.ActiveTime = DateTime.UtcNow;
                existsDevice.ExpiredTime = DateTime.UtcNow.AddMinutes(timeout);
                _authenticationService.UpdateUserDevice(existsDevice);
            }
            nowUser.Password = "";
            return new SessionObject() { SessionKey = existsDevice.SessionKey, LogonUser = nowUser };
        }
        #endregion
#region  登录API
        /// <summary>
        /// 登录API (账号登陆)
        /// </summary>
        /// <param name="phone">登录帐号手机号</param>
        /// <param name="hashedPassword">加密后的密码,这里避免明文,客户端加密后传到API端</param>
        /// <param name="deviceType">客户端的设备类型</param>
        /// <param name="clientId">客户端识别号, 一般在APP上会有一个客户端识别号</param>
        /// <returns></returns>
        [Route("account/login")]
        public SessionObject Login(string phone, string hashedPassword, int deviceType = 0, string clientId = "") {
            if (string.IsNullOrEmpty(phone))
                throw new ApiException("用户名不能为空。", "RequireParameter_userphone");
            if (string.IsNullOrEmpty(hashedPassword))
                throw new ApiException("hashedPassword 不能为空.", "RequireParameter_hashedPassword");

            int timeout = 60;

            var nowUser = _authenticationService.GetUserByPhone(phone);
            if (nowUser == null)
                throw new ApiException("帐户不存在", "Account_NotExits");

            #region 验证密码
            if (!string.Equals(nowUser.Password, hashedPassword)) {
                throw new ApiException("错误的密码", "Account_WrongPassword");
            }
            #endregion

            if (!nowUser.IsActive)
                throw new ApiException("用户处于非活动状态.", "InactiveUser");

            UserDevice existsDevice = _authenticationService.GetUserDevice(nowUser.UserId, deviceType);

            if (existsDevice == null) {
                string passkey = MD5CryptoProvider.GetMD5Hash(nowUser.UserId + nowUser.Phone + DateTime.UtcNow+ Guid.NewGuid());
                existsDevice = new UserDevice() {
                    UserId = nowUser.UserId,
                    CreateTime = DateTime.UtcNow,
                    ActiveTime = DateTime.UtcNow,
                    ExpiredTime = DateTime.UtcNow.AddMinutes(timeout),
                    DeviceType = deviceType,
                    SessionKey = passkey
                };
                _authenticationService.AddUserDevice(existsDevice);
            }
            else {
                existsDevice.ActiveTime = DateTime.UtcNow;
                existsDevice.ExpiredTime = DateTime.UtcNow.AddMinutes(timeout);
                _authenticationService.UpdateUserDevice(existsDevice);
            }
            nowUser.Password = "";
            return new SessionObject() { SessionKey = existsDevice.SessionKey, LogonUser = nowUser };
        }
        #endregion

登录API

登录API

澳门娱乐网上平台 9澳门娱乐网上平台 10

澳门娱乐网上平台 11澳门娱乐网上平台 12

        #region 匿名登陆
        /// <summary>
        /// 匿名登陆
        /// </summary>
        /// <param name="ip">用户ip地址</param>
        /// <param name="deviceType">设备类型</param>
        /// <param name="clientId">客户端识别号</param>
        /// <returns></returns>
        [Route("account/AnonymousLogin")]
        public SessionObject1 AnonymousLogin(string ip, int deviceType = 0, string clientId = "")
        {
            if (string.IsNullOrEmpty(ip))throw new ApiException("ip地址不能为空。", "RequireParameter_ip");

            int timeout = 60;

            UserDevice existsDevice = _authenticationService.GetUserDevice(ip, deviceType);
            // Session.QueryOver<UserDevice>().Where(x => x.AccountId == nowAccount.Id && x.DeviceType == deviceType).SingleOrDefault();
            if (existsDevice == null) {
                string passkey = MD5CryptoProvider.GetMD5Hash(ip+DateTime.UtcNow + Guid.NewGuid());
                existsDevice = new UserDevice() {
                    IP = ip,
                    CreateTime = DateTime.UtcNow,
                    ActiveTime = DateTime.UtcNow,
                    ExpiredTime = DateTime.UtcNow.AddMinutes(timeout),
                    DeviceType = deviceType,
                    SessionKey = passkey
                };
                _authenticationService.AddUserDevice(existsDevice);
            }
            else {
                existsDevice.ActiveTime = DateTime.UtcNow;
                existsDevice.ExpiredTime = DateTime.UtcNow.AddMinutes(timeout);
                _authenticationService.UpdateUserDevice(existsDevice);
            }
            return new SessionObject1() { SessionKey = existsDevice.SessionKey, Ip=ip };
        }

        #endregion
        #region 匿名登陆
        /// <summary>
        /// 匿名登陆
        /// </summary>
        /// <param name="ip">用户ip地址</param>
        /// <param name="deviceType">设备类型</param>
        /// <param name="clientId">客户端识别号</param>
        /// <returns></returns>
        [Route("account/AnonymousLogin")]
        public SessionObject1 AnonymousLogin(string ip, int deviceType = 0, string clientId = "")
        {
            if (string.IsNullOrEmpty(ip))throw new ApiException("ip地址不能为空。", "RequireParameter_ip");

            int timeout = 60;

            UserDevice existsDevice = _authenticationService.GetUserDevice(ip, deviceType);
            // Session.QueryOver<UserDevice>().Where(x => x.AccountId == nowAccount.Id && x.DeviceType == deviceType).SingleOrDefault();
            if (existsDevice == null) {
                string passkey = MD5CryptoProvider.GetMD5Hash(ip+DateTime.UtcNow + Guid.NewGuid());
                existsDevice = new UserDevice() {
                    IP = ip,
                    CreateTime = DateTime.UtcNow,
                    ActiveTime = DateTime.UtcNow,
                    ExpiredTime = DateTime.UtcNow.AddMinutes(timeout),
                    DeviceType = deviceType,
                    SessionKey = passkey
                };
                _authenticationService.AddUserDevice(existsDevice);
            }
            else {
                existsDevice.ActiveTime = DateTime.UtcNow;
                existsDevice.ExpiredTime = DateTime.UtcNow.AddMinutes(timeout);
                _authenticationService.UpdateUserDevice(existsDevice);
            }
            return new SessionObject1() { SessionKey = existsDevice.SessionKey, Ip=ip };
        }

        #endregion

匿名登陆

匿名登陆

澳门娱乐网上平台 13

澳门娱乐网上平台 14

 

 

身价信息的验证是由此Web API 的
ActionFilter来实现之,所有需要身份验证的API请求都见面要求客户端传一个SessionKey。

身份信息的辨证是透过Web API 的
ActionFilter来实现之,所有需要身份验证的API请求都见面要求客户端传一个SessionKey。

当此处我们透过一个自定义的SessionValidateAttribute来聘户端的身份验证,
其后续自 System.Web.Http.Filters.ActionFilterAttribute。

在这边我们经过一个自定义的SessionValidateAttribute来拜会户端的身份验证,
其连续自 System.Web.Http.Filters.ActionFilterAttribute。

 

 

澳门娱乐网上平台 15澳门娱乐网上平台 16

澳门娱乐网上平台 17澳门娱乐网上平台 18

    public class SessionValidateAttribute : System.Web.Http.Filters.ActionFilterAttribute
    {
        public const string SessionKeyName = "SessionKey";
        public const string LogonUserName = "LogonUser";

        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            var qs = HttpUtility.ParseQueryString(filterContext.Request.RequestUri.Query);
            string sessionKey = qs[SessionKeyName];

            if (string.IsNullOrEmpty(sessionKey))
            {
                throw new ApiException("无效 Session.", "InvalidSession");
            }

            IAuthenticationService authenticationService = new AuthenticationService();//IocManager.Intance.Reslove<IAuthenticationService>();

            //验证用户session
            var userSession = authenticationService.GetUserDevice(sessionKey);

            if (userSession == null)
            {
                throw new ApiException("无此 sessionKey", "RequireParameter_sessionKey");
            }
            else
            {
                //todo: 加Session是否过期的判断
                if (userSession.ExpiredTime < DateTime.UtcNow)
                    throw new ApiException("session已过期", "SessionTimeOut");

                var logonUser = authenticationService.GetUser(userSession.UserId);
                if (logonUser != null)
                {
                    filterContext.ControllerContext.RouteData.Values[LogonUserName] = logonUser;
                    SetPrincipal(new UserPrincipal<int>(logonUser));
                }
                userSession.ActiveTime = DateTime.UtcNow;
                userSession.ExpiredTime = DateTime.UtcNow.AddMinutes(60);
                authenticationService.UpdateUserDevice(userSession);
            }
        }

        public static void SetPrincipal(IPrincipal principal)
        {
            Thread.CurrentPrincipal = principal;
            if (HttpContext.Current != null)
            {
                HttpContext.Current.User = principal;
            }
        }
    }
    public class SessionValidateAttribute : System.Web.Http.Filters.ActionFilterAttribute
    {
        public const string SessionKeyName = "SessionKey";
        public const string LogonUserName = "LogonUser";

        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            var qs = HttpUtility.ParseQueryString(filterContext.Request.RequestUri.Query);
            string sessionKey = qs[SessionKeyName];

            if (string.IsNullOrEmpty(sessionKey))
            {
                throw new ApiException("无效 Session.", "InvalidSession");
            }

            IAuthenticationService authenticationService = new AuthenticationService();//IocManager.Intance.Reslove<IAuthenticationService>();

            //验证用户session
            var userSession = authenticationService.GetUserDevice(sessionKey);

            if (userSession == null)
            {
                throw new ApiException("无此 sessionKey", "RequireParameter_sessionKey");
            }
            else
            {
                //todo: 加Session是否过期的判断
                if (userSession.ExpiredTime < DateTime.UtcNow)
                    throw new ApiException("session已过期", "SessionTimeOut");

                var logonUser = authenticationService.GetUser(userSession.UserId);
                if (logonUser != null)
                {
                    filterContext.ControllerContext.RouteData.Values[LogonUserName] = logonUser;
                    SetPrincipal(new UserPrincipal<int>(logonUser));
                }
                userSession.ActiveTime = DateTime.UtcNow;
                userSession.ExpiredTime = DateTime.UtcNow.AddMinutes(60);
                authenticationService.UpdateUserDevice(userSession);
            }
        }

        public static void SetPrincipal(IPrincipal principal)
        {
            Thread.CurrentPrincipal = principal;
            if (HttpContext.Current != null)
            {
                HttpContext.Current.User = principal;
            }
        }
    }

API身份验证

API身份验证

 

 

欲身份验证的apiControler
上加上[sessionValidate],则是Controller下面所有Action都拿具备身份验证功能

亟需身份验证的apiControler
上加上[sessionValidate],则这Controller下面所有Action都拿装有身份认证功能

澳门娱乐网上平台 19

澳门娱乐网上平台 20

 

 

万一是急需管理员权限才能要的数目来说,那么我们更定义一个
SessionValidateAdminAttribute
来开管理员的身份验证,在需要管理员权限才能请的控制器上长[SessionValidateAdminAttribute ],则是控制器下面有Action都只有通过身份验证的指挥者才来权力请求。

一经是内需管理员权限才能要的数额吧,那么我们再度定义一个
SessionValidateAdminAttribute
来做管理员的身份验证,在用管理员权限才能要的控制器上加上[SessionValidateAdminAttribute ],则这控制器下面有Action都只有由此身份验证的总指挥才发权力请求。

澳门娱乐网上平台 21澳门娱乐网上平台 22

澳门娱乐网上平台 23澳门娱乐网上平台 24

public class SessionValidateAdminAttribute : System.Web.Http.Filters.ActionFilterAttribute {
        public const string SessionKeyName = "SessionKey";
        public const string LogonUserName = "LogonUser";

        public override void OnActionExecuting(HttpActionContext filterContext) {
            var qs = HttpUtility.ParseQueryString(filterContext.Request.RequestUri.Query);
            string sessionKey = qs[SessionKeyName];

            if (string.IsNullOrEmpty(sessionKey)) {
                throw new ApiException("无效 Session.", "InvalidSession");
            }

            IAuthenticationService authenticationService = new AuthenticationService();//IocManager.Intance.Reslove<IAuthenticationService>();

            //验证用户session
            var userSession = authenticationService.GetUserDevice(sessionKey);

            if (userSession == null) {
                throw new ApiException("无此 sessionKey", "RequireParameter_sessionKey");
            }
            else {
                //todo: 加Session是否过期的判断
                if (userSession.ExpiredTime < DateTime.UtcNow)
                    throw new ApiException("session已过期", "SessionTimeOut");

                var logonUser = authenticationService.GetUser(userSession.UserId);

                if (logonUser == null) {
                    throw new ApiException("无此用户", "Invalid_User");
                }
                else
                {
                    if (logonUser.Permissions == 1)
                    {
                        filterContext.ControllerContext.RouteData.Values[LogonUserName] = logonUser;
                        SessionValidateAttribute.SetPrincipal(new UserPrincipal<int>(logonUser));
                    }
                    else
                    {
                        throw new ApiException("用户无权限", "No permissions");
                    }
                }
                userSession.ActiveTime = DateTime.UtcNow;
                userSession.ExpiredTime = DateTime.UtcNow.AddMinutes(60);
                authenticationService.UpdateUserDevice(userSession);
            }
        }

    }
public class SessionValidateAdminAttribute : System.Web.Http.Filters.ActionFilterAttribute {
        public const string SessionKeyName = "SessionKey";
        public const string LogonUserName = "LogonUser";

        public override void OnActionExecuting(HttpActionContext filterContext) {
            var qs = HttpUtility.ParseQueryString(filterContext.Request.RequestUri.Query);
            string sessionKey = qs[SessionKeyName];

            if (string.IsNullOrEmpty(sessionKey)) {
                throw new ApiException("无效 Session.", "InvalidSession");
            }

            IAuthenticationService authenticationService = new AuthenticationService();//IocManager.Intance.Reslove<IAuthenticationService>();

            //验证用户session
            var userSession = authenticationService.GetUserDevice(sessionKey);

            if (userSession == null) {
                throw new ApiException("无此 sessionKey", "RequireParameter_sessionKey");
            }
            else {
                //todo: 加Session是否过期的判断
                if (userSession.ExpiredTime < DateTime.UtcNow)
                    throw new ApiException("session已过期", "SessionTimeOut");

                var logonUser = authenticationService.GetUser(userSession.UserId);

                if (logonUser == null) {
                    throw new ApiException("无此用户", "Invalid_User");
                }
                else
                {
                    if (logonUser.Permissions == 1)
                    {
                        filterContext.ControllerContext.RouteData.Values[LogonUserName] = logonUser;
                        SessionValidateAttribute.SetPrincipal(new UserPrincipal<int>(logonUser));
                    }
                    else
                    {
                        throw new ApiException("用户无权限", "No permissions");
                    }
                }
                userSession.ActiveTime = DateTime.UtcNow;
                userSession.ExpiredTime = DateTime.UtcNow.AddMinutes(60);
                authenticationService.UpdateUserDevice(userSession);
            }
        }

    }

SessionValidateAdminAttribute

SessionValidateAdminAttribute

澳门娱乐网上平台 25

澳门娱乐网上平台 26

关于:[EnableCors(origins: “*”,
headers: “*”, methods: “*”)] 的说明,

关于:[EnableCors(origins: “*”,
headers: “*”, methods: “*”)] 的说明,

详情查看:http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-05.html

端详查看:http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-05.html

 

 

至于用户过时:每次调用接口的时候
会自动更新sessionKey的逾期时,如果加上时不更新,则下次造访时见面过,则用再行登陆。

至于用户过时:每次调用接口的上
会自动更新sessionKey的晚点时,如果长日子不更新,则下次拜会时见面过,则要重新登陆。

 

 

加盟身份验证后底 UserControler 

加盟身份验证后的 UserControler 

澳门娱乐网上平台 27澳门娱乐网上平台 28

澳门娱乐网上平台 29澳门娱乐网上平台 30

[EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/Users"), SessionValidate, WebApiTracker] 
    public class UsersController : ApiController
    {
        private  readonly IUsers _users=new UsersImpl();
        #region 根据用户ID获得用户信息
        /// <summary>
        /// 根据用户ID获得用户信息(获得数据)
        /// </summary>
        /// <param name="sessionKey">sessionKey</param>
        /// <param name="id">用户id</param>
        /// <returns>result</returns>
        public ApiResult<Users> GetUserById( string sessionKey,int  id)
        {
            Users modelUsers = _users.GetUserByUsersId(id);
            if (modelUsers != null)
            {
                return new ApiResult<Users>("1","获取用户信息成功",modelUsers);
            }
            else return new ApiResult<Users>("0","无此用户信息",null);
        }
        #endregion

        /// <summary>
        /// 新用户注册(增加数据)
        /// </summary>
        /// <param name="modelUsers"></param>
        /// <returns>result</returns>
        [HttpPost, Route("api/UserRegistration")]
        public ApiResult<bool> UserRegistration(string sessionKey, AddUserRq modelUsers)
        {
            Users usersModel=new Users();
            usersModel.IsActive = true;
            usersModel.Password = modelUsers.Password;
            usersModel.Permissions = 2;
            usersModel.Phone = modelUsers.Phone;
            usersModel.Sex = modelUsers.Sex;
            usersModel.TrueName = modelUsers.TrueName;
            usersModel.UserName = modelUsers.UserName;
            return _users.RegistrationNewUsers(usersModel);
        }
    }
[EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/Users"), SessionValidate, WebApiTracker] 
    public class UsersController : ApiController
    {
        private  readonly IUsers _users=new UsersImpl();
        #region 根据用户ID获得用户信息
        /// <summary>
        /// 根据用户ID获得用户信息(获得数据)
        /// </summary>
        /// <param name="sessionKey">sessionKey</param>
        /// <param name="id">用户id</param>
        /// <returns>result</returns>
        public ApiResult<Users> GetUserById( string sessionKey,int  id)
        {
            Users modelUsers = _users.GetUserByUsersId(id);
            if (modelUsers != null)
            {
                return new ApiResult<Users>("1","获取用户信息成功",modelUsers);
            }
            else return new ApiResult<Users>("0","无此用户信息",null);
        }
        #endregion

        /// <summary>
        /// 新用户注册(增加数据)
        /// </summary>
        /// <param name="modelUsers"></param>
        /// <returns>result</returns>
        [HttpPost, Route("api/UserRegistration")]
        public ApiResult<bool> UserRegistration(string sessionKey, AddUserRq modelUsers)
        {
            Users usersModel=new Users();
            usersModel.IsActive = true;
            usersModel.Password = modelUsers.Password;
            usersModel.Permissions = 2;
            usersModel.Phone = modelUsers.Phone;
            usersModel.Sex = modelUsers.Sex;
            usersModel.TrueName = modelUsers.TrueName;
            usersModel.UserName = modelUsers.UserName;
            return _users.RegistrationNewUsers(usersModel);
        }
    }

UsersControllers

UsersControllers

 

 

 

 

以此随笔乃我学习工作记录,如发疑问欢迎在下面评论,转载请标明出处。

此随笔乃我学习工作记录,如发疑点欢迎在底下评论,转载请标明出处。

假如对而有帮带要动动鼠标右下方为我来单赞,您的支撑是自个儿无比特别的动力。

比方对你有救助要动动鼠标右下方为我来单赞,您的支持是我顶深之动力。

 2017-11
代码和数据库文件已上传至 https://github.com/huangenai/WebAPI

 2017-11
代码和数据库文件就上传至 https://github.com/huangenai/WebAPI

澳门娱乐网上平台 31

澳门娱乐网上平台 32