增加SharePoint2010修改域密码功能

前提
SharePoint2010的用户基于AD的,因此修改密码是修改了AD的密码,当然也可以修改本机密码(非域的密码)。这里我们讨论修改域密码。我们修改需要用到sharepoint的弹出对话框的模式,以下为几个对话框函数:

Ø SP.UI.ModalDialog.showModalDialog:弹出对话框

Ø SP.UI.Status.addStstus:自定义状态栏信息

Ø SP.UI.Notify.addNotification:自定义消息通知

配置开发
1. 使用sharepoint designer2010打开对应站点http://moss:8002 ,找到v4.master如下图:

2. 打开编辑v4.master,如下图:

添加JS代码:

采用自定义通知栏模式
<script language="javascript" type="text/javascript">
    function portal_openModalDialog()
    {
        var options = SP.UI.$create_DialogOptions();
        options.width = 500;
        options.height = 250;
        options.url = "/_layouts/TCL.EG.ModifyPasswd/ModifyPasswd.aspx";
        options.dialogReturnValueCallback = Function.createDelegate(null, portal_modalDialogClosedCallback);
        SP.UI.ModalDialog.showModalDialog(options);
    }
    //关闭函数
    function portal_modalDialogClosedCallback(result, value)
    {
        if (value == "1")
        {
            //自定义通知栏
SP.UI.Notify.addNotification("恭喜!修改成功!");

}
        else if (value == "0")
        {
   //自定义通知栏
            SP.UI.Notify.addNotification("修改失败,请联系管理员!");
        }
      
    }
    //关闭函数
    function closeDialog()
    {
        SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 3);
    }
</script>
 
采用自定义状态栏模式
<script language="javascript" type="text/javascript">
    function portal_openModalDialog()
    {
        var options = SP.UI.$create_DialogOptions();
        options.width = 500;
        options.height = 250;
        options.url = "/_layouts/TCL.EG.ModifyPasswd/ModifyPasswd.aspx";
        options.dialogReturnValueCallback = Function.createDelegate(null, portal_modalDialogClosedCallback);
        SP.UI.ModalDialog.showModalDialog(options);
    }
    //关闭函数
    function portal_modalDialogClosedCallback(result, value)
    {
        if (value == "1")
        {
            //自定义状态栏
  this.statusId  = SP.UI.Status.addStatus ("恭喜!修改成功!",“修改密码成功,请重新登录!”,true);
        }
        else if (value == "0")
        {
   //自定义通知栏
  this.statusId =SP.UI.Status.addStatus ("修改失败!",“修改失败,请联系管理员!”,true);
        }
         SP.UI.Status.setStatusPriColor(this.statusId, "Green");
  setTimeout(RemoveStatus, 6000);
}
function RemoveStatus() {
SP.UI.Status.removeStatus(this.statusId);
 
}
    //关闭函数
    function closeDialog()
    {
        SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 3);
    }
</script>
加入母版页面中,签入即可,如下图:

3. 使用VS2010开发添加sharepoint空白项目,如下图:

4. 添加空元素,如下图:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
      Id="{BC477D9E-365A-47BD-AB2B-BE06FA44628D}"
      Title="修改密码"
      Description="此处修改的是域里面的密码"
      Sequence="1000"
      Location="Microsoft.SharePoint.StandardMenu"
      GroupId="PersonalActions"
      ImageUrl="~sitecollection/_layouts/images/menulistsettings.gif">
    <UrlAction Url="javascript:portal_openModalDialog();"/>
  </CustomAction>
</Elements>
5. 添加修改密码的页面,页面代码部分如下:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ModifyPasswd.aspx.cs" Inherits="TCL.EG.ModifyPasswd.Layouts.TCL.EG.ModifyPasswd.ModifyPasswd"
    DynamicMasterPageFile="~masterurl/default.master" %>
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <table cellpadding="0" cellspacing="0" border="0">
        <tr>
            <td>
                旧密码:
            </td>
            <td>
                <asp:TextBox ID="txtOldPwd" runat="server" TextMode="Password"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                新密码:
            </td>
            <td>
                <asp:TextBox ID="txtNewPwd" runat="server" TextMode="Password"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                确认密码:
            </td>
            <td>
                <asp:TextBox ID="txtConfirmPwd" runat="server" TextMode="Password"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnUpdate" runat="server" Text="保存" OnClick="btnUpdate_Click" />
            </td>
            <td>
                <asp:Button ID="btnCancel" runat="server" Text="取消" OnClientClick="closeDialog()" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                 <font color="red"><asp:Label ID="Label_Title" runat="server" ></asp:Label></font>
            </td>
        </tr>
    </table>
  
</asp:Content>
<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
    修改密码
</asp:Content>
<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea"
    runat="server">
    我的应用程序页
</asp:Content>
6、后台代码.cs部分,如下:
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.DirectoryServices.AccountManagement;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.DirectoryServices;
namespace TCL.EG.ModifyPasswd.Layouts.TCL.EG.ModifyPasswd
{
    public partial class ModifyPasswd : LayoutsPageBase
    {
        #region//变量
        /// <summary>
        ///
        /// </summary>
        private string _userName;
     
        ///
        /// </summary>
        private PrincipalContext _principalContext;
        private string newPasswd = string.Empty;
        private string confirmPasswd = string.Empty;
        private string oldPasswd = string.Empty;
        #endregion
        #region//事件
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
            }
        }
        /// <summary>
        /// 更新密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (SPContext.Current != null)
            {
                //登录名
                _userName = SPContext.Current.Web.CurrentUser.LoginName;
                //
                if (_userName.ToLower() == "sharepoint\\system")
                {
                    _userName = "contoso\\mossadmin";
                }
                //旧密码不允许为空
                 //修改密码
                newPasswd = this.txtNewPwd.Text.Trim();
                confirmPasswd = this.txtConfirmPwd.Text.Trim();
                oldPasswd = txtOldPwd.Text.Trim();
                //
                if (string.IsNullOrEmpty(oldPasswd))
                {
                    this.Label_Title.Text = "请输入旧密码!";
                    return;
                }
                if (string.IsNullOrEmpty(newPasswd))
                {
                    this.Label_Title.Text = "请输入新密码!";
                    return;
                }
                if (string.IsNullOrEmpty(confirmPasswd))
                {
                    this.Label_Title.Text = "请输入确认密码!";
                    return;
                }
                //判断2次密码是否一致。
                if (newPasswd != confirmPasswd)
                {
                    this.Label_Title.Text = "新密码与确认密码不一致!";
                    return;
                }
                //_userName
                if (!string.IsNullOrEmpty(_userName))
                {
                    //登录名为contoso\\mossadmin
                    try
                    {
                        //检查原始密码是否正确
                        bool isOK = CheckUser(ValidType.Domain, _userName, oldPasswd);
                        //如果正确
                        if (!isOK)
                        {
                            this.Label_Title.Text = "旧密码输入错误!";
                            return;
                        }
                        else
                        {
                            //更改密码
                            bool isreult = UpdateMyPassword(newPasswd, oldPasswd);
                            //
                            if (isreult)
                            {
                                //提示信息
                                Response.Write(
                                "<script type=\"text/javascript\">window.frameElement.commonModalDialogClose(1, 1);</script>");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        this.Label_Title.Text = ex.Message;
                    }
                }
            }
        }
        #endregion
        #region//方法
        #region//修改密码
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="newUserPasswd">新密码</param>
        /// <param name="oldUserPasswd">原始密码</param>
        /// <returns>返回结果是否成功</returns>
        private bool UpdateMyPassword(string newUserPasswd,string oldUserPasswd)
        {
            //返回ok
            bool _result = false;
            try
            {
                Impersonator Imp = new Impersonator();
                //开始
                Imp.BeginImpersonation();
                //
                using (var context = new PrincipalContext(ContextType.Domain))
                {
                    using (UserPrincipal usr = UserPrincipal.FindByIdentity(
                                  context,
                                  IdentityType.SamAccountName,
                                  Microsoft.SharePoint.SPContext.Current.Web.CurrentUser.LoginName))
                    {
                        usr.UserCannotChangePassword = true;
                        usr.ChangePassword(oldUserPasswd, newUserPasswd);
                      
                    }
                }
                //修改
                if (Imp.IsImpersonated)
                {
                    Imp.StopImpersonation();
                    //Ok
                    _result = true;
                }
                else
                {
                    //fail
                    _result = false;
                }
              
            }
            catch(Exception ex)
            {
                this.Label_Title.Text = ex.Message;
                _result = false;
            }
            //return
            return _result;
        }
        #endregion
        #region//验证原始密码是否正确
        /// <summary> 
        /// 验证原始密码是否正确
        /// </summary> 
        /// <param name="validType">验证类型</param> 
        /// <param name="UserName">登录名</param> 
        /// <param name="PassWord">登录密码</param> 
        /// <returns>返回是否成功的标识</returns> 
        public  Boolean CheckUser(ValidType validType, String UserName, String PassWord) 
        { 
            try
            { 
                String[] UserArray = UserName.Split(new char[] { '\\' }); //UserName 組合為 Domain\Account 或 MachineName\Account 
                InitPC(validType, UserArray[0]); 
                Boolean isValid = _principalContext.ValidateCredentials(UserArray[1], PassWord); 
                return isValid; 
            } 
            catch (Exception ex) 
            { 
               
                this.Label_Title.Text = ex.Message;
                return false; 
            } 
        }
        #endregion
        #region//PrincipalContext初始化
        /// <summary> 
        /// PrincipalContext初始化 
        /// </summary> 
        /// <param name="validType">验证类型</param> 
        /// <param name="LDAPName">应用程序</param> 
        private void InitPC(ValidType validType, String LDAPName)
         {
             //PrincipalContext pc = null; 
             int typeNum = (int)validType;
             switch (typeNum)
             {
                 case 1:
                     _principalContext = new PrincipalContext(ContextType.Domain, LDAPName);
                     break;
                 case 2:
                     _principalContext = new PrincipalContext(ContextType.Machine, LDAPName);
                     break;
                 case 3:
                     _principalContext = new PrincipalContext(ContextType.ApplicationDirectory, LDAPName);
                     break;
                 default:
                     break;
             }
         }
        #endregion
        #region//枚举类型
        /// <summary>
        /// 枚举类型
        /// </summary>
        public enum ValidType 
        { 
            /// <summary> 
            /// 域
            /// </summary> 
            Domain = 1, 
            /// <summary> 
            /// 机器
            /// </summary> 
            Machine = 2, 
            /// <summary> 
            /// 应用程序 
            /// </summary> 
            ApplicationDirectory = 3
        }
        #endregion
        #endregion
    }
}
7. Impersonator.cs代码部分如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
namespace TCL.EG.ModifyPasswd
{
    public class Impersonator
    {
        private WindowsImpersonationContext ctx = null;
        public bool IsImpersonated { get; set; }
        public void BeginImpersonation()
        {
            try
            {
                if (!WindowsIdentity.GetCurrent().IsSystem)
                {
                    ctx = WindowsIdentity.Impersonate(WindowsIdentity.GetCurrent().Token);
                    IsImpersonated = true;
                }
            }
            catch
            {
                IsImpersonated = false;
            }
        }
        public void StopImpersonation()
        {
            if (ctx != null)
            {
                ctx.Undo();
            }
        }
    }
}
8. 部署后,看下效果图:

自定义通知栏效果图:

自定义状态栏效果图:

注意事项:

1、 密码复杂度策略,最好合符要求,否则会提示:密码不合符复杂度策略。要不,干脆不禁用此策略,在代码中用自己定义策略,用正则表达式,如下图:

2、 为了能每天多次修改密码,此时应当禁用如下策略,如下图:

否则定义好,必须按照此策略进行。策略更新后请重启系统或用gpupdate进行策略刷新即可。

sharepoint修改密码的更多相关文章

  1. sharepoint 修改AD密码

    sharepoint 修改AD密码 下面是添加添加“空元素”代码: 第一个<CustomAction>是添加修改密码项目 第二个<CustomAction>是添加js修改脚本 ...

  2. Sharepoint增加修改密码功能

    Sharepoint中没有自带的修改密码的功能. 如果使用的是AD验证,修改密码,只要修改域帐号的用户名密码就可以了.以下代码可以修改本机密码和域帐号密码. 做法是,添加一个webpart,做一个页面 ...

  3. 分享修改密码的SharePoint Web part: ITaCS Change Password web part

    Codeplex 上有一个现成的修改密码的Web part, 在SharePoint 2010和SharePoint 2013都可以用 项目地址:http://changepassword.codep ...

  4. SharePoint重置密码功能Demo

    博客地址 http://blog.csdn.net/foxdave 本文将说明一个简单的重置SharePoint用户密码(NTLM Windows认证)的功能如何实现 重置密码功能,实际上就是重置域用 ...

  5. SharePoint 2010:“&”作为SharePoint账号密码引起的错误

    一朋友修改了SharePoint 2010系统账号密码,导致无法登陆.他的环境如下: 两台服务器:AD+SharePoint 2010 ,Sql Server 2008 r2 目标站点开启了Form登 ...

  6. MVC5 网站开发之六 管理员 2、添加、删除、重置密码、修改密码、列表浏览

    目录 奔跑吧,代码小哥! MVC5网站开发之一 总体概述 MVC5 网站开发之二 创建项目 MVC5 网站开发之三 数据存储层功能实现 MVC5 网站开发之四 业务逻辑层的架构和基本功能 MVC5 网 ...

  7. win7下安装mysql后修改密码

    mysql的安装教程网上很多,此处不过多介绍,个人觉得下面这篇教程是比较好的,一步到位.MySQL 5.7.9 ZIP 免安装版本配置过程_百度经验  http://jingyan.baidu.com ...

  8. linux创建新用户以及修改密码

    1. 使用root账户创建新用户 useradd webuser 2. 修改新增的用户的密码 passwd webuser 这时候会提示你输入新的密码: 注意:不要用su webuser进入该账户修改 ...

  9. ASP.NET MVC5 网站开发实践(二) Member区域 - 用户部分(3)修改资料、修改密码

    在上一篇博客中实现了用户的注销和登录,其实代码里落了点东西,就是用户登录要更新最后一次登录时间和登录IP,这次补上.今天做修改资料和修改密码,TryUpdateModel是新用到的东西. 目录: AS ...

随机推荐

  1. Android中实现自定义的拍照应用

    可以参考:http://www.android-doc.com/guide/topics/media/camera.html 一.添加相应的权限 <uses-permission android ...

  2. 【uoj222】 NOI2016—区间

    http://uoj.ac/problem/222 (题目链接) 题意 有n个区间,当有m个区间有公共部分时,求m个区间长度的最大值与最小值之差的最小值. Solution 线段树+滑动窗口.这道题很 ...

  3. 【poj1009】 Edge Detection

    http://poj.org/problem?id=1009 (题目链接) 不得不说,poj上的水题还是质量非常高的= =,竟然让本大爷写了一下午. 转自:http://blog.sina.com.c ...

  4. windows进程/线程创建过程 --- windows操作系统学习

    有了之前的对进程和线程对象的学习的铺垫后,我们现在可以开始学习windows下的进程创建过程了,我将尝试着从源代码的层次来分析在windows下创建一个进程都要涉及到哪些步骤,都要涉及到哪些数据结构. ...

  5. UVA 1398 Meteor

    传送门 Solution: 记一颗流星在视野内的时间段为(L, R), 为了使所有(L, R)都取整数,首先将坐标放大. 放大倍数可取为 LCM(1, 2, ..., 10)= 2520 接着计算:从 ...

  6. HTTPS-能否避免流量劫持

    流量劫持是什么? EtherDream在一篇科普文章<>中详细介绍了流量劫持途径和方式. 流量劫持是一种古老的攻击方式,比如早已见惯的广告弹窗等,很多人已经对此麻木,并认为流量劫持不会造成 ...

  7. 栈的的顺序实例SeqStack实现

    1.#include <stdio.h>#include <stdlib.h>#include "SeqStack.h"/* run this progra ...

  8. object-c(oc)内存管理机制详解

    1.内存的创建和释放 让我们以Object-c世界中最最简单的申请内存方式展开,谈谈关于一个对象的生命周期.首先创建一个对象: 1 2 3 //“ClassName”是任何你想写的类名,比如NSStr ...

  9. 各种工具使用手册:http://www.itshouce.com.cn/linux/linux-tcpdump.html 关于tcpdump!!!!

    各种工具使用手册:http://www.itshouce.com.cn/linux/linux-tcpdump.html 关于tcpdump!!!! 实用tcpdump命令 //查看本机与mysql的 ...

  10. spring - 自定义注解

    本自定义注解的作用:用于控制类方法的调用,只有拥有某个角色时才能调用. java内置注解 1.@Target 表示该注解用于什么地方,可能的 ElemenetType 参数包括: ElemenetTy ...