问题描述
MongooseIM
规定使用 JWT 代替用户名和密码进行授权。
在服务器端,文档 suggest 修改 mongooseim.toml
文件(可以在 /etc/mongooseim/mongooseim.toml
找到)
[auth]
methods = ["jwt"]
[auth.jwt]
secret.value = "top-secret123"
algorithm = "HS256"
username_key = "user"
但是如何通过 Gajim 或 Java 代码进行身份验证?
解决方法
让我们先了解一下幕后发生了什么。
而不是传递用户名-密码对。我们创建一个 JWT 令牌并发送它。 JWT 令牌是无状态的,这意味着如果拥有密钥,则可以将令牌解码和编码为原始消息。
这是 Java 中的工作代码。我们生成 JWT 令牌并发送该令牌而不是密码。为了生成 JWT 令牌,我们使用了 Auth0(您需要在类路径中添加它)。链接到 Maven project。
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.chat2.Chat;
import org.jivesoftware.smack.chat2.ChatManager;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jxmpp.jid.Jid;
import org.jxmpp.jid.impl.JidCreate;
import javax.net.ssl.X509TrustManager;
import java.net.InetAddress;
import java.util.Date;
public class JWTMain {
private final static String senderUsername = "jatin";
private final static String senderPassword = "abcd";
private final static String sendTo = "dad";
public static void main(String[] args) throws Exception {
Algorithm algorithm = Algorithm.HMAC256("top-secret123");
String token = JWT.create()
.withClaim("user",senderUsername) // they key needs to match with `username_key` in mongooseim.toml file
.withClaim(senderUsername,senderPassword)
.sign(algorithm);
System.out.println("Token generated: " + token);
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setSecurityMode(ConnectionConfiguration.SecurityMode.required)
.setUsernameAndPassword("jatin",token)
.setXmppDomain(JidCreate.domainBareFrom("localhost"))
.setHostAddress(InetAddress.getByName("localhost"))
.setPort(5222)
.setCustomX509TrustManager(new TrustAllManager())
.addEnabledSaslMechanism("PLAIN")
.build();
AbstractXMPPConnection connection = new XMPPTCPConnection(config);
AbstractXMPPConnection connect = connection.connect();
connection.login();
sendMessage("This message is being sent programmatically? " + new Date(),sendTo + "@localhost",connect);
}
private static void sendMessage(String body,String toJid,AbstractXMPPConnection mConnection) throws Exception {
Jid jid = JidCreate.from(toJid);
Chat chat = ChatManager.getInstanceFor(mConnection)
.chatWith(jid.asEntityBareJidIfPossible());
chat.send(body);
System.out.println("Message sent to : " + toJid);
}
}
class TrustAllManager implements X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs,String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs,String authType) {
}
}
如果您想使用 JWT 令牌登录 Gajim:
上述程序输出JWT令牌。您可以使用该令牌并在密码字段中提供该令牌。