How to call internal APEX methods provided by B2B Commerce for Visualforce using REST request - salesforce

Our team has a web application developed on top of B2B Commerce for Visualforce, there is a button on Product page, Add to Cart, it will call an Apex remote action method using Javascript when clicking on the button, I checked the network traffic in DevTools, found the following XHR request
the above XHR request should be made with the similar code
CCRZ.CloudCrazeView.addItem(event), there is the doc for the class, https://developer.salesforce.com/docs/atlas.en-us.b2b_commerce_dev_guide.meta/b2b_commerce_dev_guide/ccrz_CloudCrazeView.htm
does it have a REST API for the method in the picture? if yes any documentation or sources for it, so that I can call the method using HTTP REST requests, I mean calling it with curl, python or java remotely instead of Javascript.
the APEX class is ccrz.cc_RemoteActionController and the method is addItem, I know B2B Commerce provides a collection of REST API, REST API Endpoints for B2B Commerce for Visualforce, but this page doesn't include the method.

It's 2 different annotations and developer might have not used both. For Javascript usage it's #AuraEnabled and for being exposed as REST webservice it's #RestResource annotation on whole class + possibly #HttpPost on the method itself.
The problem is that in given class you can have only 1 of each HTTP "verbs" so if the class supports say 3 different buttons, they all would be accepting data as POST - problem. (in a pinch that dev could have done 1 master method inspecting the service url used, the input params and dispatching to right method for processing but it's bit meh...)
But. You should be able to patch that. Inspect cc_RemoteActionController in setup -> apex classes to confirm the method signature (it should be marked global meaning you can call it from apex too).
Create your own class that will act as REST wrapper
#RestResource(urlMapping='/HiStackoverflow/*')
global with sharing class HiStackoverflow{
#HttpPost
global static void addItem(Event e) {
ccrz.cc_RemoteActionController.addItem(e);
}
}

Related

How to get session id in static method while making callout

I am working on something which includes LWC with tooling API. I wrote this below method which makes a callout. but when I call this method this method from lwc at that time I'm unable to get session Id, but if I call this same method from the developer console then it works fine.
Apex Code:
#AuraEnabled
public static string getList(String fieldName){
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
System.debug('res------>'+UserInfo.getSessionID());
req.setHeader('Content-Type', 'application/json');
req.setEndpoint('callout:Tooling_Query/query/?q=Select+id,Namespaceprefix,developername,TableEnumOrId+FROM+customfield+Where+developername+LIKE\'' +fieldName+ '\'');
req.setMethod('GET');
Http h = new Http();
HttpResponse res = h.send(req);
System.debug('res------>'+res.getBody());
return res.getBody();
}
When I call it from lwc it returns this
[{"message":"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}]
so, how can I get session-id from lwc, I already set up a Connected App and Named Credential by the name of Tooling_Query
and add URL to remote sites.
please help me here.
You can't. Your Apex code called in a Lightning Web Components context cannot get an API-enabled Session Id. This is documented in the Lightning Web Components Dev Guide:
By security policy, sessions created by Lightning components aren’t enabled for API access. This restriction prevents even your Apex code from making API calls to Salesforce. Using a named credential for specific API calls allows you to carefully and selectively bypass this security restriction.
The restrictions on API-enabled sessions aren’t accidental. Carefully review any code that uses a named credential to ensure you’re not creating a vulnerability.
The only supported approach is to use a Named Credential authenticated as a specific user.
There is a hack floating around that exploits a Visualforce page to obtain a Session Id from such an Apex context. I do not recommend doing this, especially if you need to access the privileged Tooling API. Use the correct solution and build a Named Credential.

401 Unauthorized calling my Azure Rest API

I have a Rest API using controllers, etc, hosted in Azure that has been working for some time. I want to secure the various methods. I added the API App (.NET core) to the App Registrations, and also added the javascript client app to App Registrations. I believe I'm initializing everything in startup.cs in the REST Api OK. I added [Authorize] to one of the methods. I used a simple javascript example which calls myMSALObj.loginPopup, and gets back a token which I then add to the Authorization header and make a fetch call. When I call, I see HTTP Error 401.0 - Unauthorized in the log stream for my App Service.
Any ideas how I can troubleshoot this to get more specifics about what is wrong?
Also, a related question: in App Registrations, Api Permissions, how does one correlate the API permission name with the method in the controller?
Add this in front of the method in the controller
[AuthorizeForScopes(Scopes = new[] { "My.Scope" })]

Spring Boot application gives "405 method not supported" exception for only Angular/HTML/JSP resources

I have an application written with Spring Boot and AngularJS. When I try to hit a REST service as part of this application, I am able to hit it with POST method wherever POST is configured for request mapping.
But if I try to request AngularJS bind pages, I get a "405 method not supported" exception. So I try to create HTML and JSP pages too, which are not bound to Angular but still, I am getting the same exception.
Where can I start debugging this, and what is the likely reason?
i am sharing here furthere details about issue.
Basically this existing application created/developed with Jhipster, angularjs, Spring boot and spring security does not allow to access html/angularjs related resources with POST from outside. I will explain here what different scenarios work and what is not not working. 1.Postman trying to access base url trying to fetch index.html from same application- Give 405 Post method not allowed.2.Created an independent Test.html in same application and trying to access it from postman- Gives 405 Post method not allowed.3.Created a service which allows POST access in same application- Able to hit service from WSO2 IS IDP and also from Postman.4.Created a separate application on tomcat and provided as callback in WSO2 IDP with starting point for SSO from base url of existing application- Able to hit callback URL on tomcat server. Firefox shows that a POST request was generated for callback URL from WSO2 IS IDP to tomcat based application 5.Created a separate application with Angular js and Spring boot and provided as callback in WSO2 IDP with starting point for SSO from base url of existing application- Able to hit callback URL on tomcat server. Firefox shows that a POST request was generated for callback URL from WSO2 IS IDP to new application with Spring boot and Angularjs. This took me down to conclusion that one of three is causing this issue
1. Spring security generated from JHipster
2. Angularjs
3. Some CORS or other filter from Spring Security is causing this issue.
Till now we have tried to different debugging methods like
1. disable CORS,
2. in angularjs-resource.js enable POST for get operation,
3. In SecurityCOnfigurer, try to permit POST method for base URL or resolve it to GET in httpsercurity authorizerequest etc.
4. Also ignoring resources in websecurity.
Application stack for existing application which we are trying to implement SSO is as below
1. Angularjs 1.5.8
2. Springboot 1.5.9.release
3. WSO2IS 5.4.1
4. WSO2AM 2.1.0
5. JHipster
Let me know if any particular area which we might have missed to analyze or different methods to try.
Thanks,
Sandeep
Try to disable CSRF in security config
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
...
}
...
}
#SpringBootApplication
#Import({
...
SecurityConfig.class
...
})
public class SpringBootApp {
...
}

How to Secure an API Call made from a mobile application without username/password?

I have bought an API that can be used in a mobile application. API includes the Key and username as expected.
Within the app, this API needs to be called on Payment confirmation.
I found that using tools like Fiddler, one can see the request made by the application. If that is the case, it is just a matter of seconds to fully get access to the API signature.
It would be of great help if someone can help out/add to this issue.
My thoughts:
Use a server to make this API call instead of calling it directly
from the application.
If a server is used, the issue would still exist as the API call made to the server(eventually which calls the bought API) can also be interrupted/accessed
How to secure the call made to the server from the application?
Technologies: Angular JS, Node JS, Ionic framework
Look at my answer to this question. Instead of using the user name and password, your backend could provide an additional resource that allows the user to create a token with a special scope.
In your AngularJS application you can use the $http or $resource services (if the ngResource module is included) and obtain such kind of token that allows you to access only the parts of your backend your client really needs.
This token must be cached at the client side and included in the header of each request.
In AngularJS storing the token in the header of each request can be done at a central place if you are using the config function of the module you created.
app.config(function($httpProvider) { $httpProvider.defaults.xsrfCookieName = "TOKEN" }
AngularJS also provides some additional security features. For example you could use the JSON vulnerability protection mechanism. If you are using this, your backend had to add the characters )]}', (you could also override the default characters) to each JSON response body.
For other clients the JSON response will be invalid Javascript code, but in your AngularJS application the characters will be automatically removed.
UPDATE
The best way for implementing security for your application would be reading and understanding the OAuth2 specification.
In this video from minute 11:36 to 17:26 the JavaScript flow is described.
This site provides some implementation of the standard for different programming languages.
Some of the aspects in this standard are that all clients and redirect urls must be registered in an additional authentication server. Client are identified by a unique client id.
To avoid that some other application intercepts your requests for extracting the token, the original token should only be active for a small amount of time and each api request must be SSL encrypted.
For providing Single sign-on also refresh tokens can be used.

How to secure an AngularJS application that does not use authentication?

I have an AngularJS application (using ASP.NET Web API as the backend) that does not require the user to authenticate (the application has no login). I want to make sure that the REST API methods the AngularJS application invokes can only be invoked from the application. I obviously cannot use token based authentication for that.
If doing nothing special the REST API methods can be invoked freely using the browsers address bar or by writing a desktop application that invokes them. The same-origin policy is only regarded if a browser invokes an API method by a HTML page coming from a site having another origin. The REST API is therefore open to the public and easily hackable.
I wonder what I could do to securely restrict the access to the REST API. Any ideas or experience?
Edit 1:
I found an easy solution for my problem: I just check if the host of the URL referrer is the same as the host of the requested URL. Using ASP.NET Web API the code the REST API actions use is:
private bool ApiCallIsAllowed()
{
var request = HttpContext.Current.Request;
return (request.UrlReferrer != null &&
request.UrlReferrer.Host == request.Url.Host);
}
I am just not 100% sure if I always get the URL referrer.
Edit 2: According to this question the URL referrer ist not reliable. Bummer.
use ssh - that's obvious :)
login process should generate token - write it as a cooke - every http request will use it in header
prepare rest interceptor that will read your token and authorize every request
use some Javascript Obfuscator
Don't forget to invalidate session ;).
you can use spring-security or other framework to simplify this process

Resources