Advertisement
Guest User

Untitled

a guest
Apr 6th, 2016
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. public class UsernamePasswordFlow {
  2. String username;
  3. String password;
  4. String clientId;
  5. String clientSecret;
  6. String tokenEndpoint = 'https://test.salesforce.com/services/oauth2/token';
  7.  
  8. public UsernamePasswordFlow(String username, String password, String clientId, String clientSecret) {
  9. this.username = username;
  10. this.password = password;
  11. this.clientId = clientId;
  12. this.clientSecret = clientSecret;
  13. }
  14.  
  15. public String requestAccessToken() {
  16. HttpRequest req = new HttpRequest();
  17. req.setEndpoint(tokenEndpoint);
  18. req.setMethod('POST');
  19. req.setBody(buildHttpQuery(new Map<String, String> {
  20. 'grant_type' => 'password',
  21. 'username' => username,
  22. 'password' => password,
  23. 'client_id' => clientId,
  24. 'client_secret' => clientSecret
  25. }));
  26.  
  27. Http http = new Http();
  28. HttpResponse resp = http.send(req);
  29.  
  30. Map<String, Object> m =
  31. (Map<String, Object>) JSON.deserializeUntyped(resp.getBody());
  32.  
  33. return (String) m.get('access_token');
  34. }
  35.  
  36. static String buildHttpQuery(Map<String, String> queryParams) {
  37. if (queryParams.isEmpty()) {
  38. return '';
  39. }
  40.  
  41. String[] params = new String[] {};
  42. for (String k : queryParams.keySet()) {
  43. String v = EncodingUtil.urlEncode(queryParams.get(k), 'UTF-8');
  44.  
  45. params.add(String.format('{0}={1}', new String[] { k, v }));
  46. }
  47.  
  48. return String.join(params, '&');
  49. }
  50. }
  51.  
  52. UsernamePasswordFlow upf = new UsernamePasswordFlow(
  53. 'my.name@example.com',
  54. 'mypassword',
  55. '3MdPGzpc3Iwg5lcwtc7HAprnDCVG9JNJ1CQBISiBA9bE1WXe_xlItLNdlxckCVyIo',
  56. '436267497522435674970'
  57. );
  58. String sessionId = upf.requestAccessToken();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement