使用webapi实现windows本地用户管理

1. 引言

最近一段时间设计和实现公司内部的基于OAuth2.0的统一身份认证中心,经梳理,公司部分自研系统可以使用OAuth2.0的方式进行身份认证,还有一部分系统无源代码,未开放接口,使用windows用户作为系统的用户。面对这种情况,同时为实现一个中心一键开关账户的功能,对于无源码、未开放接口、使用windows用户作为系统用户的系统,单独开发接口程序,有数据库的直接操作数据库将账号密码同步至数据库中;对于使用windows用户作为系统用户的系统,则在其部署的服务器上部署webapi接口,同步管理用户和密码。本文主要介绍的是C#对windows本地用户的新增、删除、修改密码功能以及列出所有本地用户的功能。

2. Active Directory与DirectoryEntry 类

C#管理windows用户,在百度上搜索到c#操作windows本地账户这样一篇文章,主要是通过导入Netapi32.dll文件实现对windows本地账户的管理。而在之前有做过使用DirectoryEntry 类修改本地用户密码的功能,经搜索,DirectoryEntry 类可封装 Active Directory 域服务层次结构中的节点或对象,也能实现对用户的新增、删除以及其他功能。

Active Directory
活动目录(Active Directory)是面向Windows Standard Server、Windows Enterprise Server以及 Windows Datacenter Server的目录服务。(Active Directory不能运行在Windows Web Server上,但是可以通过它对运行Windows Web Server的计算机进行管理。)Active Directory存储了有关网络对象的信息,并且让管理员和用户能够轻松地查找和使用这些信息。Active Directory使用了一种结构化的数据存储方式,并以此作为基础对目录信息进行合乎逻辑的分层组织。

可参考: Active Directory的基本概念

DirectoryEntry 类
DirectoryEntry类位于System.DirectoryServices表空间下,可封装 Active Directory 域服务层次结构中的节点或对象。DirectoryEntry类使用 Active Directory Services Interfaces (ADSI) 技术。 ADSI 是 Microsoft 为灵活的工具提供用于处理各种网络提供程序的接口的集合。 ADSI 使管理员能够定位和管理网络上的资源相对容易地,而不考虑网络的大小。

可参考:DirectoryEntry 类

3. 管理本地用户

using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Web;

namespace OAuthClient.Common
{
    public class WindowsUser : IUser
    {
        private static readonly string PATH = "WinNT://" + Environment.MachineName;

        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns></returns>
        public List<User> GetAllUser()
        {
            List<User> list = new List<User>();
            using (DirectoryEntry deRoot = new DirectoryEntry(PATH))
            {
                if (deRoot.Children != null)
                {
                    foreach (DirectoryEntry de in deRoot.Children)
                    {
                        if (de.SchemaClassName == "User" ||
                            de.SchemaClassName == "Computer" ||
                            de.SchemaClassName == "Domain")
                        {
                            User user = new User()
                            {
                                name = de.Name,
                                fullname = de.Properties["FullName"].Value.ToString()
                            };
                            list.Add(user);
                        }
                    }
                }
                return list;
            }
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string AddUser(User user)
        {
            try
            {
                using (DirectoryEntry deRoot = new DirectoryEntry(PATH))
                {
                    using (DirectoryEntry de = deRoot.Children.Add(user.name, "User")) 
                    {
                        de.Properties["FullName"].Add(user.fullname); //用户全称
                        de.Invoke("SetPassword", user.password); //用户密码
                        de.Invoke("Put", "Description", user.description);//用户详细描述
                        de.Invoke("Put", "UserFlags", 66049); //密码永不过期
                        de.CommitChanges();
                        return "OK";
                    }
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 移除用户
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string RemoveUser(string name)
        {
            try
            {
                using (DirectoryEntry deRoot = new DirectoryEntry(PATH))
                {
                    using (DirectoryEntry user = deRoot.Children.Find(name, "User"))
                    {
                        if (user != null)
                            dir.Children.Remove(user);
                        return "OK";
                    }
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string ChangePassword(User user)
        {
            try
            {
                using (DirectoryEntry deRoot = new DirectoryEntry(PATH))
                {
                    using (DirectoryEntry de = dir.Children.Find(user.name, "User"))
                    {
                        de.Invoke("SetPassword", new object[] { user.password });
                        de.CommitChanges();
                        return "OK";
                    }
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}

4. webapi下注意项

  1. 在webapi下,如果使用DirectoryEntry类,需添加Microsoft.Web.Infrastructure的引用。
  2. 在web.config中,需增加如下的配置节,否则会报拒绝访问的错误。
 <system.web>    
    <identity impersonate="true" />
  </system.web>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,268评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,999评论 6 342
  • 关于Mongodb的全面总结 MongoDB的内部构造《MongoDB The Definitive Guide》...
    中v中阅读 32,098评论 2 89
  • 哼着小曲徐风去梳洗,遇见满脸困倦且带着淡淡黑眼圈的花小荣,不由地问道:“荣哥,你这是怎么了,昨晚没睡好吗?” “出...
    袋鼠小说阅读 221评论 0 0
  • 不知道从什么时候开始,大家都变得敏感起来,气氛变得怪怪的。 十一之前,妈妈和爸爸来到我的城市看望阿姨,我妈就在我租...
    暮暮lynne阅读 184评论 0 0