一个关于WebService身份验证的问题,
有2个WebMethod
第1个用来身份验证,第1个验证成功后用户才能访问第2个,
如何限制用户权限?
在Web.config中设置能不能达到这个效果??
给点代码示范一下

解决方案 »

  1.   

    用WSE:http://msdn.microsoft.com/webservices/building/wse/default.aspx?pull=/library/en-us/dnwse/html/wssecauthwse.asp
      

  2.   

    参考:
    //鉴权,用户首先访问它得到ticket
    [WebMethod()]
    public string GetAuthorizationTicket(string userName, string password)
    {
    // try to authenticate the user
    string userID; try
    {
    userID = SqlHelper.ExecuteScalar(dbConn, "AuthenticateUser", userName, password).ToString();
    }
    finally
    {
    dbConn.Close();
    }

    if (userID == null)
    {
    // The user name and password combination is not valid.
    return null;
    } // create the ticket
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(userID, false, 1);
    string encryptedTicket = FormsAuthentication.Encrypt(ticket); // get the ticket timeout in minutes
    AppSettingsReader configurationAppSettings = new AppSettingsReader();
    int timeout = (int) configurationAppSettings.GetValue("AuthenticationTicket.Timeout", typeof(int)); // cache the ticket
    Context.Cache.Insert(encryptedTicket, userID, null, DateTime.Now.AddMinutes(timeout), TimeSpan.Zero); return encryptedTicket;
    }//用户传入Ticket,系统判断ticket的有效性
    [WebMethod(Description="Returns a project DataSet containing exactly one table named 'Projects'.")]
    public DataSetProjects GetProjects(string ticket)
    {
    if (!IsTicketValid(ticket, false))
    return null; DataSetProjects ds = new DataSetProjects();
    daProjects.Fill(ds, "Projects"); return ds;
    } private bool IsTicketValid(string ticket, bool IsAdminCall)
    {
    if (ticket == null || Context.Cache[ticket] == null)
    {
    // not authenticated
    return false;
    }
    else
    {
    // check the user authorization
    int userID = int.Parse(FormsAuthentication.Decrypt(ticket).Name); DataSet ds;

    try
    {
    ds = SqlHelper.ExecuteDataset(dbConn, "GetUserInfo", userID);
    }
    finally
    {
    dbConn.Close();
    }
                    
    UserInformation userInfo = new UserInformation(); //With ds.Tables(0).Rows(0)
    DataRow dr = ds.Tables[0].Rows[0]; userInfo.IsAdministrator = (bool) dr["IsAdministrator"];
    userInfo.IsAccountLocked = (bool) dr["IsAccountLocked"]; if (userInfo.IsAccountLocked)
    {
    return false;
    }
    else
    {
    // check admin status (for admin required calls)
    if (IsAdminCall && !userInfo.IsAdministrator)
    return false; return true;
    }
    }
    }
      

  3.   

    注意,2次调用WebMethod,其间状态是不保持的,再说不见得调用的是服务器上同一
    个对象,可以考虑使用(服务器端)EnableSession=true + (客户端)CookieContainerhttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebServicesWebMethodAttributeClassEnableSessionTopic.asp
    但推荐使用WES2,但一般安全要求不是很高的情形下,也可以参考使用Soap Header
    http://www.codeproject.com/cs/webservices/authforwebservices.asp