I'm trying to populate data from my DB using Angular and some API services.
My code:
$http.get("/api/trips")
.then(function (response) {
angular.copy(response.data, vm.trips);
}, function (error) {
vm.errorMessage = "Failed to load data: " + error
});
And my API GET() :
[HttpGet("")]
public IActionResult Get()
{
var results = _repository.GetTripsByUsername(this.User.Identity.Name);
return Ok(Mapper.Map<IEnumerable<TripViewModel>>(results));
}
No data is showing. I'm pretty sure the errors is popping because the this.User.Identity.Name is passed wrongly, but I'm confused.
If I change the method from GetTripsByUsername to GetAllTrips , which select all the trips without filter, then the data is shown properly in the page.
The function it self works, if I use it via PostMan, it recognize my cookie and bringing me the correct trips(inside postMan) but on the page it doesn't work ..
It doesn't because your angular application is not authenticated and this.User.Identity.Name is null.
You need to send credential in your angular code like that:
$http.get("/api/trips", { withCredentials: true })
.then(function (response) {
angular.copy(response.data, vm.trips);
}, function (error) {
vm.errorMessage = "Failed to load data: " + error
});
But it depends on your authentication mecanism, This code will not work for Oauth or Basic authentication. If you use Oauth, you must send the Authorization header containing the authorization token.
Related
I'm working on a web project (HTML, CSS, JavaScript, with back-end in PHP). I've successfully got a Google Sign-in working, using their simple API, but can't get the Microsoft equivalent to function. The official online solutions to this seem to rely on .NET or PHP Composer. I'll try composer if that's the only way but a pure JS/PHP method would be easiest.
I've tried to use the following:
https://github.com/microsoftgraph/msgraph-sdk-javascript
https://github.com/AzureAD/microsoft-authentication-library-for-js
The code below is the closest I've come to a working solution. I can get some kind of user ID (which appears to be unique and constant for each user). This might be enough to set up the login system I want, but it would be ideal if I could also fetch their name and profile picture.
<script class="pre">
var userAgentApplication = new Msal.UserAgentApplication("MY CLIENT ID", null, function (errorDes, token, error, tokenType) {
// this callback is called after loginRedirect OR acquireTokenRedirect (not used for loginPopup/aquireTokenPopup)
})
userAgentApplication.loginPopup(["user.read"]).then(function (token) {
var user = userAgentApplication.getUser(); //this is good
//user.userIdentifier seems to be a unique ID
//I will store this and use it for future verification
console.log(user);
//START
// get an access token
userAgentApplication.acquireTokenSilent(["user.read"]).then(function (token) {
console.log("ATS promise resolved");
}, function (error) {
console.log(error);
// interaction required
if (error.indexOf("interaction_required") != -1) {
userAgentApplication.acquireTokenPopup(["user.read"]).then(function (token) {
// success
console.log("s2");
}, function (error) {
console.log("e2");
// error
});
}
});
//END
// signin successful
}, function (error) {
console.log(error);
// handle error
});
</script>
(this code won't run as I've pasted it because it relies on the MSAL script from the second github link, and needs an application client ID)
After getting the access token with scope user.read , you could call microsoft graph api to get sign-in user's profile information such as displayName , businessPhones :
https://graph.microsoft.com/v1.0/me
Content-Type:application/json
Authorization:Bearer {token}
To get user's profile photo :
GET https://graph.microsoft.com/v1.0/me/photo/$value
In addition , if you are using Microsoft Graph JavaScript Client Library in first link , you could get user's displayName and profile photo by :
client
.api('/me')
.select("displayName")
.get((err, res) => {
if (err) {
console.log(err);
return;
}
console.log(res);
});
// Example of downloading the user's profile photo and displaying it in an img tag
client
.api('/me/photo/$value')
.responseType('blob')
.get((err, res, rawResponse) => {
if (err) throw err;
const url = window.URL;
const blobUrl = url.createObjectURL(rawResponse.xhr.response);
document.getElementById("profileImg").setAttribute("src", blobUrl);
});
Please refer to code sample here .
I am using AngularJS and trying to work with Google's reCAPTCHA,
I am using the "Explicitly render the reCAPTCHA widget" method for displaying the reCAPTCHA on my web page,
HTML code -
<script type="text/javascript">
var onloadCallback = function()
{
grecaptcha.render('loginCapcha', {
'sitekey' : 'someSiteKey',
'callback' : verifyCallback,
'theme':'dark'
});
};
var auth='';
var verifyCallback = function(response)
{
//storing the Google response in a Global js variable auth, to be used in the controller
auth = response;
var scope = angular.element(document.getElementById('loginCapcha')).scope();
scope.auth();
};
</script>
<div id="loginCapcha"></div>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
So far, I am able to achieve the needed functionality of whether the user is a Human or a Bot,
As per my code above, I have a Callback function called 'verifyCallback' in my code,
which is storing the response created by Google, in a global variable called 'auth'.
Now, the final part of reCAPCHA is calling the Google API, with "https://www.google.com/recaptcha/api/siteverify" as the URL and using a POST method,And passing it the Secret Key and the Response created by Google, which I've done in the code below.
My Controller -
_myApp.controller('loginController',['$rootScope','$scope','$http',
function($rootScope,$scope,$http){
var verified = '';
$scope.auth = function()
{
//Secret key provided by Google
secret = "someSecretKey";
/*calling the Google API, passing it the Secretkey and Response,
to the specified URL, using POST method*/
var verificationReq = {
method: 'POST',
url: 'https://www.google.com/recaptcha/api/siteverify',
headers: {
'Access-Control-Allow-Origin':'*'
},
params:{
secret: secret,
response: auth
}
}
$http(verificationReq).then(function(response)
{
if(response.data.success==true)
{
console.log("Not a Bot");
verified = true;
}
else
{
console.log("Bot or some problem");
}
}, function() {
// do on response failure
});
}
So, the Problem I am actually facing is that I am unable to hit the Google's URL, Following is the screenshot of the request I am sending and the error.
Request made -
Error Response -
As far as I understand it is related to CORS and Preflight request.So what am I doing wrong? How do I fix this problem?
As stated in google's docs https://developers.google.com/recaptcha/docs/verify
This page explains how to verify a user's response to a reCAPTCHA challenge from your application's backend.
Verification is initiated from the server, not the client.
This is an extra security step for the server to ensure requests coming from clients are legitimate. Otherwise a client could fake a response and the server would be blindly trusting that the client is a verified human.
If you get a cors error when trying to sign in with recaptcha, it could be that your backend server deployment is down.
Using the code from the docs:
function deleteRequest(requestId) {
FB.api(requestId, 'delete', function(response) {
console.log(response);
});
}
I am returned an error:
(#2) App Request Recipient Must Be Specified: The recipient for this app request must be specified through a user-signed access token or the fully specified app request ID.
I'm definitely connected to the FB REST before this, any thoughts?
if your app has migrated to Requests 2.0 efficient, than the requestId must contain both the apprequest id and the user id with _ between (because the same apprequest might be sent to multiple users)
for example:
apprequest=1111111 and
user_id=2222222
then the requestId will be 1111111_2222222
function deleteRequest(appRequestId, userId) {
FB.api(appRequestId+"_"+userId, 'delete', function(response) {
console.log(response);
});
}
If you use the C# facebook SDK you can use this:
var fb = new FacebookClient(Config.FacebookAppId, Config.FacebookAppSecret);
var result = fb.Delete(string.Format("{0}_{1}?access_token={2}", facebookRequestId, facebookUserId, fb.AccessToken));
(see also this question: Facebook Deleting Requests)
In the authentication flow documentation here it mentions the CODE which is returned upon oAuth authentication.
Is this required for the Javascript SDK or is this handled automatically in the background in this code?
By "is this required?" I mean, do I have to handle this code to verify the authenticity of the request, or does the JavaScript SDK use the code automatically to gain the access_token.
The documentation explains the client side flow, and how to get the access token using the 'code' so until now. I've been assuming that the SDK manages this automatically in the background, because it produces an access code as response.authResponse.accessToken.
FB.login(function(response) {
if (response.authResponse) {
// User is logged in to Facebook and accepted permissions
// Assign the variables required
var access_token = response.authResponse.accessToken;
var fb_uid = response.authResponse.userID;
alert(dump(response.authResponse));
// Construct data string to pass to create temporary session using PHP
var fbDataString = "uid=" + fb_uid + "&access_token=" + access_token;
// Call doLogin.php to log the user in
$.ajax({
type: "POST",
url: "ajax/doLogin.php",
data: fbDataString,
dataType: "json",
success: function(data) {
// Get JSON response
if (data.result == "failure")
{
alert(data.error_message);
window.location.reload();
return false;
}
else if (data.result == "success")
{
window.location.reload();
return true;
}
},
error: function() {
return false;
}
});
} else {
// user is not logged in and did not accept any permissions
return false;
}
}, {scope:'publish_stream,email'});
I would like to know, because I want to ensure that my code is secure.
From the documentation
With this code in hand, you can proceed to the next step, app authentication, to gain the access token you need to make API calls.
In order to authenticate your app, you must pass the authorization code and your app secret to the Graph API token endpoint at https://graph.facebook.com/oauth/access_token. The app secret is available from the Developer App and should not be shared with anyone or embedded in any code that you will distribute (you should use the client-side flow for these scenarios).
If you plan on using the FB.api function to make calls to their Graph API, then you need the code to get the access token. But if you only need to authenticate the user, then what you have will do that just fine.
I am currently developing a Facebook application on a website that would need to send a notification to the app's users without using a user interface dialog. After reading some blogs I concluded that the option is available in example in PHP API only. I could only find this example:
http://developers.facebook.com/docs/channels/
Is there a JavaScript API to do this?
After some sort of more reading, I found out that FB.api could handle graph object apis and also the rest apis which are to be deprecated, and I got the following working:
FB.api('/1175241653/apprequests', 'post',
{ message: "This is a Good Request!!" },
function (response) {
if (!response || response.error) {
alert('Error occured , Request Failed :(( ');
} else {
alert('Request is sent successfully');
}
});
However, that id number 1175241653 does not work if the logged in user's id is not that id.
Therefore this would required the same functionaliy that Facebook uses to retrieve the ID of whomever signed into the application. Is there any way to do this?
Now , I got this working in all means and I'd like to share it with those who may deal with :))
lets say 1st as to do a single app request from ur application to any of facebook registered users in your application would be like this:
var data =
{
message: "Hey there, something good happened over here !",
access_token: "AAADdf39DLxgBANEwZA9ZCfZCSbtdfcZBtstWMMsW5JiZBjVW2Ucx234sedhHSZCm8aEABzvhWPBNWi1bTKwZBq0EcgZD"
}
FB.api('/68751034/apprequests',
'post',
data,
function (response) {
console.log(response);
if (!response || response.error) {
} else {
}
});
access_token should be provided as to authenticate the request from the application to the registered user.
If you do not know about access tokens, you can read about it over at the facebook site:
http://developers.facebook.com/docs/authentication/
Also, if you want to send batch requests to a set of users in one request call, there's a support page from the facebook site about that too:
http://developers.facebook.com/docs/reference/api/batch/
and here's a sample of what I mean :
var _batch = [];
for (var i = 0; i < _socialids.length; i++) {
_batch.push({
method: 'post',
relative_url: _socialids[i] + '/apprequests/?access_token=' + _accessTokens[i],
body: "message= This is a request sent to many users" });
}
if (_batch.length > 0) {
FB.api('/', 'POST', { batch: _batch }, function (res) {
// Do whatever when the batch request is sent
});
}