I am trying to send an send a request using get method of HTTP Request and I need to pass the username and password of Named credentials in the URL as username as clientID and password as the client secret  Below is the code   @future (callout=true)     webservice static void requestCall(String first, String second, String third) {          HttpRequest req = new HttpRequest();         HttpResponse res = new HttpResponse();         Http http = new Http();        String url ='?first=' + first+ '&amp;second=' + second+'&amp;third=' + third+'&amp;client_id=' + '{!HTMLENCODE($Credential.Username)}' + '&amp;client_secret=' + '{!HTMLENCODE($Credential.Password)}';          req.setEndpoint('callout:Named_Credentials'+url);         req.setMethod('GET');         req.setCompressed(true);         req.setTimeout(120000);         try {             res = http.send(req);             System.debug(req);         } catch(System.CalloutException e) {             System.debug('Callout error: '+ e);             System.debug(res.toString());         } }   I am getting a response following response in the debug  {   "message": "Bad Request" }   Also, when I store the client Id and client secret in custom setting and use them, it is working fine and getting a proper response.  Any suggestions or help that how can I fetch the username and password from Named credentials
28284
I have a named credential as follows:  Name   Test_Credential URL    https://www.somesite.com Identity Type    Named Principal Authentication Protocol    Password Authentication Username   foobar Password   mySomeSiteDeveloperKey Generate Authorization Header   FALSE Allow Merge Fields in HTTP Header    TRUE Allow Merge Fields in HTTP Body     TRUE   The service that I am trying to authenticate against uses URL parameters to pass in the developer key and username. Is there any way to use  to pass those in to the URL?   The Named Credential attributes seem not to get decoded until the request is actually sent, as debugging the endpoint, or headers if I set them per the linked doc, show the un-merged data. I can get the callout to go to the right place, and return the expected error because the auth information is not provided. Anybody know of a "show me my HTTP request" site that I could point to to get a better idea of how this works?  I've tried both of these:  req.setEndpoint('callout:Test_Credential/api/action?id={!$Credential.Password}&amp;account={!$Credential.UserName}');  req.setEndpoint('callout:Test_Credential/api/action' + '?id=' + '{!$Credential.Password}' + '&amp;account=' + '{!$Credential.UserName}');   (Edited to remove the part about $Credential vs. $Test_Credential as I was able to determine that it is the former, and see the merged creds by calling out to .)
119509
We are setting up a Salesforce Community and our community members should be able to automatically login using the credentials from an extenal platform when clicking on a link from this platform. I'm trying to generate a JWT token (Please find below the class I've made to generate the JWT) and I've created a connected app to get a consumer key. public inherited sharing class JWTAuthFlow {  public static string createJWT(String iss, String sub, String aud, String endpoint){     // Static Resource to get the Key that will be used for Crypto-Sign     StaticResource jwtPrivate = [SELECT Id, Body FROM StaticResource WHERE Name = 'JWT_Private_key' LIMIT 1];     String privateKey = jwtPrivate.Body.toString();          //Create Body of the Json that contains enpoint URL, Consumer Key, Type, ect     JSONGenerator jsonHeader = JSON.createGenerator(false);     jsonHeader.writeStartObject();     jsonHeader.writeStringField('alg', 'RS256');     jsonHeader.writeStringField('typ', 'JWT');     jsonHeader.writeEndObject();     String encodedHeader = EncodingUtil.base64Encode(Blob.valueOf(jsonHeader.getAsString()));          JSONGenerator jsonBody = JSON.createGenerator(false);     jsonBody.writeStartObject();     jsonBody.writeStringField('iss', iss);     jsonBody.writeStringField('sub', sub);     jsonBody.writeStringField('aud', aud);     jsonBody.writeNumberField('exp', Datetime.now().addMinutes(3).getTime());     jsonBody.writeEndObject();     String encodedBody = EncodingUtil.base64Encode(Blob.valueOf(jsonBody.getAsString()));     String jwtRequest = encodedHeader + '.' + encodedBody;          // Sign JWT Request     Blob key = EncodingUtil.base64Decode(privateKey);     Blob rs256sig = Crypto.sign('RSA-SHA256', Blob.valueOf(jwtRequest), key);     String signature = EncodingUtil.base64Encode(rs256sig);     signature = signature.replace('+', '-');     signature = signature.replace('/', '_');     String signedJwtRequest = jwtRequest + '.' + signature;          // Create the payload     String payload = 'grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer';     payload += '&amp;assertion=' + signedJwtRequest;        // Create a HttpRequest and send it to server     Http httpObj = new Http();     HttpRequest req = new HttpRequest();     HttpResponse res;     req.setEndpoint(endpoint);     req.setMethod('POST');     req.setHeader('Content-Type', 'application/x-www-form-urlencoded');     req.setBody(payload);     res = httpObj.send(req);          if(res.getStatusCode() == 200){         Map&lt;String, Object&gt; mapTokenResponse = (Map&lt;String, Object&gt;)JSON.deserializeUntyped(res.getBody());         return (String)mapTokenResponse.get('access_token');     }          return res.getBody(); }  } I have the following error when I try to generate a JWT: 'Unrecognized base64 character:-' (I can see from system.debug that it generates the header and the body, but not the signature). I don't know what I'm doing wrong ? It's the first time I'm working with JWT so I don't know if I've missed something. The developer from the external app is waiting for the token, and the returnURL (the path). Is there something else I need to give him ?
48046
I'm looking for a way to create an HttpRequest in Apex using a POST method. When I do it, I hit this error:  {     "message": "HTTP Method 'POST' not allowed. Allowed are HEAD,GET,PATCH,DELETE",     "errorCode": "METHOD_NOT_ALLOWED" }   When I try to make a PATCH request (to update), there's an exception appearing in the developer console:  FATAL_ERROR System.CalloutException: Invalid HTTP method: PATCH   Just to give a quick background, I'm trying to use Salesforce's REST API from inside my Apex class to update an CurrencyType record. It's working outside Salesforce (using curl for example).  Thanks.
44586
[I am re-posting this; I posted it as "guest" inadvertently.]  soapUI 5.5.0, community edition.  Created REST requests with parameters (style = plain). Wanted to use them in request body as variables, but that did not work. Tried "${#firstName}" and "{firstName}"  The result was  "firstName": "",[\n]"  The call works fine with all values specified.
75965
When comparing an HTTP GET to an HTTP POST, what are the differences from a security perspective? Is one of the choices inherently more secure than the other? If so, why?  I realize that POST doesn't expose information on the URL, but is there any real value in that or is it just security through obscurity? Is there ever a reason that I should prefer POST when security is a concern?  Edit: Over HTTPS, POST data is encoded, but could URLs be sniffed by a 3rd party? Additionally, I am dealing with JSP; when using JSP or a similar framework, would it be fair to say the best practice is to avoid placing sensitive data in the POST or GET altogether and using server side code to handle sensitive information instead?
18923
I am trying to write a test for a trigger that is firing a future apex callout :  The trigger calls the callBillingService method from this class:  public class BillingCalloutService {     //Implement business and callout logic methods here     @Future(callout=true)     public static void callBillingService(List&lt;Id&gt; recordIds) {         List&lt;Project__c&gt; projects = [Select Id, ProjectRef__c,Billable_Amount__c from Project__c Where Id = :recordIds];          List&lt;Project__c&gt; projectsToUpdate = new List&lt;Project__c&gt;();          String username = ServiceCredentials__c.getValues('BillingServiceCredential').Username__c;         String password = ServiceCredentials__c.getValues('BillingServiceCredential').Password__c;          String auth = username + ':' + password;         String encodedAuth = EncodingUtil.base64Encode(Blob.valueOf(auth));          for(Project__c p : projects) {              BillingServiceProxy.InvoicesPortSoap11 service = new BillingServiceProxy.InvoicesPortSoap11();             service.inputHttpHeaders_x = new Map&lt;String, String&gt;();             service.inputHttpHeaders_x.put('Authorization', 'Basic ' + encodedAuth);              BillingServiceProxy.project project = new BillingServiceProxy.project();             project.username = username;             project.password = password;             project.projectRef = p.ProjectRef__c;             project.billAmount = p.Billable_Amount__c;              if(service.billProject(project).equals('ok')){                 projectsToUpdate.add(new Project__c(ProjectRef__c = p.ProjectRef__c, Status__c = 'Billed'));             }         }         shouldIRun.stopTrigger();         upsert projectsToUpdate ProjectRef__c;     } }   Error     Methods defined as TestMethod do not support Web service callouts   Test Class  @IsTest private class BillingCalloutServiceTest {      @IsTest     private static void testBillingCalloutService() {     Account a = new Account(Name = 'Acme');     insert a;     Opportunity o = new Opportunity(Name='Test', StageName='Submitted Project', AccountId=a.Id, Amount=1000, CloseDate=Date.Today());     insert o;     Project__c p = new Project__c(Status__c='Running',Start_Date__c=Date.Today(),End_Date__c=Date.Today(),Billable_Amount__c=10000,ProjectRef__c='projectX',Opportunity__c=o.Id);     insert p;      insert new ServiceCredentials__c(Name='BillingServiceCredential',Username__c='toto', Password__c='azerty');      Test.startTest();     Test.setMock(HttpCalloutMock.class, new BillingCalloutServiceMock());       p.Status__c = 'Billable';       update p;     Test.stopTest();     // runs callout and check results     p = [select Status__c from Project__c where id =: p.id];     System.assertEquals('Billed', p.Status__c);     }  }
47668
I am tasked with writing an authentication component for an open source JAVA app.  We have an in-house authentication widget that uses https.  I have some example php code that accesses the widget which uses cURL to handle the transfer.    My question is whether or not there is a port of cURL to JAVA, or better yet, what base package will get me close enough to handle the task?   Update:  This is in a nutshell, the code I would like to replicate in JAVA:  $cp = curl_init(); $my_url = "https://" . AUTH_SERVER . "/auth/authenticate.asp?pt1=$uname&amp;pt2=$pass&amp;pt4=full"; curl_setopt($cp, CURLOPT_URL, $my_url); curl_setopt($cp, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($cp); curl_close($cp);   , I think you're on the right track, I think I'm going to end up using HttpsURLConnection and then picking out what I need from the response.
109761
I have getting the below JSON on using JSON.serialize  [ {   "lname" : "Singh",   "hcpZipCode" : null,   "hcpState" : null,   "hcpEmail" : "test@test.com",   "hcpCity" : null,   "hcpAddLine1" : null,   "fname" : "Abhey",   "countryCode" : "AUS" } ]   I don't know why this '[' is coming at the begining.I don't need this '[' at the begining due to which I am getting System.JSONException: Malformed JSON: Expected '{' at the beginning of object  code     public PageReference step2() {         string JSONstr='';        List&lt;HCPRequest&gt; conWrapList = new List&lt;HCPRequest&gt;();        HCPRequest tempcontactWrapper = new HCPRequest();        tempcontactWrapper.fname='Abhey';        tempcontactWrapper.lname='Singh';        tempcontactWrapper.countryCode='AUS';        tempcontactWrapper.hcpEmail=contact.Email;         conWrapList.add(tempcontactWrapper);          JSONstr = JSON.serializePretty(conWrapList);         System.debug('\n******'+JSONstr +'\n******');          String clientId = 'xy';         String clientSecret = 'x';          //We can also store our username password in custom setting.         String username='x';//salesforce username          String password='x';//password+securitytoken         // Generating the Access Token         HttpRequest req = new HttpRequest();         req.setMethod('POST');         req.setEndpoint('https://test.salesforce.com/services/oauth2/token');// this is the OAuth endpoint where this request will be hit         req.setBody('grant_type=password&amp;client_id='+clientId+'&amp;client_secret='+clientSecret+'&amp;username='+username+'&amp;password='+password);          Http http = new Http();         HTTPResponse res = http.send(req);         String str = res.getBody();         wrapObj = (Wrapper)Json.deserialize(str,Wrapper.class);         accessToken = wrapObj.access_token;         instanceUrl = wrapObj.instance_url;          HttpRequest req1 = new HttpRequest();         string response='';         req1.setMethod('POST');         //req.setEndpoint(wrapObj.instance_url+'/services/apexrest/Account/getAccountById?name=champaKAli');         string EndPt = 'y';         string email='test@test.com';         req1.setEndpoint(EndPt);         req1.setHeader('Authorization', 'OAuth '+wrapObj.access_token);          req1.setHeader('Content-Type', 'application/json');          //req1.setBody('{"request":{"lname" : "Singh","hcpZipCode" : null,"hcpState" : null,"hcpEmail" : "test@test.com","hcpCity" : null,"hcpAddLine1" : null,"fname" : "Abhey","countryCode" : "AUS"}}');          req1.setBody('{"request":'+JSON.Serialize(conWrapList)+'}');          //req.setBody('{"request": {"countryCode": "AUS","hcpEmail" : ""+email}}');          //req.setTimeout(60000);             //req.setHeader('Content-Length', '0');         Http http1 = new Http();         HTTPResponse res1 = http1.send(req1);          System.debug('***Response***** ' + res1.getBody());         if(res1.getBody()!=null)         {             response=res1.getBody();             HCPResponse saj=(HCPResponse)JSON.deserialize(response,HCPResponse.class);           System.debug('***Response came full***** ' + saj);            System.debug('***Response came***** ' + saj.accList);             for(HCPResponseDetail s :saj.accList)            {            System.debug('***Response email***** ' + s.hcpEmail);            System.debug('***Response add2***** ' + s.hcpAddrLine2);            contact.Address1_Line2__c=s.hcpAddrLine2;            }           //return response;         //string methodcall=methodGet(JSONstr);               return Page.opptyStep2CustomReg;         }
49733
I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the HttpRequest object? My HttpRequest.GET currently returns an empty QueryDict object. I'd like to learn how to do this without a library, so I can get to know Django better.
35973
Im trying to access a web service from a remote computer. I managed to access the web service from the browser. But Im getting HTTP 403 when I try to call the web service from the application.  Any idea why?
39111
I am trying to do the integration between Salesforce and Xero by using Named Credentials (Authentication Protocol is OAuth 2.0). I created an Auth provider -    Then created Named credentials of OAuth 2.0 type and authenticated with required scopes mentioned in the Xero developer document.    When I am trying to run the below code to get the Account details from Xero, I am getting "AuthenticationUnsuccessful".  HttpRequest req = new HttpRequest(); req.setEndpoint('callout:XeroDev/api.xro/2.0/Accounts'); req.setMethod('GET'); Http http = new Http(); HTTPResponse res = http.send(req); System.debug(res.getBody());   This is the response -      {"title":"Forbidden","status":403,"detail":"AuthenticationUnsuccessful","instance":"707450d8-b455-47ec-a1b4-85bcb2cf80c9"}   Any suggestion on how to make it work by using Named Credential?  Xero URL -
72983
I have been struggling with this error for a few days now. I get this error every time I try to run a test for a method that has an httpCallout. I followed the architecture from  , but to no avail. I thought it could be something I was messing up in my code, so I copied all three of the classes from the documentation, and I am still getting the error when I try to run the test. All of the classes are on Salesforce API 29. Has anyone run into this before?
77120
I am trying to implement  and below is my code and debug log - any help is appreciated.  Http httpProtocol = new Http();    HttpRequest request = new HttpRequest(); request.setHeader('Content-Type', 'application/json;'); request.setEndPoint('https://test.salesforce.com/services/oauth2/token'); request.setMethod('POST'); String strbody = '{"grant_type":"Password", "password":"MY PASSWORD + TOKEN", "username":"SANDBOX USER NAME",  "client_secret":"secret",   "client_id":"Client id from remote setttings"}'; request.setBody(strbody); HttpResponse response = httpProtocol.send(request); String jsonInput = response.getBody(); system.debug('jsonInput===&gt;'+jsonInput);   Debug log -   15:55:38.068 (68324000)|SYSTEM_METHOD_ENTRY|[5]|System.HttpRequest.setMethod(String) 15:55:38.068 (68346000)|SYSTEM_METHOD_EXIT|[5]|System.HttpRequest.setMethod(String) 15:55:38.068 (68350000)|STATEMENT_EXECUTE|[6] 15:55:38.068 (68356000)|HEAP_ALLOCATE|[6]|Bytes:357 15:55:38.068 (68381000)|VARIABLE_ASSIGNMENT|[6]|strbody|"{\"grant_type\":\"Passw (337 more) ..." 15:55:38.068 (68387000)|STATEMENT_EXECUTE|[7] 15:55:38.068 (68407000)|SYSTEM_METHOD_ENTRY|[7]|System.HttpRequest.setBody(String) 15:55:38.068 (68440000)|SYSTEM_METHOD_EXIT|[7]|System.HttpRequest.setBody(String) 15:55:38.068 (68445000)|STATEMENT_EXECUTE|[8] 15:55:38.068 (68478000)|SYSTEM_METHOD_ENTRY|[8]|System.Http.send(APEX_OBJECT) 15:55:38.068 (68568000)|CALLOUT_REQUEST|[8]|System.HttpRequest[Endpoint=https://test.salesforce.com/services/oauth2/token, Method=POST] 15:55:38.483 (483258000)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:219 15:55:38.483 (483399000)|CALLOUT_RESPONSE|[8]|System.HttpResponse[Status=Bad Request, StatusCode=400] 15:55:38.483 (483424000)|HEAP_ALLOCATE|[8]|Bytes:96 15:55:38.483 (483444000)|SYSTEM_METHOD_EXIT|[8]|System.Http.send(APEX_OBJECT) 15:55:38.483 (483615000)|VARIABLE_ASSIGNMENT|[8]|response|"System.HttpResponse[Status=Bad Request, StatusCode=400]"|0x1b22c3f1 15:55:38.483 (483627000)|STATEMENT_EXECUTE|[9] 15:55:38.483 (483666000)|SYSTEM_METHOD_ENTRY|[9]|System.HttpResponse.getBody() 15:55:38.483 (483742000)|HEAP_ALLOCATE|[9]|Bytes:81 15:55:38.483 (483751000)|SYSTEM_METHOD_EXIT|[9]|System.HttpResponse.getBody() 15:55:38.483 (483780000)|VARIABLE_ASSIGNMENT|[9]|jsonInput|"{\"error\":\"unsupporte (61 more) ..." 15:55:38.483 (483786000)|STATEMENT_EXECUTE|[10] 15:55:38.483 (483794000)|HEAP_ALLOCATE|[10]|Bytes:13 15:55:38.483 (483980000)|HEAP_ALLOCATE|[10]|Bytes:94 15:55:38.483 (483999000)|SYSTEM_METHOD_ENTRY|[10]|System.debug(ANY) 15:55:38.484 (484025000)|USER_DEBUG|[10]|DEBUG|jsonInput===&gt;{"error":"unsupported_grant_type","error_description":"grant type not supported"}
13754
I'm looking into a restful design and would like to use the HTTP methods (POST, GET, ...) and HTTP headers as much as possible. I already found out that the HTTP methods PUT and DELETE are not supported from the browser.  Now I'm looking to get different representations of the same resource and would like to do this by changing the Accept header of the request. Depending on this Accept header, the server can serve a different view on the same resource.  Problem is that I didn't find a way to tell my browser to change this header.   The &lt;a..&gt; tag has a , that can have a mime type, looked like a good candidate but the header was still the browser default (in Firefox it can be changed in about:config with the network.http.accept.default key).
115162
Using WCF in a RESTful way seems great. I’m a big fan of the big guns like simplicity and flexibility, but I also love the way the Urls end up looking. What can I say, I’m a programmer. The simple API for retrieving and editing resources is matched by an almost equally simple set of possible error responses, and I can’t help feeling that to keep to a “pure” RESTful approach I may be cutting my nose off to spite by face, or more specifically, the nose of my web service consumers. I could be wrong, but there doesn’t seem to be very many Http error codes that I can use, and no ways to pass back a custom error message. To clarify, I am talking about proper exceptional errors and not expected errors. I want to actually communicate a problem to the user to help them identify what they need to do to correct it. Possible options I am considering...  Just use the Http error codes – This seem like it would be too restrictive in what I am able to express, and won’t allow me to supply a custom message. Please(!) correct me if I am wrong.  Always return Http Success but return custom error objects – Obviously the most flexible but certainly not the most RESTful.   I would really appreciate it if anyone could share some real world experience of this particular problem.  Update Thanks for the suggestion of using the StatusDescription property of the OutgoingWebResponseContext object. It seemed at first to be something that I could use. I have come to the conclusion that my second option above is not for me. I want to stick to the what Http can give me. I am having problems getting it to work, however. Regardless of the value I supply for this property, it doesn’t get returned in the response. My service method looks like this public MyType GetMyTypes(string criteria) {     try     {         return GetMyTypes();     }     catch (Exception ex)     {         OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;         response.StatusCode = HttpStatusCode.Forbidden;         response.StatusDescription = &quot;A Big fat error occurred&quot;;         return null;     } }  And here is the raw response message. There is no mention of the custom message...  HTTP/1.1 403 Forbidden Server: ASP.NET Development Server/9.0.0.0 Date: Wed, 07 Jan 2009 14:01:20 GMT X-AspNet-Version: 2.0.50727 Cache-Control: private Content-Length: 0 Connection: Close  It's not as if I just need to access the correct property on the client. The information is simply not being sent across the link. What does this StatusDescription property actually do?  Update I never did find out how to set the StatusDescription property. I ended up not including any error message at all, and going solely with the Http status codes. I have chosen to expose both Soap and Restful endpoints for my services, and so clients can choose which they prefer to use – the simple Restful messages or the relatively richer Soap messages.
84581
Im trying to improve the Java Html Document a little but i'm running into problems with the HttpUrlConntion. One thing is that some servers block a request if the user agent is a Java VM. Another problem is that the HttpUrlConnection does not set the Referrer or Location header field. Since several sites use these fields to verify that the content was accessed from their own site, I'm blocked here as well. As far as I can see the only resolution is to replace the URL handler of the HTTP protocol. Or is there any way to modify the default HTTP Handler?
92774
I want to get an access token from an external endpoint (HTTP callout to REST API) without hardcoding passwords. The external system expects a request with Oauth 2.0 authentication details provided in the body, like the following:  String body = 'client_id='+EncodingUtil.urlEncode('myClientId','UTF-8');  body += '&amp;client_secret='+EncodingUtil.urlEncode('myClientSecret','UTF-8');  body += '&amp;grant_type='+EncodingUtil.urlEncode('password','UTF-8');  body += '&amp;username='+EncodingUtil.urlEncode('myUsername','UTF-8');  body += '&amp;password='+EncodingUtil.urlEncode('myPassword','UTF-8');   Hardcoded request is successful, but I'd like to use Named Credentials. I can set up an Auth. Provider of type Open ID Connect and provide client_id and client_secret. But there I cannot set parameters like 'username' and 'password' which are needed in order to make a proper request. This makes me wonder if that kind of authentication is possible in SF.  An alternative would be using Custom Settings, but then the credentials would be too easily accessible (and concrete setting cannot be deployed) which is not a good practice.  So my question is: Can I securely authenticate with above credentials using Apex without hardcoding them?