使用authToken连接到GTalk服务器(XMPP,Smack)

5
我正在编写一个聊天应用程序,它连接到XMPP服务器。如果用户选择,我想给他们提供连接到其Google聊天帐户的选项,而无需输入凭据......我使用了Google的JavaScript API来弹出Google登录表单,成功登录后会生成访问令牌。现在,使用该访问令牌和用户的电子邮件ID,我想与XMPP服务器通信,以便用户可以与他们的Gtalk好友聊天。
我搜索了很多但没有找到解决方案。我发现需要用户密码,但我想使用访问令牌。
SASLAuthentication.registerSASLMechanism("X-OAUTH2", GoogleConnectSASLMechanism.class);
SASLAuthentication.supportSASLMechanism("X-OAUTH2", 0);
config = new ConnectionConfiguration(server, 5222, 'gmail.com');
config.setSASLAuthenticationEnabled(true);
config.setSecurityMode(SecurityMode.enabled);
config.setReconnectionAllowed(true);

connection = new XMPPConnection(config);
connection.connect();

 connection.login(username, session_key, "Chat");
 setServer(SERVER_TYPE.GTALK);

GoogleConnectSASLMechanism.java的代码如下:

    package org.jivesoftware.smack;

    import java.io.IOException;
    import java.net.URLEncoder;
    import java.io.UnsupportedEncodingException;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.GregorianCalendar;
    import java.util.HashMap;
    import java.util.Map;

    import javax.security.auth.callback.CallbackHandler;
    import javax.security.sasl.Sasl;

    import org.jivesoftware.smack.SASLAuthentication;
    import org.jivesoftware.smack.XMPPException;
    import org.jivesoftware.smack.packet.Packet;
    import org.jivesoftware.smack.sasl.SASLMechanism;
    import org.jivesoftware.smack.util.Base64;


    public class GoogleConnectSASLMechanism extends SASLMechanism {
    public static final String NAME="X-OAUTH2";


    public GoogleConnectSASLMechanism(SASLAuthentication saslAuthentication) {
        super(saslAuthentication);
    }

    @Override
    protected String getName() {
        return NAME;
    }

    static void enable() { }

    @Override
    protected void authenticate() throws IOException, XMPPException
    {
        String authCode = password;
        String jidAndToken = "\0" + URLEncoder.encode( authenticationId, "utf-8" ) + "\0" + authCode;

        StringBuilder stanza = new StringBuilder();
        //stanza.append( "<auth mechanism=\"" ).append( getName() );
        //stanza.append( "\" xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">" );
       // stanza.append( new String(Base64.encode( jidAndToken.getBytes( "UTF-8" ), Base64.DEFAULT ) ) );
        stanza.append( "<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"" ).append( getName() );
        stanza.append( "\" auth:service=\"oauth2\"" );
        stanza.append( "\" xmlns:auth=\"http://www.google.com/talk/protocol/auth\">" );
        stanza.append( "\" base64(\"\\0"+user_name+"\\0" + authCode+")" );



        stanza.append( "</auth>" );

        //Log.v("BlueTalk", "Authentication text is "+stanza);
        // Send the authentication to the server
        getSASLAuthentication().send( new Auth2Mechanism(stanza.toString()) );
    }

    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();
        }
        }
    }

但是我从connection.login()得到了一个异常,提示"用户名或密码不正确"

要做到这一点,我需要获取使用Google帐户的权限,获取令牌并使用该令牌对Google Talk(XMPP服务器,使用Smack)进行身份验证。

问题是...如果我知道登录名和令牌,如何对GTalk服务器进行身份验证呢?

非常感谢任何帮助... :)


嗨,imVJ,我也有与你上面提到的相同需求,请指导我如何获取访问令牌,连接到gtalk服务器以及如何与用户聊天? - user2709752
3个回答

3

Vijay,

请将您的身份验证函数更改如下:

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);
}

这与您原始的认证功能相同。我只是改变了诗歌格式。


这里的 usernamesessionKey 值是什么?我无法解决这个问题。 - RajaReddy PolamReddy

2

您的问题似乎出在这一行:

stanza.append( "\" base64(\"\\0"+user_name+"\\0" + authCode+")" );

所以我认为您的authenticate函数应该是这个样子:

protected void authenticate() throws IOException, XMPPException
{
    String authCode = password;
    String jidAndToken = "\0" + authenticationId + "\0" + authCode;

    StringBuilder stanza = new StringBuilder();
    stanza.append("<auth mechanism=\"").append( getName());
    stanza.append("\" xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">");
    stanza.append(new String(Base64.encode(jidAndToken.getBytes("UTF-8"), Base64.DEFAULT)));
    stanza.append("</auth>");

    //Log.v("BlueTalk", "Authentication text is "+stanza);
    // Send the authentication to the server
    getSASLAuthentication().send( new Auth2Mechanism(stanza.toString()) );
}

所以,它更像是你的已注释代码。在内容中,不应出现base64(..)。那里只应该有一个Base64编码的字符串。
在您帮助我解决此相同主题的线程时,我成功地登录了。

我认为这段代码与你原来注释的代码唯一的区别在于 authenticationId 没有进行 URL 编码。根据我的经验,它不需要被编码(毕竟它已经进行了 base64 编码!) - dexy

1
我非常感激Ketan的回答,它拯救了我的整个项目。我已经为这个问题苦斗了好几天... 无论如何,我希望更多的人能从这篇文章中找到他们的解决方案。
我使用Smack 3.4,但我认为这个答案也适用于更高版本。
我只是详细解释了Ketan的答案,这对我有用(刚注册Stack Overflow,无法评论原始答案)。
只需覆盖GoogleConnectSASLMechanism类的authenticate()方法,例如在本地创建一个GoogleConnectSASLMechanism类,而不是使用Smack提供的类。
Google拥有自己的OAUth2机制,具有自定义属性。这就是为什么在Smack中,“X-OAUTH2是实验性的”。可以在Smack的文档here中找到这个声明。 "custom attributes"是xml代码片段: <auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" mechanism="X-OAUTH2" auth:service="oauth2" xmlns:auth="http://www.google.com/talk/protocol/auth"> base64("\0" + user_name + "\0" + oauth_token) </auth>
这可以在google's instruction中找到。Smack无法使用X-OAUth2的原因是它的报文中不包含此XML片段。因此,解决方案就是添加它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接