I tried to create a react native app with OAuth login in my rails app.
I have this react native setup
const config = {
issuer: 'http://app.domain.tld',
clientId: '85bb84b9cb0528b1f64b7c77586507b3ca5e69b11abe36ae1e54e88a6150c21e',
clientSecret: '0d3c0713437e0028a121a0c2294cc9a72f4eb5609416935a2860e20f176c7855',
redirectUrl: 'com.domain://com.domain',
responseType: 'code',
scopes: [],
dangerouslyAllowInsecureHttpRequests: __DEV__,
// clientAuthMethod: 'post',
serviceConfiguration: {
authorizationEndpoint: 'http://app.domain.tld/oauth/authorize',
tokenEndpoint: 'http://app.domain.tld/oauth/token',
// revocationEndpoint: 'http://app.domain.tld/oauth/revoke'
},
additionalParameters: {
approval_prompt: 'force'
}
}
// use the client to make the auth request and receive the authState
try {
const result = await authorize(config)
// result includes accessToken, accessTokenExpirationDate and refreshToken
console.log('result', result)
} catch (error) {
console.log('error', error.message)
}
the oaut app looks like this:
When I press the button to login in my app, I get a browser window where I can login in my rails app and got redirected to the authorize page for the oauth app. After I authorize my app, I got redirected to the app with the message "Network error". With that message I can't find out whats wrong, maybe anyone can help me.
In the server logs I can see this:
Redirected to com.domain://com.domain?code=54f3b4c03ea3724522f9a7983e2ea1b9037336076cd52cb875f9654d5d79784a&state=8xmiicVcPKN980ZDZUwBnw
in the debugger-ui i get this error log:
error Error: Network error
at createErrorFromErrorData (ReactNativeART.js:10)
at ActivityIndicator.js:72
at MessageQueue.__invokeCallback (ReactNativeART.js:472)
at blob:http://localhost:8081/1fccf34b-97b0-4c42-81fa-f0e1391a3ad3:2358
at MessageQueue.__guard (ReactNativeART.js:373)
at MessageQueue.invokeCallbackAndReturnFlushedQueue (blob:http://localhost:8081/1fccf34b-97b0-4c42-81fa-f0e1391a3ad3:2357)
at debuggerWorker.js:80
so i think there is something wrong. The app didn't make any further request to the server to obtain the access_token. Whats wrong?
Use this in config:
dangerouslyAllowInsecureHttpRequests: true,
Related
I am trying to use MSAL for node.js for OAuth 2.0 authentication, and I'm getting an error when calling acquireTokenByAuthCode.
Network request failed. Please check network trace to determine root cause. | Fetch client threw: Error: HTTP status code 400 | Attempted to reach: https://login.microsoftonline.com/{myTenantId}/oauth2/v2.0/token
Client instance:
const msal = new ConfidentialClientApplication({
auth: {
clientId: process.env.MS_CLIENT_ID,
clientSecret: process.env.MS_SECRET,
authority: process.env.MS_AUTHORITY
}
})
Login route:
const uri = await msal.getAuthCodeUrl({
responseMode: 'query',
redirectUri: `${process.env.APP_URI}/auth/code`,
scopes: ['user.read']
});
res.redirect(uri);
Token route (/auth/code):
try {
const {
accessToken,
} = await msal.acquireTokenByCode({
scopes: ['user.read'],
code: req.query.code,
redirectUri: `${process.env.APP_URI}/auth/code`,
});
res.cookie('token', accessToken);
res.redirect('/');
}
catch(e) {
res.status(401).send(e);
}
I can retrieve an auth code just fine, but I get the error when trying to get the token in the last snippet.
Make sure your clientSecret is correct. I just had this same issue and realized I was using the ID of the secret as opposed to the actual secret itself.
I fixed it. The Application was just missing the openid permission.
We are building a react-native chat app. We are implementing a back end authentication solution on google Firebase. The creation of a new user in Firebase Auth triggers a cloud function which should create a new SendBird user with an access token. The access token will be stored in Cloud Firestore, ready for retrieval the next time the user logs in.
We are having trouble implementing the POST request that creates the new user via the platform API. We are using the Request library for node.js. We are able to reach the API endpoint, but the following object is returned: { message: 'SendBird API Endpoint.', error: true }. There is no indication of what the error may be.
This happens when sending the request to the base url. When we send the request to /users or /v3/users, we receive a 403 error.
Any indication as to what may be causing this problem would be greatly appreciated.
Below is the cloud function index.js code
const functions = require('firebase-functions');
const admin = require("firebase-admin");
const request = require('request');
admin.initializeApp();
exports.handleNewUser = functions.auth.user().onCreate((user) => {
var newUserRequestBody = {
"user_id": user.email,
"nickname": user.email,
"profile_url": "",
"issue_access_token": true,
}
request.post({
headers: {
'Content-Type': 'application/json, charset=utf8',
'Api-Token': // API Token
},
url: 'https://api-{application_id}.sendbird.com',
form: newUserRequestBody
}, function(error, response, body){
if (!error && response.statusCode === 200) {
const info = JSON.parse(body);
console.log("request successful");
console.log(response.statusCode);
console.log(info);
}
else{
console.log("request unsuccessful");
console.log(response.statusCode);
console.log(error);
}
});
return null;
});
Did you try with full path of end point to url: (including /v3/users)?
Or you may need to use "baseUrl" like below?
https://github.com/request/request#requestoptions-callback
Also, you need to make sure that you correctly used {application_id} value and {API Token} value.
You can double check this from your dashboard of SendBird.
http://dashboard.sendbird.com > Log in with your ID > select your APP.
There is a section named "App credentials" in "Overview" menu.
You can double check your API-request URL and API-Token value from there.
I'm doing an axios call.
My Code:
loginSAP () {
var config = {
url: 'http://linkToSAPoDataService/oDataSet?&format=json',
withCredentials: true
}
this.axios(config)
}
Need to login first to access my database.
After I log in, I get:
Failed to load resource: the server responded with a status of 401 (Unauthorized)
createError.js:15 Uncaught (in promise) Error: Request failed with status code 401
at createError (createError.js:15)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)
I can't access the data instantly -
When I refresh the page, everything's fine and working.
I have to access and display the data before refreshing.
Do you have any ideas what could be wrong with my call?
Seems that your axios config is not going to be updated after login. You can use an interceptor to add login token (as an example) to axios config.
axios
.interceptors
.request
.use(function (config) {
if (cookie.load('auth-token')) {
config.headers['AUTH-TOKEN'] = cookie.load('auth-token');
}
return config;
}, function (error) {
return Promise.reject(error);
});
Therefore, after login, all of your requests have a valid token with no need to refresh the page to reset the config.
I have an iOS App with an Uber API integration where I use SSO to authenticate the user and then save the accessToken & refreshToken locally on my device. Then I'm calling my server who uses a javascript background function to call the node-uber (https://www.npmjs.com/package/node-uber) library to make a request to Uber.
So far, I'm trying to set up the uber client with my 2 local tokens from the SSO login like this:
var uber = new uberClient({
client_id: '...',
client_secret: '...',
server_token: '...',
name: 'My App',
sandbox: true, //optional
access_token: accessToken,
refresh_token: refreshToken
});
afterwards I want to call the uber.requests.getEstimatesAsync endpoint like this:
uber.requests.getEstimatesAsync({
"start_latitude": pickupLocation["lat"],
"start_longitude": pickupLocation["lng"],
"end_latitude": dropoffLocation["lat"],
"end_longitude": dropoffLocation["lng"]
})
.then(function(res) {
console.log(JSON.stringify(res));
})
.error(function(err) {
console.error(err);
});
})
Though every time I get an "invalid_grant" error 400 while doing this. Did I make a mistake authenticating myself or setting up the Uber client wrong? Is it even possible to use my SSO accessToken & refreshToken then on the uber client, which does a OAuth2 authentification? I thought that both access and refresh token should probably be the same what Uber sends back to be for SSO & OAuth2.
I'm using a Developer account for doing this, therefore I should actually have all the required permissions for the request endpoint, but I also obtained them previously in the App correctly.
This thread on the official uber documentation explains potential reasons but I guess they don't really apply to my case, do they? https://developer.uber.com/docs/riders/guides/authentication/introduction#common-problems-and-solutions
Any security expert here who can help?
Best regards,
Matt
P.S.: I also posted this question on the Uber library I'm using for making those requests, but nobody seems to be able to help me there so far. https://github.com/shernshiou/node-uber/issues/70
Edit: The following picture shows my authentication setup so far:
I found a solution. I think was a problem with the library itself. Because once I made the request with http with the "request" library (https://github.com/request/request) it worked. Include for that at the top of your code:
var request = require('request');
Both OAuth2 and SSO accessToken worked. You should give the method a pickupLocation with latitude and longitude and your obtained accessToken from Uber like this:
function getAllAvailableUberProducts(pickupLocation, accessToken){
var lat = pickupLocation["lat"].toString();
var lng = pickupLocation["lng"].toString();
var options = {
uri: "https://api.uber.com/v1.2/products?latitude="+lat+"&longitude="+lng,
method: 'GET',
headers: {
"Authorization": "Bearer " + accessToken,
"Accept-Language": "en_US",
"Content-Type": "application/json"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(JSON.parse(body).products);
} else {
console.log(error);
}
});
}
I hope this helps someone.
I'm using Torii and ember-simple-auth to manage authentication on my front-side, and Knock and Omniauth-twitter on my server. I had no problem with Facebook, but Twitter using Oauth1.0, I have troubles to figure out the flow.
Here is my Torii config :
# environment.js
ENV['torii'] = {
sessionServiceName: 'sessiontorii',
providers: {
'facebook-oauth2': {
apiKey: 'API_KEY',
redirectUri: 'http://localhost:4200/'
},
'twitter': {
requestTokenUri: 'http://127.0.0.1:3000/auth/twitter'
}
}
My route or controller :
# route.js
twitterLogin() {
var self = this;
this.get('sessiontorii').open('twitter').then(function(response) {
console.log(response);
self.transitionTo('index');
}, function() {
console.log('auth failed');
});
},
A new window is opening and I can login with my Twitter account. My server does the authentication/registration, but I can't figure out how to close this new window and send the token to my front.
Is my flow completely wrong ? Or do I miss something ?
I followed this tutorial, but I wonder if it's not a bit outdated
The issue was that I was sending a wrong type of data from my server. So I updated my torii-provider and the code I was sending. Torii does the job and close the new window when it gets the data. Then, I'm sending the data to my authenticator and confirm the authentication with the JWT code.