使用 C# 对 phpbb 论坛进行身份验证
使用 C# 验证基于 phpbb 的论坛。
引言
我的一个网站是一个 phpBB 论坛,我最近为其添加了一个新功能。用户可以下载一个小型的 C# 应用程序,并可以通过关键词跟踪帖子。我的用户很满意,我决定添加新功能,例如在应用程序内发布帖子。问题是如何登录用户,因此我将在本文中解释如何创建/保持/使用会话。
背景
最重要的一点是 C# 和 phpBB 如何管理 cookie。
使用代码
第一步是准备要发送到论坛的 post 数据,作为字节数组。它将包含登录过程所需的所有信息:用户名、密码。一个重要的参数是名为“redirect
”的参数,因为login.php 脚本在登录成功时会将您重定向到主页。在这种情况下,不会收到任何 cookie。关键是指定一个无效的 redirect 参数,以便 phpBB 停止执行(以便可以接收 cookie)。
// Note: autologin is set to keep the session
// for next "X" days (X is set in phpbb admin)
StringBuilder builder = new StringBuilder();
builder.Append("autologin=1&login=true&username=" +
_user + "&password=" + _password + "&redirect=\n");
byte[] data = Encoding.ASCII.GetBytes(builder.ToString());
接下来,获取 phpBB 发送的 cookie
string[] keys = response.Headers.GetValues("Set-Cookie");>
cookie 应该包含这两个参数:phpbb2mysql_data
,它是一个序列化的数组,包含用户 ID 和其他信息,phpbb2mysql_sid
,它是会话密钥。如果用户名和密码不正确,phpbb2mysql_data
将包含一个 -1,表示登录失败。
如果登录成功,诸如 phpbb2mysql_sid
、phpbb2mysql_data
和用户名等信息将通过序列化存储在文件中。棘手的部分是这些信息会随着时间而变化。在下一次向论坛发送请求时,phpBB 将在数据库中检查您的会话并更新它。这意味着在每次发送的请求中,我们需要使用最新的 cookie 来更新 cookie。
以下是如何初始化类
PhpBBLogin.Instance.Domain = "www.your-domain.com";
//set this value from your admin area
PhpBBLogin.Instance.ValidityDaysForKey = 5;
PhpBBLogin.Instance.LoadCache();
//if something goes wrong, use LastError public member
PhpBBLogin.Instance.OnError += new EventHandler(Instance_OnError);
PhpBBLogin.Instance.OnLoginFinish += new EventHandler(Instance_OnLoginFinish);
PhpBBLogin.Instance.OnLogoutFinish += new EventHandler(Instance_OnLogoutFinish);
如何登录
PhpBBLogin.Instance.Login("username","password");
//This request is done in a separated thread.
//when it finishes the OnLoginFinish event is triggered
//and you can check the property PhpBBLogin.Instance.IsLogged to see if login succeed.
用户登录后创建新帖子
string message="new post";
string subject="subject";
int f=1; //this is the forum ID.
string post="Post";
PhpBBLogin.Instance.PostMessage(
"subject=" + subject + "&" +
"message=" + message + "&" +
"topictype=" + topictype + "&" +
"f=" + f + "&" +
"post=" + post+"&"+
"mode=newtopic");
历史
- 版本 1.0:提交于 2008.4.5。