我在我的应用程序中使用 GoogleTalk XMPP 进行聊天。无法通过使用用户名和 AuthToken 来创建 XMPP 连接Google authentication
。
现在我正在使用GoogleAuth2
for authentication
。我尝试使用 access_token 和电子邮件进行这样的身份验证。通过使用SASLMechanism
. 但我无法连接到 xmpp 服务器,它给出了这样的错误SASL authentication failed using mechanism X-OAUTH2
ConnectionConfiguration config = new ConnectionConfiguration(server_host, SERVER_PORT, SERVICE_NAME);
config.setSASLAuthenticationEnabled(true);
m_connection = new XMPPConnection(config);
SASLAuthentication.registerSASLMechanism("X-OAUTH2", GoogleConnectSASLMechanism.class);
SASLAuthentication.supportSASLMechanism("X-OAUTH2", 0);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
try {
m_connection.connect();
} catch (XMPPException e) {
e.printStackTrace();
}
这是我正在使用的课程SASLMechanism.
public class GoogleConnectSASLMechanism extends SASLMechanism {
public static final String NAME = "X-OAUTH2";
private String username = "";
private String sessionKey = "";
public GoogleConnectSASLMechanism(SASLAuthentication saslAuthentication) {
super(saslAuthentication);
}
@Override
protected String getName() {
return NAME;
}
static void enable() {
}
@Override
protected void authenticate() throws IOException, XMPPException {
final StringBuilder stanza = new StringBuilder();
byte response[] = null;
stanza.append("<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\"" +
"mechanism=\"X-OAUTH2\"" +
"auth:service=\"oauth2\"" +
"xmlns:auth= \"http://www.google.com/talk/protocol/auth\">");
String composedResponse = "\0" + username + "\0" + sessionKey;
response = composedResponse.getBytes("UTF-8");
String authenticationText = "";
if (response != null) {
authenticationText = Base64.encodeBytes(response, Base64.DONT_BREAK_LINES);
}
stanza.append(authenticationText);
stanza.append("</auth>");
// Send the authentication to the server
Packet p=new Packet() {
@Override
public String toXML() {
return stanza.toString();
}
};
getSASLAuthentication().send(p);
}
public class Auth2Mechanism extends Packet {
String stanza;
public Auth2Mechanism(String txt) {
stanza = txt;
}
public String toXML() {
return stanza;
}
}
/**
* Initiating SASL authentication by select a mechanism.
*/
public class AuthMechanism extends Packet {
final private String name;
final private String authenticationText;
public AuthMechanism(String name, String authenticationText) {
if (name == null) {
throw new NullPointerException(
"SASL mechanism name shouldn't be null.");
}
this.name = name;
this.authenticationText = authenticationText;
}
public String toXML() {
StringBuilder stanza = new StringBuilder();
stanza.append("<auth mechanism=\"").append(name);
stanza.append("\" xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">");
if (authenticationText != null
&& authenticationText.trim().length() > 0) {
stanza.append(authenticationText);
}
stanza.append("</auth>");
return stanza.toString();
}
}
}
如何Google Auth
使用 SASL 机制进行身份验证?