如何使用AccountManager的身份验证令牌和Smack API认证到Google Talk?

8
这个问题与以下问题类似:如何使用authToken对Google Talk (XMPP, Smack)进行身份验证。如果您需要帮助,可以参考该问题的答案。
  1. I have android.accounts.AccountManager class and its methods to get authentication token for Google account:

    public AccountManagerFuture<Bundle> getAuthToken (Account account,
           String authTokenType, Bundle options, Activity activity,
           AccountManagerCallback<Bundle> callback, Handler handler)
    
  2. I know how to prepare authentication XML:

    jidAndToken ="\0" + UTF8(YOURUSERNAME@gmail.com) + "\0" + Auth
    

    (where "\0" is intended to be a single octet with value zero). Use this in the initial SASL auth:

    <auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' 
          mechanism='X-GOOGLE-TOKEN'>Base64(jidAndToken)</auth>
    


但是我无法像某人在这里为Facebook聊天所做的那样将其与Smack API集成:XMPP with Java Asmack library supporting X-FACEBOOK-PLATFORM

有人能帮助我吗?


我以前看过这个,但从未真正尝试过。您能否发布您的代码,以便我可以尝试自己做,并且也许我会找到解决方案。谢谢。 - Guillaume
2个回答

8

Vijay,

你的代码帮了我很多,谢谢!我在这里发布我的解决方案,用于使用AccountManager登录Google Talk的问题。到目前为止,我还没有找到完整的解决方案,但是我已经根据上面的代码开发了自己的解决方案,并纠正了一些不起作用的代码行。

解决方案分为两部分。第一部分基于上述思路和代码。它是创建SASLMechanism的子类:

import java.io.IOException;
import java.net.URLEncoder;

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

import android.util.Base64;
import android.util.Log;

public class GTalkOAuth2 extends SASLMechanism {
public static final String NAME="X-GOOGLE-TOKEN";


public GTalkOAuth2(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>" );

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

第二部分是使用它。没有其他示例给我带来的重要信息是,从AccountManager系统获取令牌时,令牌类型不是“ah”,而是“mail”。这个想法在与Google服务器进行直接通信以获取令牌的示例中已经存在,但在请求它时并没有出现在AccountManager中。将它们结合起来,您需要在驱动程序代码中执行以下操作。创建一个函数来获取令牌:
public String getAuthToken(String name)
{
    Context context = getApplicationContext();
    Activity activity = this;
    String retVal = "";
    Account account = new Account(name, "com.google");
    AccountManagerFuture<Bundle> accFut = AccountManager.get(context).getAuthToken(account, "mail", null, activity, null, null);
    try
    {
        Bundle authTokenBundle = accFut.getResult();
        retVal = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();
    }
    catch (OperationCanceledException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (AuthenticatorException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return retVal;
}

确保使用正确的SASL系统后,再调用它:

SASLAuthentication.registerSASLMechanism( GTalkOAuth2.NAME, GTalkOAuth2.class );
SASLAuthentication.supportSASLMechanism( GTalkOAuth2.NAME, 0 );
config.setSASLAuthenticationEnabled(true);

String saslAuthString = getAuthToken(acct.name);
connection = new XMPPConnection(config);
try {
    connection.connect();
    connection.login(name, saslAuthString);
} catch (XMPPException e) {
    // Most likely an expired token
    // Invalidate the token and start over. There are example of this available
}

愉快的谷歌交流!


我使用了这段代码,但是没有成功解决我的问题。我仍然没有从服务器得到任何响应。 - RajaReddy PolamReddy

1

我知道这个帖子有点老,但我想帮助一下... 这是我的类,它似乎可以使用 Smack 连接到 Gtalk 并使用令牌机制。说实话,我宁愿使用 OAuth2 .. 但这似乎还可以。确保你的用户名形式为"<your_user>@gmail.com",它应该可以工作:

public class GoogleTalkAuthentication extends SASLMechanism
{
    static
    {
        SASLAuthentication.registerSASLMechanism( "X-GOOGLE-TOKEN", GoogleTalkAuthentication.class );
        SASLAuthentication.supportSASLMechanism( "X-GOOGLE-TOKEN", 0 );
    }

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

    @Override
    protected String getName()
    {
        return "X-GOOGLE-TOKEN";
    }

    @Override
    public void authenticate( String username, String host, String password ) throws IOException, XMPPException
    {
        super.authenticate( username, host, password );
    }

    @Override
    protected void authenticate() throws IOException, XMPPException
    {
        String authCode = getAuthCode( authenticationId, 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( Base64.encode( jidAndToken.getBytes( "UTF-8" ) ) );

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

        // Send the authentication to the server
        getSASLAuthentication().send( stanza.toString() );
    }

    public static String getAuthCode( String username, String password ) throws IOException
    {
        StringBuilder urlToRead = new StringBuilder();
        urlToRead.append( "https://www.google.com/accounts/ClientLogin?accountType=GOOGLE&service=mail&" );
        urlToRead.append( "Email=" + username + "&" );
        urlToRead.append( "Passwd=" + password );

        URL url = new URL( urlToRead.toString() );
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod( "GET" );

        BufferedReader rd = new BufferedReader( new InputStreamReader( conn.getInputStream() ) );

        try
        {
            String line;
            while ( ( line = rd.readLine() ) != null )
            {
                if ( line.startsWith( "Auth=" ) )
                    return line.substring( 5 );
            }

            return null;
        }
        finally
        {
            rd.close();
        }
    }

    public static void main( String[] args ) throws IOException
    {
        String username = "";
        String password = "";

        String authCode = getAuthCode( username, password );
        String jidAndToken = "\0" + URLEncoder.encode( username, "utf-8" ) + "\0" + authCode;

        System.err.println( authCode );
        System.err.println( "Code:" + jidAndToken );
    }
}

祝你好运。


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