【问题标题】:How to authenticate to Google Talk with AccountManager's authentication token using Smack API?如何使用 Smack API 使用 AccountManager 的身份验证令牌向 Google Talk 进行身份验证?
【发布时间】:2011-11-13 13:50:07
【问题描述】:

这个问题类似于:Authenticate to Google Talk (XMPP, Smack) using an authToken

  1. 我有 android.accounts.AccountManager 类及其获取 Google 帐户身份验证令牌的方法:

    public AccountManagerFuture<Bundle> getAuthToken (Account account,
           String authTokenType, Bundle options, Activity activity,
           AccountManagerCallback<Bundle> callback, Handler handler)
    
  2. 我知道如何准备身份验证 XML:

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

    (其中“\0”是一个值为零的八位字节)。在初始 SASL 身份验证中使用它:

    <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

有人可以帮我吗?

【问题讨论】:

  • 我以前看过这个,但从未真正尝试过。您介意发布您的代码,以便我可以尝试自己做,也许我会找到解决方案。谢谢

标签: android xmpp smack


【解决方案1】:

我知道这个线程有点老了,但我想我会帮忙......所以这是我的课程,它似乎可以使用令牌机制连接到 Gtalk。老实说,我宁愿选择 oauth2 .. 但这似乎没问题。确保您的用户名类似于 "&lt;your_user&gt;@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 );
    }
}

祝你好运。

【讨论】:

    【解决方案2】:

    维杰,

    您的代码对我帮助很大,谢谢!我在这里发帖是为了解决使用 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 系统获取令牌时,令牌类型不是“啊”而是“邮件”。这个想法出现在与谷歌服务器直接通信以获取令牌的示例中,但不是从 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
    }
    

    Google Talk 愉快!

    【讨论】:

    • 我正在使用此代码,但未能成功解决我的问题。我仍然没有得到服务器的响应。
    猜你喜欢
    • 2011-09-05
    • 1970-01-01
    • 2012-12-23
    • 2017-04-11
    • 2012-08-01
    • 2015-09-12
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    相关资源
    最近更新 更多