I made some api with REST Spring. GET request works fine in Postman but when I try to do POST request I receive this error :
{
"timestamp": "2018-09-25T06:39:27.226+0000",
"status": 403,
"error": "Forbidden",
"message": "Forbidden",
"path": "/cidashboard/projects"
}
This is my controller :
@RestController
@RequestMapping(ProjectController.PROJECT_URL)
public class ProjectController {
public static final String PROJECT_URL = "/cidashboard/projects";
private final ProjectService projectService;
public ProjectController(ProjectService projectService) {
this.projectService = projectService;
}
@GetMapping
List<Project> getAllProjects(){
return projectService.findAllProjects();
}
@GetMapping("/{id}")
Project getProjectById(@PathVariable int id) {
return projectService.findProjectById(id);
}
@PostMapping
void addProject(@RequestBody Project newProject) {
projectService.saveProject(newProject);
}
}
Security configuration
initial I wanted to work with ldap, but in my application properties i left only the conection at database………………………………………………………………………………………………………………………………….
@EnableGlobalMethodSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**").permitAll();
// .anyRequest().fullyAuthenticated();
// .and()
// .formLogin().loginPage("/login").permitAll()
// .failureUrl("/login-error");
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups")
.contextSource(contextSource())
.passwordCompare()
//.passwordEncoder(new LdapShaPasswordEncoder())
.passwordAttribute("userPassword");
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/static/**"); // #3
}
@Bean
public DefaultSpringSecurityContextSource contextSource() {
return new DefaultSpringSecurityContextSource(Arrays.asList("ldap://localhost:8389/"), "dc=springframework,dc=org");
}
}
Thanks for building this useful tool.
Found today that Post/Put/Delete doesn’t work — it returns 403 forbidden.
This problem happens in multiple setup — mine, and 3 other coworkers.
- Postman doesn’t send out request at all. I add breakpoint in server side.
I followed http://blog.getpostman.com/2015/06/13/debugging-postman-requests/, it failed at xhr.send.
Please fix this as this will make postman totally not woking.
This is stack trace from postman:
background_page.js:447 POST …… 403 (Forbidden)
sendXhrRequest @ background_page.js:447
addToQueue @ background_page.js:536
onExternalMessage @ background_page.js:554
target.(anonymous function) @ extensions::SafeBuiltins:19
EventImpl.dispatchToListener @ extensions::event_bindings:388
target.(anonymous function) @ extensions::SafeBuiltins:19
publicClassPrototype.(anonymous function) @ extensions::utils:151
EventImpl.dispatch_ @ extensions::event_bindings:372
EventImpl.dispatch @ extensions::event_bindings:394
target.(anonymous function) @ extensions::SafeBuiltins:19
publicClassPrototype.(anonymous function) @ extensions::utils:151
messageListener @ extensions::messaging:207
target.(anonymous function) @ extensions::SafeBuiltins:19
EventImpl.dispatchToListener @ extensions::event_bindings:388
target.(anonymous function) @ extensions::SafeBuiltins:19
publicClassPrototype.(anonymous function) @ extensions::utils:151
EventImpl.dispatch_ @ extensions::event_bindings:372
EventImpl.dispatch @ extensions::event_bindings:394
target.(anonymous function) @ extensions::SafeBuiltins:19
publicClassPrototype.(anonymous function) @ extensions::utils:151
dispatchOnMessage @ extensions::messaging:334
Собственно, проблема следующая:
Postman отрабатывает отлично и возвращает ожидаемый результат

А python на аналогичный запрос выдает 403 код. Хотя вроде как заголовки одинаковые. Что ему, собаке, не хватает?
import requests
from pprint import pprint
url = 'http://ovga.mos.ru:8080/_ajax/pass/list?search={%22grz%22:%22К239ММ159%22}&sort=validitydate&order=desc'
headers = {"X-Requested-With": "XMLHttpRequest",
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/54.0.2840.99 Safari/537.36',
}
response = requests.get(url, headers)
pprint(response)
<Response [403]>
-
Вопрос заданболее двух лет назад
-
1993 просмотра
Ты не все заголовки передал. Postman по-умолчанию генерирует некоторые заголовки самостоятельно, вот так подключается нормально:
headers = {
'Host': 'ovga.mos.ru',
'User-Agent': 'Magic User-Agent v999.26 Windows PRO 11',
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'X-Requested-With': 'XMLHttpRequest'
}
url = 'http://ovga.mos.ru:8080/_ajax/pass/list?search={"grz":"К239ММ159"}&sort=validitydate&order=desc'
response = requests.get(url, headers=headers)
<Response [200]>
Пригласить эксперта
-
Показать ещё
Загружается…
30 янв. 2023, в 00:44
500 руб./за проект
29 янв. 2023, в 22:56
10000 руб./за проект
29 янв. 2023, в 22:48
500 руб./за проект
Минуточку внимания
After implementing a new project with Django that should allow to me to send some long text to the server, then use the KeyBERT library to extract automatically the Keywords from the sent text and finally send me a JSON response with the result. Once I deployed the project to test it using Postman, I found this error when trying to send directly a POST request to my view in Django using Postman.
In this article, I will explain to you 2 possible ways to circumvent this exception when sending requests through Postman to your Django project.
A. Disable CSRF protection for as specific view
Disabling the CSRF protection of a real project or something that really requires it is in no one’s head. You shouldn’t definitively do this unless you know what you’re doing (you understand totally how a CSRF attack and how could it be a problem to your application if you allow form submission without CSRF protection). Some cases where it could be feasible to use this approach:
- A local API that you’re testing locally only.
- A public API that’s designed to be accessible for anyone but somehow you trust all the possible requests (e.g your API is only accessible for specific IPs like the IP of another server that requests information from this endpoint and it has already CSRF protection with another language like PHP).
Otherwise, don’t do it. In my case, I designed a basic API that runs a machine learning library and should return the result of it as response, however the API doesn’t need any user implementation as it’s mean to be used only for me. This approach consists of disabling the CSRF protection of a specific route:
# views.py
from django.http import JsonResponse
# 1. Import the csrf_exempt decorator
from django.views.decorators.csrf import csrf_exempt
# 2. Exempt the view from CSRF checks
@csrf_exempt
def extract_keywords(request):
text = request.POST.get('text')
return JsonResponse(text)
The decorator will disable the CSRF checks for the route, in this case the extract_keywords method of the view. If you send the POST request to the same route again with Postman, it should succeed this time.
B. Auto-set X-CSRFToken header in Postman
The second option will work only if you are facing the following situation. If you have a Django project working properly let’s say in the following URL http://localhost:8080/my-form and it answers to GET and POST requests. Your project works properly, when you access the Form address through the browser through a GET request, the form will be rendered so the user can easily submit the data and when it’s submitted through a POST request, the request succeeds in the browser as expected. The problem with Postman appears when it works in the browser, but if you try to simulate the POST request to the same address using Postman, the mentioned exception will appear.
As previously mentioned, Django has inbuilt CSRF protection. The only mechanism that you have to trigger an AJAX request when this protection is enabled is to add the X-CSRFToken header to your request (which should contain a valid CSRF token to validate in the server). You can obtain this token first triggering a GET request to the endpoint to obtain the token and then use a Postman test script to manipulate the subsequent request with JavaScript adding the required header.
To accomplish this, open the Tests tab of your postman request and add the following test code:
var xsrfCookie = postman.getResponseCookie("csrftoken");
postman.setEnvironmentVariable('csrftoken', xsrfCookie.value);
This test JavaScript is executed after the response is received. Once it’s there, run the GET request:

What we did with the previous code is basically extracting the csrftoken of the form obtained with the GET request and it’s now going to be used in the subsequent POST request to validate the form. This token will be stored as an environment variable namely csrftoken, so we can easily add it to the new POST request as a new header:

After declaring the header, simply run the POST request and it should now succeed:

Happy coding ❤️!
This error indicates that the server has determined that you are not allowed access to the thing you’ve requested, either on purpose or due to a misconfiguration . It’s probably because the site owner has limited access to it and you don’t have permission to view it. The vast majority of the time, there’s not much you can do to fix things on your (*client) end. There are three common causes for 403 Forbidden error (server side) . Here they are listed from most likely to least likely:
- An empty website directory
- No index page
- Incorrect settings in the .htaccess file
- Permission / Ownership error
If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT automatically repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.
I want to embed PowerBI report in a web app. To test out, I am trying to generate embed token in Postman.
Before I did the following 2 steps, I have already register the app on https://dev.powerbi.com/apps and give the app all permissions. I was able to obtain the access token in step 1, but I am stuck at step 2. I keep getting 403 Forbidden error.
Step 1. Postman has a OAuth2 I obtained an access token using OAuth2.0 with the following parameters.
Auth URL: https://login.microsoftonline.com/{my azure tenant ID}/oauth2/authorize?resource=15637cae-03c4-49a3-9a32-5e28f0b46e3d
Token URL: https://login.microsoftonline.com/{my azure tenant ID}/oauth2/token
Callback URL: https://www.getpostman.com/oauth2/callback
After signing in with my credential with Postman, I was able to get an access token as a long string like following:
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ing0Nzh4eU9wbHNNMUg3TlhrN1N4MTd4MXVwYyIsImtpZCI6Ing0Nzh4eU9wbHNNMUg3TlhrN1N4MTd4MXVwYyJ9.eyJhdWQiOiIxYjFiYmU2Ni00MzcyLTQ2YTctOGUyOS05OTBkMTY5Y2VkYWYiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDcvIiwiaWF0IjoxNTEyOTU2NzgzLCJuYmYiOjE1MTI5NTY3ODMsImV4cCI6MTUxMjk2MDY4MywiYWNyIjoiMSIsImFpbyI6IlkyTmdZRENxL3MzK2ptK3kzK3pLaE9Cbm9sOWVMRkswcUpHZHdhMmRMWjErTUVQb3lGY0EiLCJhbXIiOlsicHdkIiwibWZhIl0sImFwcGlkIjoiMWIxYmJlNjYtNDM3Mi00NmE3LThlMjktOTkwZDE2OWNlZGFmIiwiYXBwaWRhY3IiOiIxIiwiZmFtaWx5X25hbWUiOiJBbiIsImdpdmVuX25hbWUiOiJ…
Step 2. I used the above token as the Auth header in Postman, the POST to the following URL.
https://api.powerbi.com/v1.0/{my azure tenant ID}/groups/e367de11-7296-46a7-bd1d-6727df903999/reports/49c31038-1192-45f0-a385-6b6c0f6256e9/GenerateToken
Postman filled in the Auth header for me, i.e. Authorization= Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ing0Nzh4eU9wbHNNMUg3TlhrN1N4MTd4MXVwYyIsImtpZCI6Ing0Nzh4eU9wbHNNMUg3TlhrN1N4MTd4MXVwYyJ9.eyJhdWQiOiIxYjFiYmU2Ni00MzcyLTQ2YTctOGUyOS05OTBkMTY5Y2VkYWYiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDcvIiwiaWF0IjoxNTEyOTU2NzgzLCJuYmYiOjE1MTI5NTY3ODMsImV4cCI6MTUxMjk2MDY4MywiYWNyIjoiMSIsImFpbyI6IlkyTmdZRENxL3MzK2ptK3kzK3pLaE9Cbm9sOWVMRkswcUpHZHdhMmRMWjErTUVQb3lGY0EiLCJhbXIiOlsicHdkIiwibWZhIl0sImFwcGlkIjoiMWIxYmJlNjYtNDM3Mi00NmE3LThlMjktOTkwZDE2OWNlZGFmIiwiYXBwaWRhY3IiOiIxIiwiZmFtaWx5X25hbWUiOiJBbiIsImdpdmVuX25hbWUiOiJ… in the header.
When I send the request, I got 403 FOrbidden response, and no explanation. If I change the URL to just list the groups or reports as following, I also got the same 403 forbidden response code. https://api.powerbi.com/v1.0/124edf19-b350-4797-aefc-3206115ffdb3/groups/
It’s very frustrating. What am I missing here? Any pointer is greatly appreciated.
tl;dr
The Postman App was sending an Origin header to /_api/contextinfo and that was generating a 403 Forbidden. Using a fiddler rule I removed the Origin HTTP header and the call to /_api/contextinfo endpoint then worked.
I’ve recently been trying to grok the SharePoint online REST API, particularly executing requests that require an HTTP POST and therefore a X-RequestDigest header.
To help me understand the interaction with the REST API I installed the Google Chrome Postman REST App and started to test.
If you open google chrome, login to your Office 365 site, then launch Postman, requests to the RESP API will be sent with the appropriate cookies for FedAuth and rtFA to authenticate.
So all good then, I was able to execute simple GET requests such as https://*myo365site*/_api/web and get back results as expected.
I wanted to start experimenting with the REST APIs for custom permissions that are “documented” here:
https://msdn.microsoft.com/en-us/library/office/dn495392.aspx
So the first thing I needed to do was to get a Request Digest to add as a header to my POST requests from Postman. Of course to get a Request Digest you need to have issued a POST request – but for POST requests you need a X-RequestDigest header – chicken & egg.
The process to follow is to issue a POST request to the https://*myo365site*/_api/contextinfo endpoint with an empty body and two headers:
Accept: application/json;odata=verbose
Content-Length: 0
This “should” return a 200 status code and a body such as the following:
{
"d": {
"GetContextWebInformation": {
"__metadata": {
"type": "SP.ContextWebInformation"
},
"FormDigestTimeoutSeconds": 1800,
"FormDigestValue": "<FORMDIGESTVALUE>",
"LibraryVersion": "16.0.4107.1226",
"SiteFullUrl": "https://*myo365site*",
"SupportedSchemaVersions": {
"__metadata": {
"type": "Collection(Edm.String)"
},
"results": [
"14.0.0.0",
"15.0.0.0"
]
},
"WebFullUrl": "https://*myo365site*"
}
}
}
Instead I was getting a 403 Forbidden status code with no body. I then started up fiddler to what was being sent through by Postman. Postman was sending through a few extra headers:
POST https://*myo365site*/_api/contextinfo HTTP/1.1
Host: *myo365site*
Connection: keep-alive
Content-Length: 0
Accept: application/json;odata=verbose
Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
CSP: active
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Cookie: WSS_FullScreenMode=false; rtFa=*cookievalue*; FedAuth=*cookievalue*
I copied all of the above headers into fildder’s Compose tab, I then started to remove the additional headers one by one to see if it made any difference.
When I removed the Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm the request succeeded!
I then added a rule to fildder in the static function OnBeforeRequest(oSession: Session) method:
oSession.RequestHeaders.Remove("origin");
And my requests from Postman to /_api/web/contextinfo now succeeded and I was able to obtain the RequestDigest value from the JSOM and use it as the value for the X-RequestDigest HTTP header for subsequent HTTP POST calls to REST endpoints.
Now…should I be leaving this fiddler rule in place “for all requests”?, I don’t know. All I know for now is that for my specific environment this is what I was seeing and I was able to get the call to /_api/contextinfo to execute successfully by removing the origin header.
I suspect that once I start issuing calls that do require the origin header (guessing here but the calls from an AppWeb to a HostWeb for example) then I’ll maybe run into issues. Need to investigate further.
YMMV
I have a Authorization code which i need to pass in body with some header value when calling a api. when trying the same from postman its working fine but C# Webclient throwing 403 error.
Code below:-
public string GetResponse(string AuthCode)
{
string url = «https://example.com//openam/oauth2/access_token?grant_type=authorization_code&realm=/cbpgatqa»;
Uri uri = new Uri(string.Format(url));
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = «code=» + AuthCode + «&redirect_uri=» + «http://localhost:8080»;
byte[] data = Encoding.GetEncoding(«UTF-8»).GetBytes(postData);
// Create the request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, «Basic » + AuthCode);
httpWebRequest.ContentType = «application/json»;
httpWebRequest.Method = «POST»;
httpWebRequest.ContentLength = data.Length;
httpWebRequest.UserAgent = @»Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36″;
Stream stream = httpWebRequest.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
// Get the response
HttpWebResponse httpResponse = null;
try
{
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (Exception ex)
{
Console.WriteLine(«Exception while getting resource » + ex.Message);
return null;
}
string result = null;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
Postman Curl command:-
Generated from a curl request:
curl -X POST
‘https://example.com//openam/oauth2/access_token?grant_type=authorization_code&realm=/cbpgatqa’
-H ‘Authorization: Basic MzE4OGQwYjQtZTRlOC00MTZjLTg5NjAtZDNlYWFhMmNjY2IxOkx3NiVBa0x4NWtPM01rJTJ5RWwxbW1jR0ZYZmhTQmk1NHhIRCpzNiUyVUd5WXN0MCNVbyNMNWQhcVlpZE93djc=’
-H ‘Cache-Control: no-cache’
-H ‘Content-Type: application/x-www-form-urlencoded’
-d ‘code=93317468-7464-4804-b38a-43e13265c4ac&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F’
I am not able to figure it out the issue . Can anyone please help me