How to get user.email in server using auth0 and node.js? - angularjs

On my frontend, I can see the email through:
console.log(auth.profile.email)
Then I call this service to retrieve some information from the backend, it's protected so you need to be logged in to get anything back:
var metadata_req = {
method: "GET",
url: "http://localhost:80/protected/all/metadata"
}
On the backend, I'm using node.js and this to verify that the user is logged in before doing a request:
var jwtCheck = express-jwt({
secret: new Buffer(config.secret, 'base64'),
audience: config.client_id
});
But if I print out req.user, I only see iss, sub, aud, exp and iat. I would like to see the email as well.

You can get profile information in req.user by including the email permission when your user initially logs in.
For example, using lock in angular would look like this:
auth.signin({
authParams: {
scope: 'openid email'
}
}, function(profile, token) {
// stuff
}, function(err) {
// error handling
});

Change your API definition from "all/metadata" to "all/metadata/:emailId"
Call your API
var metadata_req = {
method: "GET",
url: "http://localhost:80/protected/all/metadata/{your_email_id}"
}
In NodeJS retrieve you email_id from req.params.emailId

Related

API VEEML - LOGIN

I would like to load data from VEEML to our website. I found some documentation on the API /getgrid2 but I need to add my security token in the query.
How can I get my security token? Is there a specific endpoint that I can call?
Each time you will use a VEEML API, you need to be authenticated properly by the method /login.
Using this endpoint, you will get a valid authentication token to use with the other endpoints.
You need to include the javascript library sah256.js previously.
-> "https://the-url.ofyour.portal/js/sah256.js"
var _email = 'myemail; // Here the email of an "admin" account
var _password = 'mypassword'; // Here the password
var _hash = CryptoJS.SHA256(_password);
var _data = {"email": _email, "password": _hash.toString()};
var _url = "https://the-url.ofyour.portal/login"; //
api to authenticate the user
$.ajax({
type: "POST",
url: _url,
dataType : 'jsonp',
data: _data,
error: function(xhr, response, error)
{console.log(error);},
success: function(json){console.log(json.success);
});

Outlook REST API 403 error while trying to fetch user emails

I am trying to fetch emails from user's outlook mail using Outlook REST API. I have been able to successfully authenticate user and get user access token, however, when I try to make an AJAX call to Outlook REST API, I get the following error:
GET https://outlook.office.com/api/v2.0/me/messages?callback=jQuery31008093694845457056_1490285639120 403 (Forbidden)
Also, I get following error from error function callback of AJAX:
Object {readyState: 4, status: 404, statusText: "error"}
Here is my code:
var ADAL = new AuthenticationContext({
instance: 'https://login.microsoftonline.com/',
tenant: 'common',
clientId: '', //Intentionally left blank here
redirectUri: 'http://localhost:8383/',
callback: userSignedIn,
popUp: true
});
function signIn() {
ADAL.login();
}
function userSignedIn(err, token) {
console.log('userSignedIn called');
if (!err) {
console.log(token); //This works!
fetchUserSentMails(token);
} else {
console.error("error: " + err);
}
}
function fetchUserSentMails(token) {
var user = ADAL.getCachedUser();
console.log(user.profile.name); //This works!
$.ajax({ //This doesn't work
type: 'GET',
crossDomain: true,
url: 'https://outlook.office.com/api/v2.0/me/messages',
dataType: 'jsonp',
headers: {'Authorization': 'Bearer ' + token},
success: function (res) {
console.log(res);
},
error: function (x, t, m) {
console.log(x);
console.log(t);
console.log(m);
}
});
}
What am I doing wrong??
The most likely answer is your token doesn't have the proper scope. Parse your token at https://jwt.io and see what you have in the scp claim.
It looks like you're missing a call to AcquireToken. The login method just signs the user in and gets their identity, it doesn't provide an access token. You need something like this:
ADAL.acquireToken("https://outlook.office.com", function(error, accessToken){
if (error) {
console.log('ERROR: ' + JSON.stringify(error));
} else {
fetchUserSentMails(accessToken);
}
}
I see that you are getting timeout error. I had the exact same issue with timeout and I could only fix this by manipulating adal.js library. In this library there is a timeout of 6 seconds and it seems like it is very tight for some applications being loaded locally. To give it a quick test, you can find LOADFRAME_TIMEOUT: '6000' in adal.js and replace it with LOADFRAME_TIMEOUT: '30000', which will give you 30 seconds to load your application. I hope it works for you!

callback missmatch error in angular with auth0

Hi I'm using Auth0 with Nodejs and angularjs
here is what i want to achieve
1. I want to user to signup using auth0's lock
2. as soon as user logs in a callback should be called at my nodejs server
3. after that i will get the user information and user's JWT
4. then i will redirect user to dashboard page and store the JWT in browser
What's the problem with Auth0's example
1. they provide example either for angular or nodejs standalone not the combined
2. there is combined(client server) example but that's using jade with nodejs
my code snipped
Angular snipped
var options = { auth: {
redirectUrl: 'http://localhost:3000/callback'
, responseType: 'code'
, params: {
scope: 'openid name email picture'
}
}
}
lockProvider.init({
clientID: 'cUlBNhhaIblahBlahRp6Km',
domain: 'rishabh.auth0.com',
option:options
});
node snipped
router.get('/callback',
passport.authenticate('auth0', { failureRedirect: '/url-if-something-fails' }),
function(req, res) {
console.log(req.user);
res.json({id_token:req.user});
});
Note: I've added this callbacks in auth0
http://localhost:3000/callback
but dont know why I'm facing this error for callback error when I've mentioned my redirect URL in angular side
can anyone tell me what is the problem with my code why auth0 not redirecting me to this url http://localhost:3000/callback
and the interesting thing is when i use simple lock.js instead of angular like this
<script>
var options = { auth: {
redirectUrl: 'http://localhost:3000/callback'
, responseType: 'code'
, params: {
scope: 'openid name email picture'
}
}
}
var lock = new Auth0Lock('clientID', 'rishabh.auth0.com',options);
lock.show();
</script>
then in this case my nodejs /callback route is called properly, so what I'm doing wrong with angular ?
please help
Update
this is my project structure
full code
https://github.com/LabN36/error
Config.js
var Auth0Strategy = require('passport-auth0');
var passport = require('passport');
var strategy = new Auth0Strategy({
domain: process.env.AUTH0_DOMAIN || 'rishabh.auth0.com',
clientID: process.env.AUTH0_CLIENT_ID || 'cUheWwRxm7OLdHBRzlBNvfvfvfvfvhhaI1lxRp6Km',
clientSecret: process.env.AUTH0_CLIENT_SECRET || 'e37eIZpjgBnDMBtrYMwvffvfvfvfaU4jSqt8qylZMT9Oj1EiffLGViinWQ5AiuWi1-WBwA8v3',
callbackURL: process.env.AUTH0_CALLBACK_URL || 'http://localhost:3000/callback'
}, function(accessToken, refreshToken, extraParams, profile, done) {
// accessToken is the token to call Auth0 API (not needed in the most cases)
// extraParams.id_token has the JSON Web Token
// profile has all the information from the user
console.log(extraParams.id_token);
//save user detail with token here and return token only profile
return done(null, extraParams.id_token);
});
passport.use(strategy);
// you can use this section to keep a smaller payload
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
module.exports = passport;
AngularApp.js
angular.module('workApp',['auth0.lock'])
.config(function($locationProvider,lockProvider){
var options = { auth: {
// redirect:true,
responseType: 'code',
redirectUrl: 'http://localhost:3000/callback',
params: {
scope: 'openid name email picture'
}
}
}
lockProvider.init({clientID: 'cUheWwRxm7OLdHBRzlBNhhaI1lxRp6Km',domain: 'rishabh.auth0.com',
option:options
});
$locationProvider.html5Mode(true);
})
.controller('homeCtrl',function($scope,$http,$location,$window,lock){
$scope.login = function() {
// window.alert("magic")
console.log("Messed Up really")
var vm = this;
vm.lock = lock;
lock.show();
}
}).run(function(lock){
lock.interceptHash();
lock.on('authenticated', function(authResult) {
localStorage.setItem('id_token', authResult.idToken);
lock.getProfile(authResult.idToken, function(error, profile) {
if (error) {
console.log(error);
}
localStorage.setItem('profile', JSON.stringify(profile));
});
});
})
According to the screenshot the error happens because the authentication request is made with a redirect_uri of:
http://localhost:3000/
and the allowed callback URL's are:
http://localhost:3000/callback
http://35.162.118.253:3000/callback
Also based on the code you shared you're indeed setting the redirectUrl to be http://localhost:3000/callback so there may be something on the rest of the code that either causes that value to be overridden or not used at all.
If the redirectUrl is not set, Lock will use the current page so the likely culprit is that the options you set are not being used. If you still don't find the cause for this, update the question with the code associated with how Lock is shown.
Damn, the actual root cause was already shown in the code you initially provided, but only looking now at the full code made it possible for me to catch it...
You're calling lockProvider.init() with:
{ clientID: [?], domain: [?], option: options }
when it should be called with:
{ clientID: [?], domain: [?], options: options } // options instead of option

HTTP POST with URL query parameters in Angular

I am trying to send POST request which contains url param, url query params and body.
My resource looks like this:
return $resource(myService.getResourceUrl('/users/:username/password'), {}, {
resetPassword: {
method: 'POST',
params: {passwordResetToken: '#passwordResetToken'}
}
});
Resource is used in service:
resetPassword: function(username, password, config){
return ru.handleErrors(passwordManagerResource.save({username: username}, password, config).$promise);
}
And finally service is called in the main controller:
var config = {passwordResetToken: '39af3539-12f8-4285-8a96-526a25c0fa00'};
var password = {password: 'Aaaaaaaa01'};
userManagementService.resetPassword("test_user", password, config).then(function(res){
console.log("helllloooo_again");
}
However query parameters are not added to the url. Generated URL has following structure:
http://localhost:8080/ghostwriter/users/test_user/password
instead of
http://localhost:8080/ghostwriter/users/test_user/password?passwordResetToken=39af3539-12f8-4285-8a96-526a25c0fa00

Angular $http post with custom headers

I am new to angular and am from .net framework. I need to post a angular request to .net service, where it expects two custom headers from the client.
angular post command:
var request = $http(
{
url: "http://localhost:53585/api/myService/Validate",
method: "POST",
data: JSON.stringify(payload),
headers: { 'first_token': sessionService.first_token, 'second_token': sessionService.second_token }
});
But in the service side, I can see only first_token in the request header and not the second token. What I am missing here?
Issue is with my service. I figured out and restarted the IIS and then service was able to read both the headers token
I found this method in a forum, it works.
return this.http.post<any>('https://yourendpoint', { username, password }, { headers: new HttpHeaders().set('Authorizaion', 'your token')})
.pipe(map(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// sto`enter code here`re user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
console.log(user);
return user;

Resources