MongooseIM有一项使用JWT代替用户名和密码进行授权的规定。
在服务器端,docs 建议用于修改mongooseim.toml文件(可在/etc/mongooseim/mongooseim.toml中找到)
[auth]
methods = ["jwt"]
[auth.jwt]
secret.value = "top-secret123"
algorithm = "HS256"
username_key = "user"但是如何从Gajim或Java代码进行身份验证呢?
发布于 2021-04-12 13:57:09
让我们先了解一下幕后发生了什么。
而不是传递用户名-密码对。我们创建一个JWT令牌并发送它。JWT令牌是无状态的,这意味着如果有秘密密钥,则可以对令牌进行解码并将其编码到原始消息中。
以下是Java中的工作代码。我们生成JWT令牌,并发送该令牌而不是密码。为了生成JWT令牌,我们使用了Auth0 (您需要在类路径中添加这一点)。链接到maven 项目。
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令牌。您可以使用该令牌并在密码字段中提供令牌。

https://stackoverflow.com/questions/67059744
复制相似问题