wso2 access token validation API call from POSTMAN fails - wso2

I found that we can make this call
curl -k -u admin:admin -H 'Content-Type: application/x-www-form-urlencoded' -X POST --data 'token=fbc4e794-23db-3394-b1e5-f2c3e511d01f' https://localhost:9443/oauth2/introspect
to check the validity of an access token
This works perfectly as a curl command, but when i import this into postman and make calls,it fails
it doesnt work from nodejs code also
var axios = require('axios');
var qs = require('qs');
var data = qs.stringify({
'token': 'ff744c77-53a6-46f2-ae4c-1da72cab52ab'
});
var config = {
method: 'post',
url: 'https://localhost:9443/oauth2/introspect',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic YWRtaW46YWRtaW4='
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});

If you get an error as follows while running this nodejs code:
{ Error: unable to verify the first certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1058:34)
at TLSSocket.emit (events.js:198:13)
at TLSSocket._finishInit (_tls_wrap.js:636:8)
code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
.
.
.
}
Update the nodejs code as follows:
var axios = require('axios');
var https = require('https');
var qs = require('qs');
var data = qs.stringify({
'token': 'ff744c77-53a6-46f2-ae4c-1da72cab52ab'
});
var config = {
method: 'post',
url: 'https://localhost:9443/oauth2/introspect',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic YWRtaW46YWRtaW4='
},
data : data,
httpsAgent: new https.Agent({
rejectUnauthorized: false
})
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
It should return false/true (depending on the access token) as follows:
{
"active": false
}

Can you try importing the following curl to postman
curl --location --request POST 'https://localhost:9443/oauth2/introspect' \
--header 'Authorization: Basic YWRtaW46YWRtaW4=' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'token=ff744c77-53a6-46f2-ae4c-1da72cab52ab'

Related

DRF - Authentication credentials were not provided. (Djoser + SimpleJWT)

I am currently getting an error when making a request to /users/me to receive back my user's data. From what I have been reading, I am not sending the token, though I'm not sure how to store it when I receive it from the jwt/create endpoint when signing in.
This is from my Auth-Test/nuxt-auth/pages/index.vue file:
onMounted(async () => {
const cookie = useCookie('jwt');
console.log('COOKIE: ' + JSON.stringify(cookie));
const response = await fetch('http://localhost:8000/api/auth/users/me/', {
headers: {
'Content-Type': 'application/json',
'Authorization': `JWT ${JSON.stringify(cookie)}`,
},
credentials: 'include'
})
const content = await response.json();
console.log(content);
})
and this is from my Auth-Test/nuxt-auth/pages/login.vue
const router = useRouter();
async function submit() {
console.log(JSON.stringify({
email: user.email,
password: user.password
}))
await fetch('http://localhost:8000/api/auth/jwt/create/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include',
body: JSON.stringify({
email: user.email,
password: user.password
})
});
await router.push({ path: '/' });
}
Could anyone help me realize what I might be (am) doing wrong? I can't seem to figure out it myself through the use of documentation after a lot of reading.
In case you might need to access the other files (front and back end), here is the Github repo.
Follow the usage guide here https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html#usage
You should store the JWT token instead of using cookie.
const router = useRouter();
async function submit() {
console.log(JSON.stringify({
email: user.email,
password: user.password
}))
const response = await fetch('http://localhost:8000/api/auth/jwt/create/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include',
body: JSON.stringify({
email: user.email,
password: user.password
})
});
// it's common to use localStorage to store it so when users go back to your site it's still there.
// If you don't want that you can just store it in memory.
const responseJson = await response.json();
localStorage.setItem('token', responseJson.access);
await router.push({ path: '/' });
}
Then you can use it as a Bearer token
Bearer authentication (also called token authentication) is an HTTP authentication scheme that involves security tokens called bearer tokens. The name “Bearer authentication” can be understood as “give access to the bearer of this token.” The bearer token is a cryptic string, usually generated by the server in response to a login request. The client must send this token in the Authorization header when making requests to protected resources:
Authorization: Bearer 'token'
onMounted(async () => {
const cookie = useCookie('jwt');
console.log('COOKIE: ' + JSON.stringify(cookie));
const token = localStorage.getItem('token');
const response = await fetch('http://localhost:8000/api/auth/users/me/', {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
credentials: 'include'
})
const content = await response.json();
console.log(content);
})

How to send a POST request (registration) in Postman using pre-request script

I'm trying to create a new user using a pre-request script to be able to use a PUT request to edit user profile settings independently from other requests.
So I'm setting a token from the response to my env variable to use it in the header for the PUT request.
My whole pre-request script is not working - new user is not created and new token is not set. What am I missing?
const createUser = pm.environment.get('url') + 'users'
pm.sendRequest({
url: createUser,
method: 'POST',
header: {
'Content-type': 'application/json',
'X-Foo': 'bar'
},
body: {
mode: 'application/json',
raw: JSON.stringify({"user":{
"username":"{{$randomUserName}}",
"email":"{{$randomEmail}}",
"password": "Pa$$w0rd!"}
})
}
})
pm.sendRequest(function (err, response) {
pm.environment.set("tokenConduit", response.json().token);
});
I think this is incorrect:
body: {
mode: 'application/json',
raw: JSON.stringify({"user":{
"username":"{{$randomUserName}}",
"email":"{{$randomEmail}}",
"password": "Pa$$w0rd!"}
})
}
application/json goes into Headers like you have it, but the body is in raw format. See the example in Postman docs. You stringify a json, so it's just a bunch of charaters, mode "application/json" doesn't exist.
Another thing is you're sending 2 requests, but I think you want to send only one:
const request = {
url: createUser,
method: 'POST',
header: {
'Content-type': 'application/json',
'X-Foo': 'bar'
},
body: {
mode: 'application/json',
raw: JSON.stringify({"user":{
"username":"{{$randomUserName}}",
"email":"{{$randomEmail}}",
"password": "Pa$$w0rd!"}
})
}
};
pm.sendRequest(request, function (err, response) {
pm.environment.set("tokenConduit", response.json().token);
});
So you should have only one pm.sendRequest() in your code.
const createUser =
pm.sendRequest({
url: "https://reqres.in/api/users?page=2",
method: 'POST',
header: {
'Content-type': 'application/json',
'X-Foo': 'bar'
},
body: {
mode: 'application/json',
raw: pm.variables.replaceIn(JSON.stringify({"user":{
"username":"{{$randomUserName}}",
"email":"{{$randomEmail}}",
"password": "Pa$$w0rd!"}
}))
}
})
pm.sendRequest(function (err, response) {
pm.environment.set("tokenConduit", response.json().token);
});
you have to use pm.variables.replacein to use variables inside script section,
Goto console to see what was actually send:

I have an app with react as frontend and django rest framework as backend, i use axios to send my response, but the data is empty

I have an app with react and Django rest framework. I use Django allauth for login and registration. when I want to log in, everything is ok, and the response is 201 but the data is empty and I don't get token. I send this request with the postman and I get the token. what should i do?
React Request:
axios({
method: 'post',
url: 'http://localhost:8000/rest-auth/login/',
data: {
username: 'admin',
email: '',
password: 'admin123456'
},
headers: { 'content-type': 'application/json' }
})
.then(response => {
console.log(response.data.key);
})
.catch(error => {
console.log(error);
});
the response is:
{data: "", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
postman request: http://localhost:8000/rest-auth/login/
{
"username": "mahtab",
"email": "",
"password": "mahtab23"
}
postman response:
{
"key": "f75b9f54848a94ac04f455321118aff5d5a7e6f8"
}

react native 0.50.3 authorization header not sent

I am using react-native 0.50.3 to send token authenticated requests to my backend and unfortunately the 'authorization' part of the header is not send by the fetch.
My code is the following :
async componentDidMount() {
var mytoken = await AsyncStorage.getItem('token');
fetch('http://myserver:8000/home', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Origin': '',
'Content-Type': 'application/json',
'authorization': 'Bearer ' + mytoken
}
})
.then((response) => response.json())
.then((content) => {
this.state.user = content.user;
})
.done();
}
And on my server side, the wireshark trace shows that the authorization is not in the request header :
Hypertext Transfer Protocol
GET /home/ HTTP/1.1\r\n
Host: 10.150.21.124:8000\r\n
Content-Type: application/json\r\n
Origin: \r\n
Accept: application/json\r\n
User-Agent: Expo/2.3.0.1012011 CFNetwork/893.14 Darwin/17.3.0\r\n
Accept-Language: en-us\r\n
Accept-Encoding: gzip, deflate\r\n
Connection: keep-alive\r\n
\r\n
[Full request URI: http://10.150.21.124:8000/home/]
[HTTP request 1/1]
[Response in frame: 2326]
And of course I get a 401 unhautorized by the server.
My backend is a django API with CORS installed and CORS_ORIGIN_ALLOW_ALL = True and ALLOWED_HOSTS = ['*'].
The versions of my developments framework elements are the following :
npm 4.6.1
node v9.3.0
react-native-cli 2.0.1
One important update, the request I try to do with react-native works like a charm with postman. So the issue is not located on the server side.
Thank you for your help.
Alex.
try with trailing slash, in url address:
fetch('http://myserver:8000/home/', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Origin': '',
'Content-Type': 'application/json',
'authorization': 'Bearer ' + mytoken
}
})
.then((response) => response.json())
.then((content) => {
this.state.user = content.user;
})
.done();
Pooya's answer worked for me by adding the trailing slash on the request object. Strange because it worked on postman without the trailing slash hence the challenge in debugging. P.S i am also using the same stack, django, django REST framework (DRF) react native
fetch('http://mywebsite.com/posts/', {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token
}
})

Django OAuth Toolkit and POSTMAN

I made a django OAuth server using Django OAuth Toolkit.
I've setup the code right and when I use CURL in the following way:
curl -X POST -d "grant_type=password&username=geethpw&password=abcabcabc" -u"wHsGgpsHZyw8ghnWbEPZC8f4AZLgJIPmoo50oNWp:ZQcXeQWnae0gmX0SMi6Xn6puBnhiphR2M80UC6ugmffbrUd66awhbguYgxtQ1ufahJZehj4RlGjYu06fHkVgO15TURttSozj27nshl0AhFfCVzUKqTDubBimTSsK4yDS" http://localhost:8000/o/token/
I get a response:
{"access_token": "glzwHLQNvUNQSOU5kFAoopgJxiNHcW", "token_type": "Bearer", "expires_in": 36000, "refresh_token": "5k6jvCd2UxaRUGHKONC2SqDukitG5Y", "scope": "read write groups"}Geeths-MacBook-Pro:~ geethwijewickrama$
Geeths-MacBook-Pro:~ geethwijewickrama$
which is expected.
But When I try postman to do the samething, I always get:
{
"error": "unsupported_grant_type"
}
My headers are:
Content-Type:application/x-www-form-urlencoded
If I remove this header I get:
{
"error": "invalid_client"
}
How can I test my APIs in postman?
Your postman body should be something like:
grant_type: <grant_type>
client_id: <client_id>
client_secret: <client_secret>
username: <username>
password: <password>
Try Bulkedit with these, hope this helps (Hope you have registered the app to obtain client_id and client_secret)
Get token from django-oauth-toolkit from JS:
async function getToken () {
let res = await fetch("https://<your_domain>/o/token/", {
body: new URLSearchParams({
grant_type: 'password',
username: '<user_name>',
password: '<user_pass>',
client_id: '<client_app_id>',
client_secret: '<client_pass>'
}),
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST"
})
return res.json();
}
console.log(await getToken());
Your client application authorisation grant type should be: "Resource owner password-based"
P.S. I've failed to get token via "Content-Type": "application/json", not sure why (django-oauth-toolkit documentation says nothing about that).