GET Shift Preference Issue - azure-active-directory

Having an error when getting this API (https://learn.microsoft.com/en-us/graph/api/shiftpreferences-get?view=graph-rest-1.0&tabs=http)
Request header:
{'Authorization': 'Bearer eyJ**6MA', 'Content-Type': 'application/json', 'MS-APP-ACTS-AS': '53**76'}
Error Response: {'error': {'code': 'Forbidden', 'message': '{"error":{"code":"Forbidden","message":"The user identifier in the path does not match the one in the authorization token.","details":[],"innererror":{"code":"InvalidOAuthToken"}}}', 'innerError': {'date': '2020-10-06T13:53:08', 'request-id': '093**ad', 'client-request-id': '09**bad'}}}
And I have all permissions required for this.
Any Idea why is this?

I can easily reproduce your problem.
This error will occur if you use the wrong user_id or the token you use is not issued by the user. You can use https://jwt.ms/ to parse your access token and view oid Claims, which is your user_id and also Token issuer, you need to ensure that it is consistent with the user_id in your request path.
There is also a relatively simple method, you can directly use Graph Explorer to request this API (this requires you to log in).

Related

Forbidden (CSRF cookie not set.): /api/signinUser

The error occurs in this react code
const headers = new Headers({
"X-CSRFToken": Cookies.get('csrftoken')
});
const response = await fetch("api/signinUser",
{
method: "POST",
headers: headers,
body: formData
});
Trying to access this Django Api
#ensure_csrf_cookie
def signin(request):
if request.method == 'POST':
auth = False
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
print("Authenticating User", user)
if user is not None:
auth = True
login(request, user) # Does this return anything?
ret = {
"auth": auth
}
print("RET", ret)
return JsonResponse(ret)
I have django.middleware.csrf.CsrfViewMiddleware in my MIDDLEWARE variable
I'm running my Django server in an AWS EC2 instance that I access with http://<my public ip>:8000/
headers: {
'X-Requested-With': 'XMLHttpRequest',
'csrftoken': Cookies.get('csrftoken'),
},
As you are accessing using HTTP (and not https) you need to ensure the cookies are not https only (i.e. "Secure").
The "easiest" for this it to changes your settings to ensure that http cookies will work (https://docs.djangoproject.com/en/4.1/ref/settings/#csrf-cookie-httponly, https://docs.djangoproject.com/en/4.1/ref/settings/#csrf-cookie-secure and https://docs.djangoproject.com/en/4.1/ref/settings/#session-cookie-httponly).
However, as you're on AWS, it's fairly easy and cheap to access over HTTPS with a valid certificate if you have a (sub)domain name you can use.
Create yourself a Load Balancer (in the EC2) panel). That prompts you to...
Create a "Target Group". The target group contains the instance above
Set it so that a listener on "443" will redirect traffic to "80" on your instance (so your instance does not need a certificate). In doing this, you'll be prompted to create a certificate within AWS.
Point your DNS to the load balancer.
Please check costs, but the normally-expensive part (the certificate) is free, and you can set security groups to lock users our of having direct access to your EC2.
You should check out the docs.
https://docs.djangoproject.com/en/4.1/ref/csrf/
A hidden form field with the name ‘csrfmiddlewaretoken’, must be present in all outgoing POST forms.
They are referring to a hidden input field within your form.
For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or TRACE, a CSRF cookie must be present, and the ‘csrfmiddlewaretoken’ field must be present and correct. If it isn’t, the user will get a 403 error.

How to get a cookie outside getServerSideProps?

I have this code inside getServerSideProps which gives me the token value from a cookie named token:
const token = context.req.cookies?.token || null;
const auth = true;
//Then I sent the token to server
const settings = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': "Bearer " + token,
},
body: JSON.stringify({ "limit": "10" })
};
The cookie is a httpOnly cookie I receive from a post request sent with Set-Cookie header.
The thing is, I want to use the token not only in page components (getServerSideProps is only in page components). In other components I'd like to sometimes use functions that give me more data, let's say all the messages of the client - based on his token (I limit it to 10 in logs.js and I want to increase it in my inner component functions) . Is it safe to pass the token via props and then use it in my functions? I have logs.js component, which has another component named Messages, and inside the Messages component I want to call a function to get more messages but I am not sure whether it is safe or not because the idea of getting the token in getServerSideProps is that nobody can see it, or am I wrong?
If I am not wrong, what is the best way to get the token from the client-side in order to send requests inside inner components?
the idea of getting the token in getServerSideProps is that nobody can see it
Not really when it comes to cookies. Cookies will be sent to the browser so anyone can see it anyways. What you do with it in getServerSideProps is hidden, but the cookie itself is visible.
Because it's an httpOnly cookie, you can't access it with javascript on the client. So if you need the cookie value in javascript, you have a few options:
Read the cookie in getServersideProps and pass that value to your page and through to your components. This will work if you only need your components to read the cookie value.
Change to a { httpOnly: false } cookie which will allow it to be read (and written to) by javascript. I wouldn't do this if it has anything to do with security, because then anyone can not only read the cookie but could change it and do whatever they want with it.
You mentioned it's a token - the big question is: what is the token for in terms of security? You mention using it to determine if you should have more than 10 logs. Is that a business requirement? Would something bad happen (like you lose money, a breach, etc?) if someone manipulated it to show 20, 30, 1,000?
If your business needs to show the user only 10 except in the case where his/her token increases that limit, and you don't want the user to manipulate the limit, leave it as httpOnly, read it in getServerSideProps, and then pass the number to your component. Then, nothing can be manipulated or changed because the client can't mess with the token to unlock more logs.

Axios Post method authorization does not work - React

I am developing a website [using React for front-end // Spring for backend] and in this website there is an admin panel. There is a button which lets other admins to add users to the database but I have a problem with axios' post method.
I checked so many different sources but couldnt find exactly what I am looking for. So here I am.
I get this error, 401 error code, unauthorized client, when using this syntax below
async addUsers(newData){
const headers = {
'Content-Type': 'application/json',
'Authorization': window.$auth
}
await Axios.post(
"http://localhost:8080/admin/addUser",
JSON.stringify(newData),
{headers: headers}
);
}
Before, I tried using a different syntax which I think is wrong, and with this syntax I get 415 error code: 415 error code, unsupported media type
async addUsers(newData){
await Axios.post(
"http://localhost:8080/admin/addUser",
JSON.stringify(newData),
{auth:window.$auth},
{headers: {'Content-Type':'application/json'}}
);
}
P.S: I tried to add User manually to database using Insomnia REST client and it successfully adds it and returns 200 Code.
Could someone help me with this problem, please?
Instead of sending authorization token with each request better add it as a default header. First check if token exist if it is exist add it
if(authorization_token){
axios.defaults.headers.common['Authorization'] = authorization_token;
}
It looks like this "authorization always returning 401 error code" was a known issue. Changing the complete syntax fixed it. Here is the site that I found the solution on https://github.com/axios/axios/issues/926
Here is the part of my code which that I fixed and now works:
async addUsers(newData){
await Axios({
method:'post',
url:'http://localhost:8080/admin/addUser',
data:JSON.stringify(newData),
auth:window.$auth,
headers:{'Content-Type':'application/json'}
})
}

Getting 204 Response while using Alexa Location API

My Code is:
URL = "https://api.amazonalexa.com/v1/devices/{}/settings" \
"/address".format(context['System']['device']['deviceId'])
TOKEN = context['System']['apiAccessToken']
#TOKEN = session['user']['permissions']['consentToken']
HEADER = {'Accept': 'application/json',
'Authorization': 'Bearer {}'.format(TOKEN)}
r = requests.get(URL, headers=HEADER)
print('Status Code: '+str(r.status_code)+ " " +str(r.reason))
I am have given permission to access my address. Earlier, i was getting 403 Forbidden response. Now after granting permission in skills setting i am getting 204 No content response. Please help me to resolve it!!
Can you try these things:
Make sure that you have an address saved for the associated device from which you are testing. There is a chance that you will get this issue from test simulator. So add a real device, save address and test it.
Always use apiEndpoint from context.System.apiEndpoint. Depending upon the geographical location this will change.
Check whether you have granted permissions to access address. If not you will get FORBIDDEN error.

Using fetch API with mode: 'no-cors', can’t set request headers

I am trying to hit a service end point and the service is a login service
I am using the authentication type as basic ,The code is in react and using the fetch library however even if i set the headers field in my request I am unable to see the values of corresponding headers in my request in network tab?
Following is the code :
var obj = {
method: 'GET' ,
mode : 'no-cors',
headers: {
'Access-Control-Request-Headers': 'Authorization',
'Authorization': 'Basic amFzcGVyYWRtaW46amFzcGVyYWRtaW4=',
'Content-Type': 'application/json',
'Origin': ''
},
credentials: 'include'
};
fetch('http://myreport:8082/jasperserver/rest/login/', obj ).then(…
Popup where its asking me for username and password
Request and response calls from the network tabs
None of your headers are CORS-safelisted, so they can not be attached to the request.
Explanation:
no-cors request mode sets guard property for a headers object to request-no-cors
To append a name/value (name/value) pair to a Headers object (headers), browser have to run these steps:
Normalize value.
If name is not a name or value is not a value, then throw a TypeError.
If guard is "immutable", then throw a TypeError.
Otherwise, if guard is "request" and name is a forbidden header name, return.
Otherwise, if guard is "request-no-cors" and name/value is not a CORS-safelisted request-header, return. ← your scenario
Otherwise, if guard is "response" and name is a forbidden response-header name, return.
Append name/value to header list.
CORS-safelisted request-header (case-insensitive):
Accept
Accept-Language
Content-Language
Content-Type, but only if the value is one of:
application/x-www-form-urlencoded
multipart/form-data
text/plain
You can learn more about fetch's Headers class specs here:
https://fetch.spec.whatwg.org/#headers-class

Resources