如何使用HumHub进行JWT SSO /自动登录

时间:2017-11-17 17:30:55

标签: php yii yii2 social-networking

有没有人知道在HumHub中使用JWT的好例子?

我在官方文档中找到了一个起点,但它没有明确解释在JWT的标头或有效负载中应该发送什么来使SSO /自动登录工作。

是用户ID,用户电子邮件......?

此外,看起来它只适用于企业版,是否有可以免费使用的示例?

还有其他方法可以在HumHub中自动登录吗?

1 个答案:

答案 0 :(得分:0)

对于任何不认识的人,您都需要安装企业版JWT才能正常工作。如果安装了社区版,则可以将企业作为模块安装。它将要求您提供一个许可证密钥,您可以每月以99欧元的价格购买许可证密钥,但是如果您很好地询问他们的支持部门,他们会给您提供试用许可证:)。

humhub/protected/modules/enterprise/modules/jwt/examples/php/index.php中,有一些示例代码可用于验证用户身份。

// Load JWT Libary
require __DIR__ . '/vendor/autoload.php';

use Firebase\JWT\JWT;

// Configuration
$key = 'your shared key';
$domain = "http://humhub.example.com";
$urlRewritingEnabled = false;

// Build token including your user data
$now = time();
$token = array(
    'iss' => 'example',
    'jti' => md5($now . rand()),
    'iat' => $now,
    'exp' => $now + 60,
    'username' => 'j.doe',
    'firstname' => 'John',
    'lastname' => 'Doe',
    'email' => 'john.doe@example.com',
);

// Create JWT token
$jwt = JWT::encode($token, $key);

// Redirect user back to humhub
if ($urlRewritingEnabled) {
    $location = $domain . '/user/auth/external?authclient=jwt';
} else {
    $location = $domain . '/index.php?r=/user/auth/external&authclient=jwt';
}
$location .= "&jwt=" . $jwt;

header("Location: " . $location);

所以我要做的就是将此代码复制到我自己的PHP文件中,例如https://test.example.com/jwtclient.php,然后在humhub / protected / config / common.php中添加以下内容:

return [
    // ...
    'components' => [
        // ...
        'authClientCollection' => [
            'clients' => [
                // ...
                'jwt' => [
                    'class' => 'humhub\modules\enterprise\modules\jwt\authclient\JWT',
                    'url'       => 'https://test.example.com/jwtclient.php',
                    'sharedKey' => 'your shared key', // same as jwtclient.php
                    // Other configuration options
                    'title' => 'Company SSO Login',
                    // Automatic login, when allowed IP matches
                    'autoLogin' => true,
                    // Limit allowed JWT IPs
                    // 'allowedIPs' => ['localhost'],
                    // Leeway (seconds) for token validation
                    'leeway' => 60
                ]
            ]
        ]
        // ...
    ]
    // ...
];

将会发生的是,如果您转到humhub.example.com,它将重定向到test.example.com/jwtclient.php,然后重定向回humhub.example.com,并将jwt附加到URL。就是这样。

我还通知您,也不需要使用LDAP即可工作。只要确保您的数据库用户在表user_password中没有密码即可。

我希望这也会对您有所帮助,因为它也使我大开眼界!