I hope to send notifications to individual users using Azure Mobile Services. When I add the notification service in Visual Studio 2013, it automatically generate a custom API in my Azure service. Since I have built my mobile service with JavaScript backend. The generate code is follow:
exports.post = function (request, response) {
response.send(statusCodes.OK);
sendNotifications(request);
};
function sendNotifications(request) {
var payload = '<?xml version="1.0" encoding="utf-8"?><toast><visual><binding template="ToastText01">' +
'<text id="1">' + request.body.toast + '</text></binding></visual></toast>';
var push = request.service.push;
push.wns.send(null,
payload,
'wns/toast', {
success: function (pushResponse) {
console.log("Sent push:", pushResponse);
}
});
}
And In my client service, I have used userId as my tags and invoke the function
`await App.MobileService.GetPush().RegisterNativeAsync(channel.Uri,userIdTags);`
where userIdTags is a List of strings that contains certain userId values I hope to receive the message.
But when I debug I found that all of users will receive the notification. So I would like to know whether do I need to handle or modify the auto-generate code in the custom API or any other reason that cause the problem .
Related
i am creating an agenda system that list and creates events in google calendar API,
i have successfully retrieved using the following code:
var mykey = 'your_api_key'; // typically like Gtg-rtZdsreUr_fLfhgPfgff
var calendarid = 'you_calendar_id'; // will look somewhat like 3ruy234vodf6hf4sdf5sd84f#group.calendar.google.com
$.ajax({
type: 'GET',
url: encodeURI('https://www.googleapis.com/calendar/v3/calendars/' + calendarid+ '/events?key=' + mykey),
dataType: 'json',
success: function (response) {
//do whatever you want with each
},
error: function (response) {
//tell that an error has occurred
}
});
now i need to insert events and everything i can find requires oath and is mostly about saving an event on the users calendar while i just want it saved in my calendar. any advice?
You can use a service account => https://developers.google.com/android/management/service-account
Create a Service Account
Create a Key for your service account (JSON should work)
Provide access to the required calendar scopes for your service account
Go to https://admin.google.com/
Go to Security->API Controls -> Domain-wide Delegation
Add scopes, for example https://www.googleapis.com/auth/calendar, https://www.googleapis.com/auth/calendar.events
When you call the API use the JSON (JWT => Json Web Token) file to authenticate
In the account where the calendar lives you have to provide permission to edit events from your calendar to the service account.
All the steps and code samples for HTTP/Rest using service account are here https://developers.google.com/identity/protocols/oauth2/service-account#httprest_1
I am trying to fetch git azure devops api to get information about repositories and branches in js.
In order to achieve that, I made a little application with the following code :
$(document).ready(function() {
var personalToken = btoa(':'+'<personnalAccessToken>');
fetch('https://dev.azure.com/<company>/<project>/_apis/git/repositories?api-version=5.1', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
'Authorization': 'Basic '+ personalToken
}
}).then(function(response) {
return response.json();
}).then(function(repositories) {
console.log("There are "+repositories.count+" repositories");
}).catch(function(error) {
console.log('Fetch error: ' + error.message);
});
This code is working great but as you can see there is my personnalAccessToken writen directly inside the code... which is really bad...
When I am using git in command line, I don't have to specify any credential information because I use git credential manager for windows. Which means my personnalAccessToken is already stored, cached and automatically used everytime I use a git command, like clone, etc.
So, I would like my js code to use the same thing, I would like it to use my stored credentials automatically to fetch the api without being required to set my personnalAccessToken in code.
I have already searched for hours but can't find out if it is possible.
I have already searched for hours but can't find out if it is
possible.
Sorry but as I know it's impossible. The way you're calling the Rest API is similar to use Invoke-RestMethod to call rest api in Powershell.
In both these two scenarios, the process will try to fetch PAT for authentication in current session/context and it won't even try to search the cache in Git Credential Manager.
You should distinguish the difference between accessing Azure Devops service via Rest API and by Code:
Rest API:
POST https://dev.azure.com/{organization}/{project}/{team}/_apis/wit/wiql?api-version=5.1
Request Body:
{
"query": "Select [System.Id], [System.Title], [System.State] From WorkItems Where [System.WorkItemType] = 'Task' AND [State] <> 'Closed' AND [State] <> 'Removed' order by [Microsoft.VSTS.Common.Priority] asc, [System.CreatedDate] desc"
}
Corresponding Code in C#:
VssConnection connection = new VssConnection(new Uri(azureDevOpsOrganizationUrl), new VssClientCredentials());
//create http client and query for resutls
WorkItemTrackingHttpClient witClient = connection.GetClient<WorkItemTrackingHttpClient>();
Wiql query = new Wiql() { Query = "SELECT [Id], [Title], [State] FROM workitems WHERE [Work Item Type] = 'Bug' AND [Assigned To] = #Me" };
WorkItemQueryResult queryResults = witClient.QueryByWiqlAsync(query).Result;
Maybe you can consider using a limited PAT, limit its scope to Code only:
I know there exists other Authentication mechanism
:
For Interactive JavaScript project: ADALJS and Microsoft-supported Client Libraries.
You can give it a try but I'm not sure if it works for you since you're not using real Code way to access the Azure Devops Service... Hope it makes some help :)
If you have the script set up in an Azure Runbook you can set it as an encrypted variable there and have it pull it from there before running rather than having it directly written into the code.
$encryptedPatVarName = "ADO_PAT"
$adoPat = Get-AutomationVariable -Name $encryptedPatVarName
$adoPatToken = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($adoPat)"))
$adoHeader = #{authorization = "Basic $adoPatToken"}
The above is the Powershell version of it. I have seen some people do it with other
I am developing a .Net Web App where after authenticating against Azure AD B2C through the Azure AD Connect protocol the controller in my app gets an access token through the MSAL library (C# code) to access a backed Web API. That works all fine.
Now from the same web app I need to use JavaScript to access the same backed Web API. My question is how can I leverage the access token obtained through my server side C# code to get my client side JavaScript to access the Web API without being prompted to sign-in.
I used the sample code on GitHub to get me started.
Below is my JavaScript code. When I run it I get the following error "user_login_error:User login is required"
if (!clientApplication) {
clientApplication = new Msal.UserAgentApplication(window.config.clientID, window.config.authority, authCallback);
clientApplication.redirectUri = window.config.redirectUri;
}
function ReloadInfo(type, language, location) {
clientApplication.acquireTokenSilent(window.config.b2cScopes).then(function (accessToken) {
ReadResource(accessToken, type, language, location);
}, function (error) {
clientApplication.acquireTokenPopup(window.config.b2cScopes).then(function (accessToken) {
ReadResource(accessToken, type, language, location);
}, function (error) {
debugger
logMessage("Error acquiring the access token to call the Web api:\n" + error);
});
})
}
Thanks!
A simple solution for this scenario is that you can create a corresponding controller to call the web API.
And in the JavaScript, you can call your web app instead of the web API directly. Since you have sign-in, the JavaScript can call the controller successfully. And in this sencario, there is no need to use MSAL library for JavaScript.
Update
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
$("#Location").change(function () {
$.ajax({
url: "data.html",//modify the path HTTP request you wanted
}).done(function (data) {
console.log(data);// handle the result data here
});
});
})
</script>
You can refer here about full jQuery document.
I'm trying to use the Facebook Graph API to get the latest status from a public page, let's say http://www.facebook.com/microsoft
According to http://developers.facebook.com/tools/explorer/?method=GET&path=microsoft%2Fstatuses - I need an access token. As the Microsoft page is 'public', is this definitely the case? Is there no way for me to access these public status' without an access token?
If this is the case, how is the correct method of creating an access token for my website? I have an App ID, however all of the examples at http://developers.facebook.com/docs/authentication/ describe handling user login. I simply want to get the latest status update on the Microsoft page and display it on my site.
This is by design. Once it was possible to fetch the latest status from a public page without access token. That was changed in order to block unidentified anonymous access to the API. You can get an access token for the application (if you don't have a Facebook application set for your website - you should create it) with the following call using graph API:
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials
This is called App Access Token. Then you proceed with the actual API call using the app access token from above.
hope this helps
You can use AppID and Secret key to get the public posts/feed of any page. This way you don't need to get the access-token. Call it like below.
https://graph.facebook.com/PAGE-ID/feed?access_token=APP-ID|APP-SECRET
And to get posts.
https://graph.facebook.com/PAGE-ID/posts?access_token=APP-ID|APP-SECRET
It's no more possible to use Facebook Graph API without access token for reading public page statuses, what is called Page Public Content Access in Facebook API permissions. Access token even is not enough. You have to use appsecret_proof along with the access token in order to validate that you are the legitimate user. https://developers.facebook.com/blog/post/v2/2018/12/10/verification-for-individual-developers/.
If you are individual developer, you have access to three pages of the data (limited), unless you own a business app.
You can get the posts by simply requesting the site that your browser would request and then extracting the posts from the HTML.
In NodeJS you can do it like this:
// npm i request cheerio request-promise-native
const rp = require('request-promise-native'); // requires installation of `request`
const cheerio = require('cheerio');
function GetFbPosts(pageUrl) {
const requestOptions = {
url: pageUrl,
headers: {
'User-Agent': 'Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0'
}
};
return rp.get(requestOptions).then( postsHtml => {
const $ = cheerio.load(postsHtml);
const timeLinePostEls = $('.userContent').map((i,el)=>$(el)).get();
const posts = timeLinePostEls.map(post=>{
return {
message: post.html(),
created_at: post.parents('.userContentWrapper').find('.timestampContent').html()
}
});
return posts;
});
}
GetFbPosts('https://www.facebook.com/pg/officialstackoverflow/posts/').then(posts=>{
// Log all posts
for (const post of posts) {
console.log(post.created_at, post.message);
}
});
For more information and an example of how to retrieve more than 20 posts see: https://stackoverflow.com/a/54267937/2879085
I had a similar use case for some weeks and I used this API:
https://rapidapi.com/axesso/api/axesso-facebook-data-service/
I could fetch all posts and comments in some minutes, worked quite well for me.
I'm looking to create a scheduled job using a Azure mobile service.
Since the service will end up calling another cloud service (website), I was wondering if the mobile script could access a database the cloud service already does.
I understand you can specify a database to use for the mobile script (I selected free for logging) but can't seem to tell if you can access other databases through the API.
var todoItemsTable = tables.getTable('TodoItems');
Hypothetically...
var todoItemsTable = databases.getDatabase('NonMobileSqlDb').tables.getTable('TodoItems');
I've already checked this question (Can you mix Azure Mobile Services with Azure Cloud Services?) but it doesn't seem to cover scripts talking to databases.
Some background...
The mobile service will (on a schedule) invoke a web service (with authorisation) that performs routine actions. I'd like to lock down this service (without ssl) and one way is to generate a key the service could use that the cloud service could verify. This key would be stored in the database both can access and only be available for a short period of time.
Yes you can.
You need to connect using the following example (uses Node.js) taken from the how-to guide:
To use the node-sqlserver, you must require it in your application and
specify a connection string. The connection string should be the ODBC
value returned in the How to: Get SQL Database connection information
section of this article. The code should appear similar to the
following:
var sql = require('node-sqlserver');
var conn_str = "Driver={SQL Server Native Client 10.0};Server=tcp:{dbservername}.database.windows.net,1433;Database={database};Uid={username};Pwd={password};Encrypt=yes;Connection Timeout=30;";
Queries can be performed by specifying a Transact-SQL statement with
the query method. The following code creates an HTTP server and
returns data from the ID, Column1, and Column2 rows in the Test table
when you view the web page:
var http = require('http')
var port = process.env.port||3000;
http.createServer(function (req, res) {
sql.query(conn_str, "SELECT * FROM TestTable", function (err, results) {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.write("Got error :-( " + err);
res.end("");
return;
}
res.writeHead(200, { 'Content-Type': 'text/plain' });
for (var i = 0; i < results.length; i++) {
res.write("ID: " + results[i].ID + " Column1: " + results[i].Column1 + " Column2: " + results[i].Column2);
}
res.end("; Done.");
});
}).listen(port);
Many thanks to #GauravMantri & #hhaggan for their help in getting this far.