栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

连接到Facebook XMMP MD5-DIGEST的问题

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

连接到Facebook XMMP MD5-DIGEST的问题

最后,由于使用了no.good.at.coding编码和骚扰的建议,我已经能够连接到Facebook聊天了。这段代码是Asmack库的机制(Android的Smack端口)。对于Smack库,必须使用no.good.at.coding机制。

SASLXFacebookPlatformMechanism.java:

import java.io.IOException;import java.io.UnsupportedEncodingException; import java.net.URLEnprer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map;  import org.apache.harmony.javax.security.auth.callback.CallbackHandler; import org.apache.harmony.javax.security.sasl.Sasl; import org.jivesoftware.smack.SASLAuthentication; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.sasl.SASLMechanism; import org.jivesoftware.smack.util.base64;public class SASLXFacebookPlatformMechanism extends SASLMechanism {          private static final String NAME   = "X-FACEBOOK-PLATFORM";          private String   apiKey = "";         private String   applicationSecret = "";         private String   sessionKey        = "";                   public SASLXFacebookPlatformMechanism(SASLAuthentication saslAuthentication)         {      super(saslAuthentication);         }          @Override         protected void authenticate() throws IOException, XMPPException         {       getSASLAuthentication().send(new AuthMechanism(NAME, ""));         }          @Override         public void authenticate(String apiKeyAndSessionKey, String host,  String applicationSecret) throws IOException, XMPPException         {      if (apiKeyAndSessionKey == null || applicationSecret == null)      {   throw new IllegalArgumentException("Invalid parameters");      }       String[] keyArray = apiKeyAndSessionKey.split("\|", 2);      if (keyArray.length < 2)      {   throw new IllegalArgumentException(          "API key or session key is not present");         }this.apiKey = keyArray[0];          this.applicationSecret = applicationSecret;          this.sessionKey = keyArray[1];this.authenticationId = sessionKey;          this.password = applicationSecret;          this.hostname = host;String[] mechanisms = { "DIGEST-MD5" }; Map<String, String> props = new HashMap<String, String>();          this.sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,this);         authenticate();        }   @Override  public void authenticate(String username, String host, CallbackHandler cbh)throws IOException, XMPPException  {          String[] mechanisms = { "DIGEST-MD5" };          Map<String, String> props = new HashMap<String, String>();          this.sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,cbh);          authenticate();        }      @Override     protected String getName()        {         return NAME;  }   @Override  public void challengeReceived(String challenge) throws IOException  {          byte[] response = null;if (challenge != null)          {       String depredChallenge = new String(base64.depre(challenge));       Map<String, String> parameters = getQueryMap(depredChallenge);        String version = "1.0";       String nonce = parameters.get("nonce");       String method = parameters.get("method");        long callId = new GregorianCalendar().getTimeInMillis();        String sig = "api_key=" + apiKey + "call_id=" + callId + "method=" + method + "nonce=" + nonce + "session_key=" + sessionKey + "v=" + version + applicationSecret;     try       {    sig = md5(sig);       }      catch (NoSuchAlgorithmException e)       {    throw new IllegalStateException(e);       }        String composedResponse = "api_key=" + URLEnprer.enpre(apiKey, "utf-8") + "&call_id=" + callId + "&method="+ URLEnprer.enpre(method, "utf-8") + "&nonce="+ URLEnprer.enpre(nonce, "utf-8")+ "&session_key="+ URLEnprer.enpre(sessionKey, "utf-8") + "&v="+ URLEnprer.enpre(version, "utf-8") + "&sig="+ URLEnprer.enpre(sig, "utf-8");response = composedResponse.getBytes("utf-8");     }    String authenticationText = "";    if (response != null)   {authenticationText = base64.enpreBytes(response, base64.DONT_BREAK_LINES);   }     // Send the authentication to the server   getSASLAuthentication().send(new Response(authenticationText));          }   private Map<String, String> getQueryMap(String query)  {          Map<String, String> map = new HashMap<String, String>();          String[] params = query.split("\&");for (String param : params)          {       String[] fields = param.split("=", 2);       map.put(fields[0], (fields.length > 1 ? fields[1] : null));          }return map;      }   private String md5(String text) throws NoSuchAlgorithmException,UnsupportedEncodingException  {          MessageDigest md = MessageDigest.getInstance("MD5");          md.update(text.getBytes("utf-8"), 0, text.length());          return convertToHex(md.digest());  }   private String convertToHex(byte[] data)  {          StringBuilder buf = new StringBuilder();          int len = data.length;for (int i = 0; i < len; i++)          {       int halfByte = (data[i] >>> 4) & 0xF;       int twoHalfs = 0;        do       {    if (0 <= halfByte && halfByte <= 9)    { buf.append((char) ('0' + halfByte));    }    else    { buf.append((char) ('a' + halfByte - 10));    }    halfByte = data[i] & 0xF;       }      while (twoHalfs++ < 1);          }return buf.toString();      }         }

要使用它:

ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com", 5222); config.setSASLAuthenticationEnabled(true); XMPPConnection xmpp = new XMPPConnection(config); try {         SASLAuthentication.registerSASLMechanism("X-FACEBOOK-PLATFORM", SASLXFacebookPlatformMechanism.class);         SASLAuthentication.supportSASLMechanism("X-FACEBOOK-PLATFORM", 0);         xmpp.connect();         xmpp.login(apiKey + "|" + sessionKey, sessionSecret, "Application"); } catch (XMPPException e) {         xmpp.disconnect();         e.printStackTrace(); }

apiKey是在Facebook的“应用程序设置”页面中提供的API密钥。sessionKey是访问令牌的第二部分。如果令牌的格式为AAA | BBB |
CCC,则BBB是会话密钥。sessionSecret是使用旧的REST
API和auth.promoteSession方法获得的。要使用它,需要使Http到达该URL:

https://api.facebook.com/method/auth.promoteSession?access_token=yourAccessToken

尽管有Facebook
Chat文档,但仍需要使用您的应用程序秘密密钥,只有当我使用返回了该REST方法的密钥时,我才能够使它起作用。为了使该方法有效,您必须在应用程序设置的“高级”选项卡中禁用“禁用不赞成使用的身份验证方法”选项。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/569957.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号