NOT FOUND - The server has not found anything matching the requested URI - asp.net-mvc

In my react website I login i want to generate a token. I'm calling my API and respone is undefined.
[object Error]{config: Object {...}, description: "Network Error",
message: "Network Error", name: "Error", request: XMLHttpRequest {...}, response: undefined, stack: "Error: Netw..."}
This is my react code.
const axios = require("axios");
const fakeAuth = {
isAuthenticated: false,
authenticate(cb: any) {
this.isAuthenticated = true;
axios.post('https://localhost:44310/api/Users/Token' )
.then((response : any) => {
console.log(response)
})
.catch((error : any) =>{
console.log(error)
})
},
signout(cb: any) {
this.isAuthenticated = false;
},
getValue() {
return this.isAuthenticated;
}
};
export default fakeAuth;
and this my API token method.
private string Token()
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("qwertyuiopqwertyuiop"));
var signInCred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
var token = new JwtSecurityToken(
issuer: "localhost",
audience: "localhost",
expires: DateTime.Now.AddMinutes(1),
signingCredentials: signInCred
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
return tokenString;
}

Related

there's no question mark printing before query params

first way I tried is :
static async callSendApi(requestBody) {
let url = new URL(
`${API_URL}/${PAGE_ID}/messages`
);
url.search = new URLSearchParams({
access_token: `${PAGE_ACCESS_TOKEN}`,
});
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(url, {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
// access_token: `${PAGE_ACCESS_TOKEN}`,
});
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
Second way I tried is :
static async callSendApi(requestBody) {
let url = new URL(
`${API_URL}/${PAGE_ID}/messages?access_token=${PAGE_ACCESS_TOKEN}`
);
/* url.search = new URLSearchParams({
access_token: `${PAGE_ACCESS_TOKEN}`,
});*/
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(url, {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
// access_token: `${PAGE_ACCESS_TOKEN}`,
});
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
the error I get :
error: {
message: 'Unknown path components: /messagesaccess_token=access_token
type: 'OAuthException',
code: 2500,
fbtrace_id: 'AbBJGVotjz3ijKKLzVE6_CM'
}
I'm receiving this error in both ways. both ways are escaping the '?' mark. I have no idea what is happening.. I'm using heroku for this. I tried deleting and redeploying the repository to confirm if the code is not updating. but still gives this error. :( .
I tried withot using URL and URLSearchParams and it worked!
below is my code:
static async callSendApi(requestBody) {
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(
`${API_URL}/${PAGE_ID}/messages`,
{
params: { access_token: `${PAGE_ACCESS_TOKEN}` },
},
{
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
}
);
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}

Using Auth0 for Twitter to get token and secret token

im using auth0 to get authentication for twitter, im using react native and i want to use twitter as login,
this is my code.
_loginWithAuth0Twitter = async () => {
const redirectUrl = AuthSession.getRedirectUrl();
const result = await AuthSession.startAsync({
authUrl: `${auth0Domain}/authorize` + toQueryString({
connection: 'twitter',
client_id: auth0ClientId,
response_type: 'token',
scope: 'openid',
redirect_uri: redirectUrl,
}),
});
after request auth give me this result
Object {
"errorCode": undefined,
"params": Object {
"access_token": "8uDhJTvWFxpr6GpTfioXp_8wCtqfwDsW",
"exp://127.0.0.1:19000/--/expo-auth-session": "",
"expires_in": "7200",
"scope": "openid",
"token_type": "Bearer",
},
"type": "success",
"url": "exp://127.0.0.1:19000/--/expo-auth-session#access_token=8uDhJTvWFxpr6GpTfioXp_8wCtqfwDsW&scope=openid&expires_in=7200&token_type=Bearer",
}
i only get acess_token and there is not much thing you can do with access token since twitter still using auth 1.0
i try to set rules
Get email address from Twitter
function (user, context, callback) {
// additional request below is specific to Twitter
if (context.connectionStrategy !== 'twitter') {
return callback(null, user, context);
}
const oauth = require('oauth-sign');
const uuid = require('uuid');
const url = 'https://api.twitter.com/1.1/account/verify_credentials.json';
const consumerKey = configuration.TWITTER_CONSUMER_KEY;
const consumerSecretKey = configuration.TWITTER_CONSUMER_SECRET_KEY;
const twitterIdentity = _.find(user.identities, { connection: 'twitter' });
const oauthToken = twitterIdentity.access_token;
const oauthTokenSecret = twitterIdentity.access_token_secret;
const timestamp = Date.now() / 1000;
const nonce = uuid.v4().replace(/-/g, '');
const params = {
oauth_consumer_key: consumerKey,
oauth_nonce: nonce,
oauth_signature_method: 'HMAC-SHA1',
oauth_timestamp: timestamp,
oauth_token: oauthToken,
oauth_version: '1.0',
oauth_callback:'https://pembersih.auth0.com/login/callback'
};
params.oauth_signature = oauth.hmacsign('POST',
url,
params,
consumerSecretKey,
oauthToken);
const auth = Object.keys(params).sort().map(function (k) {
return k + '="' + oauth.rfc3986(params[k]) + '"';
}).join(', ');
request.post(url, {
headers: {
'Authorization': 'OAuth ' + auth
},
json: true
}, (err, resp, body) => {
if (resp.statusCode !== 200) {
return callback(new Error('Error retrieving email from twitter: ' + body || err));
}
});
}
then i get this error
Object {
"errorCode": undefined,
"params": Object {
"error": "access_denied",
"error_description": "Error retrieving email from twitter: [object Object]",
"exp://127.0.0.1:19000/--/expo-auth-session": "",
},
"type": "success",
"url": "exp://127.0.0.1:19000/--/expo-auth-session#error=access_denied&error_description=Error%20retrieving%20email%20from%20twitter%3A%20%5Bobject%20Object%5D",
}
how can i get user token and secret token so that i can use twitter API ?

MS Graph Sample Application Integration Test not Working

I want to do what the MS Graph sample node app is doing in its integrationTests.js, but that test doesn't work. Here's what I've tried:
Followed the quick start for creating a node.js app.
Ran the app. Ensured it worked by sending an e-mail.
Modified the test Checking that the sample can send an email to use my account parameters.
Tried to run the test. It fails with 403: insufficient scope. The call to get the token returned scopes, but lacked Mail.Send.
In the post data for the call to login.microsoftonline.com, I added "scope: 'Mail.Send'"
I still receive a valid token, and the return scope includes Mail.Send, but when I try to post with that token, I get 400: cannot POST /beta/me/sendMail
I tried adding scope (Mail.Send) in the query string and as a header (thought I saw that somewhere), but it made no difference.
I added the Mail.Send permission (under "Application Permissions") for the app in the application registration portal.
I compared the token (using https://jwt.ms) from my test call to the call from the app when it works. I see no real difference. They both contain the Mail.Send scope.
Here is the code (which is only slightly different from what's in the sample):
// in graphHelper.js
function postSendMail(accessToken, message, callback) {
request
.post('https://graph.microsoft.com/beta/me/sendMail')
//.post('https://graph.microsoft.com/beta/me/sendMail?scope=Mail.Send') // nope
.send(message)
.set('Authorization', 'Bearer ' + accessToken)
.set('Content-Type', 'application/json')
.set('Content-Length', message.length)
.set('scope', 'Mail.Send') // nope
.end((err, res) => {
callback(err, res);
});
}
describe('Integration', function () { // mocha
var accessToken;
var scope;
const config = getConfig();
// My account variables in testConfig.json file
function getConfig() {
var configFilePath = path.join(__dirname, 'testConfig.json');
return JSON.parse(fs.readFileSync(configFilePath, { encoding: 'utf8' }));
}
function getAccessToken(done) {
var postData = querystring.stringify(
{
grant_type: 'password',
//grant_type: 'client_id', // not supported
//grant_type: 'authorization_code', // This assumes you've requested an auth code.
resource: 'https://graph.microsoft.com/',
scope: 'Mail.Send',
client_id: config.test_client_id_v2,
client_secret: config.test_client_secret_v2,
username: config.test_username,
password: config.test_password
}
);
var postOptions = {
host: 'login.microsoftonline.com',
port: 443,
path: '/common/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var postRequest = https.request(postOptions, function (res) {
var data = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
const response = JSON.parse(data);
accessToken = response.access_token;
scope = response.scope;
done();
});
});
postRequest.on('error', function (e) {
console.log('Error: ' + e.message);
done(e);
});
postRequest.write(postData);
postRequest.end();
}
before( // eslint-disable-line no-undef
function (done) {
getAccessToken(done);
}
);
it('Checking that the sample can send an email',
function (done) {
var postBody = emailer.generateMailBody(config.test_name, config.test_username);
graphHelper.postSendMail(
accessToken, scope,
JSON.stringify(postBody),
function (error) {
assert(error === null, `The sample failed to send an email: ${error}`);
done();
});
}
);
});

OKTA - OAuthError: Illegal value for redirect_uri parameter

I am working in my Developer Account in OKTA.
I am trying to get a Very Simple SPA App to obtain a JWT From OKTA.
I login with authClient.signIn({}) and that returns a transaction.sessionToken/
With that Session Token I should be able to call authClient.token.getWithoutPrompt({}) but I can never reach that code.
I get the following error: OAuthError: Illegal value for redirect_uri parameter.
How do I get beyond this OAuth Error so I can finally get back a JWT. I have tried examples on OKTA GIT but cannot get anything to work.
function getJWT()
{
var orgUrl = 'https://MYXXXXXXX.oktapreview.com';
var keyID = "MY CLIENT ID";
var user = "MYUSER ID";
var pwd = "MY PASWORD"
var appScope = ['openid', 'email', 'profile', 'phone', 'groups'];
var authClient = new OktaAuth({url: orgUrl, clientId: keyID,});
$('#tokendiv').html('');
authClient.signIn({
username: user,
password: pwd,
redirectUri: "http://localhost:5656/test.html" //THIS IS SETUP IN MY OKTA ID
})
.then(function(transaction) {
if (transaction.status === 'SUCCESS') {
authClient.session.setCookieAndRedirect(transaction.sessionToken); // Sets a cookie on redirect
console.log(transaction.sessionToken);
$('#tokendiv').append('<h4>Session Token</h4>' + transaction.sessionToken);
/// THIS IS NEVER REACHED, I Always Get OAuthError: Illegal value for redirect_uri parameter.
authClient.token.getWithoutPrompt({
responseType: 'id_token', // or array of types
scopes: appScope,
sessionToken: transaction.sessionToken
})
.then(function(res) {
console.log("JWT: " + jwt);
$('#tokendiv').append('<h4>JWT</h4>' + res.idToken);
})
.fail(function(err) {
console.log("ERROR " + err);
$('#tokendiv').append('<h4>Error</h4>' + err);
})
} else {
throw 'We cannot handle the ' + transaction.status + ' status';
}
})
.fail(function(err) {
console.error(err);
});
}
As long as your redirectUri is included in the approved Redirect URIs in your Okta Developer organization, you should not be receiving that error.
Below I was able to successfully return an id_token running on localhost:5656.
<!-- index.html -->
<html>
<body>
<button onClick="getJWT()">Button</button>
<div id="tokendiv"></div>
</body>
</html>
<script>
function getJWT(){
var orgUrl = 'https://{{org}}.oktapreview.com';
var keyID = "{{clientId}}";
var user = "{{user}}";
var pwd = "{{password}}"
var appScope = ['openid', 'email', 'profile', 'phone', 'groups'];
var authClient = new OktaAuth(
{
url: orgUrl,
clientId: keyID,
redirectUri: "http://localhost:5656/index.html"
});
$('#tokendiv').html('');
authClient.signIn({
username: user,
password: pwd,
})
.then(function(transaction) {
if (transaction.status === 'SUCCESS') {
authClient.token.getWithoutPrompt({
responseType: 'id_token', // or array of types
scopes: appScope,
sessionToken: transaction.sessionToken
})
.then(function(res) {
$('#tokendiv').append('<h4>JWT</h4>' + res.idToken);
console.log("JWT: " + JSON.stringify(res));
})
.fail(function(err) { /* err */ })
} else { /* throw error */ }
})
.fail(function(err) { /* err */ });
}
</script>

How Do I send VoIP push notifications to an iOS device using Amazon SNS in Node JS

I am trying to send VoIP push notifications directly to an iOS device from an App server using the NodeJS package called sns-mobile and Amazon SNS API.
However, When I try to send VoIP pushes using the below code, here is the error message that I get. Could someone please suggest me where I am going wrong, I have been spending nearly half a day to resolve this.
Invalid parameter: JSON must contain an entry for 'default' or
'APNS_VOIP
var iOSApp = new SNS({
platform: SNS.SUPPORTED_PLATFORMS.IOS,
region: 'us-west-2',
apiVersion: '2010-03-31',
accessKeyId: 'XXXXXXXXXXXXX',
secretAccessKey: 'XXXXXXXXXXXXX',
platformApplicationArn: 'arn:aws:sns:us-west-2:3303035XXXXX:app/APNS_VOIP/VoIPPushesApp'
});
iOSApp.addUser('deviceID',
JSON.stringify({
"APNS_VOIP": JSON.stringify({aps:{alert:"Hello and have a good day."}})
})
, function(err, endpointArn) {
if(err) {
console.log("The Error is :****: "+JSON.stringify(err, null, 4));
throw err;
}
// Send a simple String or data to the client
iOSApp.sendMessage(endpointArn, 'Hi There!', function(err, messageId) {
//iOSApp.sendMessage(endpointArn, messageTest, function(err, messageId) {
if(err) {
console.log("The Error in end message is :****: "+JSON.stringify(err, null, 4));
throw err;
}
console.log('Message sent, ID was: ' + messageId);
});
});
Here is the code that send a VoIP notifications to the receiver device using its device VoIP token. When a VoIP notification is received, the device calls a function called, didReceiveIncomingPushWithPayload
var AWS = require('aws-sdk');
// Amazon SNS module
AWS.config.update({
accessKeyId : 'XXXXXXXXXXXXXXXX',
secretAccessKey : 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
region : 'us-west-2'
});
var amazonSNS = new AWS.SNS();
// 1. Create Platform Endpoint
var createPlatformEndpoint = function(req, res, next){
var deviceVoipToken = req.deviceVoipToken; // Obtaining the device VoIP token from the request object
amazonSNS.createPlatformEndpoint({
// App in Sandboxmode (ie running on device directly from Xcode)
PlatformApplicationArn: "arn:aws:sns:us-west-2:xxxxxxxxxxxx:app/APNS_VOIP_SANDBOX/CurieVoip",
// App in Production mode (ie running on device after archiving and installed on device with a provisioning profile)
//PlatformApplicationArn: "arn:aws:sns:us-west-2:xxxxxxxxxxxx:app/APNS_VOIP/CurieVoip",
Token: deviceVoipToken
}, function(err, data) {
if (err) {
console.log(err.stack);
response.json({"status": "failure", "statusCode" : 402})
return;
}
var endpointArn = data.EndpointArn;
req.endpointArn = data.EndpointArn; // Passing the EndpointArn to the next function
next()
})
}
// 2. Publish notification
var publishVoipNotification = function(req, res, next){
var endpointArn = req.endpointArn;
var payload = {
default : 'Hello World, default payload',
APNS_VOIP : {
aps: {
alert: 'Hi there',
sound: 'default',
badge: 1
}
}
};
// first have to stringify the inner APNS object...
payload.APNS = JSON.stringify(payload.APNS);
// then have to stringify the entire message payload
payload = JSON.stringify(payload);
console.log('sending push');
amazonSNS.publish({
MessageStructure : 'json',
Message : payload,
TargetArn : endpointArn
}, function(err, data) {
if (err) {
console.log("Error stack: "+err.stack);
var message = "There has been an error in Publishing message via AmazonSNS with error: "+err.stack;
res.json({"status": "failure", "statusCode" : 402, "message" : message})
return;
}
next();
});
}
// 3. Deleting platform endpoint after sending a voipNotification; Ref: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#deleteEndpoint-property
var deleteEndpointArn = function(req, res){
var endpointArn = req.endpointArn;
var roomName = req.roomName;
var params = {
EndpointArn: endpointArn /* required */
};
amazonSNS.deleteEndpoint(params, function(err, data) {
if (err){
var message = "Unable to deleteEndpointArn, with error: "+err.stack;
res.json({"status": "failure", "statusCode" : 400, "message":message})
}
else{
var message = "Deleted endpointArn successfully";
res.json({"status": "success", "statusCode" : 200, "message":message})
}
});
}
router.post('/sendVoipNotificationToReceiver', [createPlatformEndpoint, publishVoipNotification, deleteEndpointArn]);
Go to Amazon SNS
Click on Mobile: Push notifications
Click on Create platform Application,
User Apple Credentials "Used for development in sandbox" check this checkbox if you want to test voip notification on sandbox.
Push certificate type -- Voip Push certificate
Upload Certificate .P12 files.
Save Form and copy ARN
Create Lambda function. Code example below
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set region
AWS.config.update({region: 'us-east-1'});
var amazonSNS = new AWS.SNS();
const isset = (s) => {
return typeof s !== typeof undefined ? true : false;
};
exports.handler = (event, context, callback) => {
let data = event['body-json'];
if (isset(data)) {
let getAction = data['action'];
let userToken = data['token'];
let webPayload = data['payload'];
if (isset(getAction) && getAction == 'APNS_VOIP') {
amazonSNS.createPlatformEndpoint({
PlatformApplicationArn: 'YOUR APPLICATION ARN',
Token: userToken
}, function (err, data1) {
if (err) {
//handle error
console.log(err)
} else {
//Publish notification
var endpointArn = data1.EndpointArn;
console.log("endpointArn",endpointArn);
var payload = {
default: 'Silent voip push notification',
APNS_VOIP: {
//aps:webPayload
"aps" : {
"alert" : {
"title" : "Call Request"
},
"data":webPayload,
"content-available":1,
"category":"GENERAL"
}
}
};
payload.APNS_VOIP = JSON.stringify(payload.APNS_VOIP);
payload = JSON.stringify(payload);
amazonSNS.publish({
MessageStructure: 'json',
Message: payload,
MessageAttributes:{
"AWS.SNS.MOBILE.APNS.PRIORITY":{"DataType":"String","StringValue":"10"},
"AWS.SNS.MOBILE.APNS.PUSH_TYPE":{"DataType":"String","StringValue":"voip"}
},
TargetArn: endpointArn
}, function (err, data2) {
if (err) {
//handle error
console.log(err)
} else {
var params = {
EndpointArn: endpointArn /* required */
};
//Deleting platform endpoint after sending a voipNotification;
amazonSNS.deleteEndpoint(params, function (err, data3) {
if (err) {
//handle error
//console.log(err);
callback(null, {
"status": "error",
"data": [],
"message": []
});
} else {
//code success
console.log("delete",data3);
callback(null, {
"status": "Success",
"data": data3,
"message":"notification sent successfully"
});
}
});
}
});
}
});
}
else if (isset(getAction) && getAction == 'APNS_VOIP_SANDBOX') {
amazonSNS.createPlatformEndpoint({
PlatformApplicationArn: 'YOUR APPLICATION ARN',
Token: userToken
}, function (err, data1) {
if (err) {
//handle error
console.log(err)
} else {
//Publish notification
var endpointArn = data1.EndpointArn;
console.log("endpointArn",endpointArn);
var payload = {
default: 'Silent voip push notification',
APNS_VOIP_SANDBOX: {
"aps" : {
"alert" : {
"title" : "Call Request"
},
"data":webPayload,
"content-available":1,
"category":"GENERAL"
}
}
};
payload.APNS_VOIP_SANDBOX = JSON.stringify(payload.APNS_VOIP_SANDBOX);
payload = JSON.stringify(payload);
amazonSNS.publish({
MessageStructure: 'json',
Message: payload,
MessageAttributes:{
"AWS.SNS.MOBILE.APNS.PRIORITY":{"DataType":"String","StringValue":"10"},
"AWS.SNS.MOBILE.APNS.PUSH_TYPE":{"DataType":"String","StringValue":"voip"}
},
TargetArn: endpointArn
}, function (err, data2) {
if (err) {
//handle error
console.log(err)
} else {
var params = {
EndpointArn: endpointArn /* required */
};
//Deleting platform endpoint after sending a voipNotification; Ref: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#deleteEndpoint-property
amazonSNS.deleteEndpoint(params, function (err, data3) {
if (err) {
//handle error
//console.log(err);
callback(null, {
"status": "error",
"data": [],
"message": []
});
} else {
//code success
console.log("delete",data3);
callback(null, {
"status": "Success",
"data": data3,
"message":"notification sent successfully"
});
}
});
}
});
}
});
}
else {
callback(null, {
"status": "error",
"data": [],
"message": "You have not posted valid data."
});
}
}
};
https://docs.aws.amazon.com/sns/latest/dg/sns-send-custom-platform-specific-payloads-mobile-devices.html
How Do I send VoIP push notifications to an iOS device using Amazon SNS in Node JS

Resources