Cannot read user info - Adal error cannot login - javascript

I am trying to implement authentication with ADAL (Inside a react app), so I followed the example from Azure-Samples, and this is my code:
var AuthenticationContext = require('../../node_modules/adal-angular/lib/adal.js');
var adalInstance = new AuthenticationContext({
instance: 'https://login.microsoftonline.com/',
clientId: '9897809e-XXXX-XXXX-XXXX-3e6de068af92',
postLogoutRedirectUri: window.location.origin,
endpoints: {}
});
export function enter() {
adalInstance.login();
var isCallback = adalInstance.isCallback(window.location.hash);
adalInstance.handleWindowCallback();
if (isCallback && !adalInstance.getLoginError()) {
adalInstance.acquireToken(adalInstance.config.clientId, function (error, token) {
if (error || !token) {
console.log('ADAL Error Occurred: ' + error);
return;
}
});
}
var user = adalInstance.getCachedUser();
console.log(user);
}
export function logout() {
adalInstance.logout();
}
So I have the following messages:
ADAL Error Occurred: User login is required
and for user, I get null.
Currently I can go to the microsoft login page (called from the login component), login, and return to the app. I have the sessionStorage set:
Storage { adal.state.login: "73771340-XXXX-XXXX-XXXX-858c9edcba05", adal.nonce.idtoken: "20074445-XXXX-XXXX-XXXX-9f94c9b5cc31", adal.login.error: "", adal.error: "Invalid_state", adal.login.request: "http://localhost:3000/#id_token=eyJ…", adal.error.description: "Invalid_state. state: a2f210a5-e34b…", adal.token.renew.status: "Completed", length: 7 }
What I am doing wrong?
DATA: I am using adal.js library from the adal-angular package version: AdalJS v1.0.13
EDIT:
Now I am using an specific adal.js from here
I changed my code to:
var AuthenticationContext = require('./adal.js');
When I compiled it (using webpack with babel for transpiling es6 code), but gave me an error about logging is not defined, so I added:
var Logging = {
level: 3,
log: function (message) {
console.log(message);
}
}
to the adal library.
And now, I am getting in the browser(firefox, because chromes seems to not show any log I dont know why) console:
Wed, 18 Jan 2017 11:52:51 GMT:1.0.13-VERBOSE: State: d3c2bb0d-XXXX-XXXX-XXXX-e98a460572e2 bundle.js:74558:8
Wed, 18 Jan 2017 11:52:51 GMT:1.0.13-INFO: Returned from redirect url bundle.js:74558:8
Wed, 18 Jan 2017 11:52:51 GMT:1.0.13-INFO: State status:false; Request type:UNKNOWN bundle.js:74558:8
Wed, 18 Jan 2017 11:52:51 GMT:1.0.13-WARNING: User login is required bundle.js:74558:8
ADAL Error Occurred: User login is required bundle.js:74507:10
USER null bundle.js:74513:4

During integrating with PowerBi endpoint, I got a same error. After some research got this result. So the code below does auto login. Replace the method yourLogic to use the token for api request.
import AuthenticationContext from "adal-angular/lib/adal";
window.AuthenticationContext = AuthenticationContext;
let authenticationContext = new window.AuthenticationContext({
instance: "https://login.microsoftonline.com/",
clientId: "XXXXXXX",
postLogoutRedirectUri: window.location.origin,
cacheLocation: "localStorage", // enable this for IE, as sessionStorage does not work for localhost.
}),
resource = "https://analysis.windows.net/powerbi/api",
isCallback = authenticationContext.isCallback(window.location.hash);
authenticationContext.handleWindowCallback();
let user = authenticationContext.getCachedUser(),
token = authenticationContext.getCachedToken(resource),
loginActive = isCallback && user && !token,
renewActive = isCallback && user && !!token;
if (user) {
if (!renewActive) {
authenticationContext.acquireToken(resource, (errorDesc, token, error) => {
if (!error) {
yourLogic(token);
} else {
authenticationContext.error("Error when acquiring token for resource: " + resource, error);
}
});
}
} else {
authenticationContext.login();
}

Sorry for the characters limitation of comment, I write my troubleshooting suggestion as an answer here.
Actually, your code snippet works fine on my side. For troubleshooting and arrow down the issue, you can try the following options.
Currently, it seems that the javascript syntax on browser is not support export,require key words. So you can check the bundled script, whether there is anything wrong about the global variables. You can test your AAD application with plain javascript within adal.js, as the sample you are referring.
You can try to add global variable logging to track all the info during the authentication flow. E.G. add following code in js script.
Logging = {
level: 3,
log: function (message) {
console.log(message);
}
}

Related

zoomsdk react and node integration always ends up with an error

I have been trying to integrate zoomsdk in my react app and also followed every step metioned here. Backend part is working fine and I am getting back the signature response. But when I try to run the frontend part, it throws this error:
Error: error:0308010C:digital envelope routines::unsupported
at new Hash (node:internal/crypto/hash:71:19)
at Object.createHash (node:crypto:140:10)
at module.exports (/Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/webpack/lib/util/createHash.js:135:53)
at NormalModule._initBuildHash (/Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/webpack/lib/NormalModule.js:417:16)
at handleParseError (/Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/webpack/lib/NormalModule.js:471:10)
at /Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/webpack/lib/NormalModule.js:503:5
at /Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/webpack/lib/NormalModule.js:358:12
at /Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/loader-runner/lib/LoaderRunner.js:373:3
at iterateNormalLoaders (/Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/loader-runner/lib/LoaderRunner.js:214:10)
at iterateNormalLoaders (/Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/loader-runner/lib/LoaderRunner.js:221:10)
/Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/react-scripts/scripts/start.js:19
throw err;
^
Error: error:0308010C:digital envelope routines::unsupported
at new Hash (node:internal/crypto/hash:71:19)
at Object.createHash (node:crypto:140:10)
at module.exports (/Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/webpack/lib/util/createHash.js:135:53)
at NormalModule._initBuildHash (/Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/webpack/lib/NormalModule.js:417:16)
at /Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/webpack/lib/NormalModule.js:452:10
at /Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/webpack/lib/NormalModule.js:323:13
at /Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/loader-runner/lib/LoaderRunner.js:367:11
at /Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/loader-runner/lib/LoaderRunner.js:233:18
at context.callback (/Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/loader-runner/lib/LoaderRunner.js:111:13)
at /Users/vickpro/React projects/expert-buddy-demo/Frontend/node_modules/babel-loader/lib/index.js:59:103 {
opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'
}
The methods I have tried,
updating the current project webpack(v4.44.2) to latest one which is v5.75.0.
Tried updating my node js version to latest.
Neither of them worked in my case, I am still getting the same error.
Here is my app.js file code:
import React from "react";
import "./App.css";
import { ZoomMtg } from "#zoomus/websdk";
ZoomMtg.setZoomJSLib("https://source.zoom.us/2.9.7/lib", "/av");
ZoomMtg.preLoadWasm();
ZoomMtg.prepareWebSDK();
// loads language files, also passes any error messages to the ui
ZoomMtg.i18n.load("en-US");
ZoomMtg.i18n.reload("en-US");
function App() {
// setup your signature endpoint here: https://github.com/zoom/meetingsdk-sample-signature-node.js
var signatureEndpoint = "http://localhost:4000";
// This Sample App has been updated to use SDK App type credentials https://marketplace.zoom.us/docs/guides/build/sdk-app
var sdkKey = "nMYXtjORjReaes6NpngNPakcKP3CiFdIfN7D";
var meetingNumber = "85433353829";
var role = 0;
var leaveUrl = "http://localhost:3000";
var userName = "React";
var userEmail = "vickbishnoi#gmail.com";
var passWord = "000000";
// pass in the registrant's token if your meeting or webinar requires registration. More info here:
// Meetings: https://marketplace.zoom.us/docs/sdk/native-sdks/web/client-view/meetings#join-registered
// Webinars: https://marketplace.zoom.us/docs/sdk/native-sdks/web/client-view/webinars#join-registered
var registrantToken = "";
function getSignature(e) {
e.preventDefault();
fetch(signatureEndpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
meetingNumber: meetingNumber,
role: role,
}),
})
.then((res) => res.json())
.then((response) => {
startMeeting(response.signature);
})
.catch((error) => {
console.error(error);
});
}
function startMeeting(signature) {
document.getElementById("zmmtg-root").style.display =
"block";
ZoomMtg.init({
leaveUrl: leaveUrl,
success: (success) => {
console.log(success);
ZoomMtg.join({
signature: signature,
meetingNumber: meetingNumber,
userName: userName,
sdkKey: sdkKey,
userEmail: userEmail,
passWord: passWord,
tk: registrantToken,
success: (success) => {
console.log(success);
},
error: (error) => {
console.log(error);
},
});
},
error: (error) => {
console.log(error);
},
});
}
return (
<div className="App">
<main>
<h1>Zoom Meeting SDK Sample React</h1>
<button onClick={getSignature}>Join Meeting</button>
</main>
</div>
);
}
export default App;
On the screen, I get this error:
It has been 3-4 days since I have trying different approaches to integrate zoom in my react app but none of them are working.
It is very important to me as it is part of an assignment given to me by one of the companies I interviewed in. In this part, I am required to build a screen where there is a create meeting button which should be able to create a zoom meeting and after that, we should be able to share the meeting link to other people and when any individual clicks on the link, they should first be brought to that page and then there should be a join meeting button which takes them to the meeting. After the meeting ends, we should be able to take the meeting attendees to a feedback screen where they should be able to share their experience.
If I am able to pull this thing off, they are going to offer me a position and being a self taught developer without a cs degree, it really is a golden opportunity for me, so any help from you guys would be incredibly helpful for me.
Please watch the Zoom WebSDK Integration using ReactJS -> Here.

Why all users in Strapi have access to update all users profile?

I added a new filed called config (type: json) to the User model. I use built-in swagger of Strapi local document. The problem is that I can update another user config (data) with put method.
First, I authorized by POST /auth/local and get my token and my user id (in this cast it's 5)
I add my token to swagger Authorize button.
Then, I use PUT /user/{id} in this case id is 5.
Calling api http://localhost:1337/api/users/4 returns 200!
I expect that I get 403 error! Because I should not able to change other user profiles!!!
Is it normal? If yes, tell me a solution to fix this.
This is because Strapi has only two default roles:
Public
Authenticated
So by default, when you setup permissions, whatever authentication state currently the user has access to all the content accordingly (e.g. Public to only public, Authenticated to authenticated)
To work with this, and to limit the user actions in the auth scope you have to use middleware or policy, so since this is in user-permissions scope let's add policy to user-permissions:
Strapi 4.5.3
yarn strapi generate
? Strapi Generatos
>policy
? Policy name
isOwner
? Where do you want to add this policy?
> Add policy to root of project
Next step is in your /src/extensions folder you have to create folder users-permissions, and in this folder file strapi-server.js with following content:
/src/extensions/users-permissions/strapi-server.js
module.exports = (plugin) => {
for (let i = 0; i < plugin.routes["content-api"].routes.length; i++) {
const route = plugin.routes["content-api"].routes[i];
if (
route.method === "GET" &&
route.path === "/users/:id" &&
route.handler === "user.findOne"
) {
console.log(route);
plugin.routes["content-api"].routes[i] = {
...route,
config: {
...route.config,
policies: route.config.policies
? [...route.config.policies, "global::isOwner"] // tests if policies were defined
: ["global::isOwner"],
},
};
}
}
return plugin;
};
if you did the step correct in your strapi server console you have to see:
info: In isOwner policy. if you send get request to /api/users/:id
Next step is we are going to modify policy file like so:
/src/policies/isOwner.js
"use strict";
/**
* `isOwner` policy
*/
module.exports = async (policyContext, config, { strapi }) => {
strapi.log.info("In isOwner policy.");
const { user, auth } = policyContext.state;
const { params } = policyContext;
// this case the userId is the same as the id we are requesting
// other cases would need more extensive validation...
const canDoSomething = user.id == params.id;
if (canDoSomething) {
return true;
}
return false;
};
and whoala:
{
"data": null,
"error": {
"status": 403,
"name": "PolicyError",
"message": "Policy Failed",
"details": {}
}
}
if we try to get other user profile

MS graph API: 400 AuthenticationError with "/me/onlineMeetings" request

I am trying to create an online meeting and recover its URL like explained here in the docs, but when the request is run I get this error:
{
"statusCode": 400,
"code": "AuthenticationError",
"message": "Error authenticating with resource",
"requestId": "652ea3be-6a97-47e8-bfc6-3d7d1d51d425",
"date": "2020-09-01T12:53:41.000Z",
"body": "{
"code":"AuthenticationError",
"message":"Error authenticating with resource",
"innerError":{
"date":"2020-09-01T13:53:41",
"request-id":"652ea3be-6a97-47e8-bfc6-3d7d1d51d425"
}
}"
}
I tried also the get started projet for JS and it's working fine so I can't spot the problem.
here is what I used:
const msalConfig = {
auth: {
clientId: 'my_app_id',
redirectUri: 'http://localhost:8080'
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: false,
forceRefresh: false
}
};
const loginRequest = { scopes: [
'openid',
'profile',
'user.read',
'calendars.read',
'User.Read.All',
'User.Export.All'
]
}
const options = new MicrosoftGraph.MSALAuthenticationProviderOptions([
'user.read',
'calendars.read',
'OnlineMeetings.ReadWrite'
]);
const onlineMeeting = {
startDateTime:"2020-09-01T16:00:34.2444915-07:00",
endDateTime:"2020-09-01T16:30:34.2464912-07:00",
subject:"test meeting"
};
const authProvider = new MicrosoftGraph.ImplicitMSALAuthenticationProvider(msalClient, options);
// Initialize the Graph client
const graphClient = MicrosoftGraph.Client.initWithMiddleware({authProvider});
// then I call this inside an async function
let events = await graphClient.api('/users/my_UserPrincipalName/onlineMeetings').post(onlineMeeting);
//let events = await graphClient.api('/me/onlineMeetings').post(onlineMeeting);
// I tried with both calls and none of them worked
and here are the permissions on azure active directory:
So any ideas on how to solve this ?
thanks
You didn't provide a correct access token.
Since Create onlineMeeting only supports Delegated (work or school account) permission type, you need to get the access token with Auth code flow or Implicit flow.
The started project for JS is using Implicit flow. So you can use Implicit flow to get the access token.
Here is the example in Postman:
The Auth URL above is https://login.microsoftonline.com/{your tenant}/oauth2/v2.0/authorize.
I figured out how to make it work in my code:
let's call my user, which I used all this time, user "A", all I did is that I simply created another user "B" in Azure Active Directory and then logging in with this new user "B" in the login screen instead of the admin user "A" that I used before..... and now it's working.
But this does not explain the issue, so if anyone can explain the difference or why it didn't work with the first account, that would be very helpful.

Parse-server social login

I am developing application based on Parse-server and I want to offer social login. I found this guide in the documentation http://docs.parseplatform.org/js/guide/#linking-users.
I started to implement the social login by google. I did following steps:
1) I added following lines to the ParseServer settings
var api = new ParseServer({
...
auth:{
google: {}
},
...
});
2) I did the authentication by hello.js on the client side (call user._linkWith function on login)
hello.init({
google: 'My Google id'
});
hello.on('auth.login', function(auth) {
// Call user information, for the given network
hello(auth.network).api('me').then(function(r) {
const user = new Parse.User();
user._linkWith(auth.network, auth.authResponse).then(function(user){
console.log('You are logged in successfully.');
});
});
});
When I debugged it, I found that it fails in _linkWith() function, when provider object is preparing. Object AuthProviders, which should store all providers, is empty. Because of it the statement provider = authProviders['google']; leads to undefined. Invoking provider.authenticate(...); leads to error "Cannot read property 'authenticate' of undefined"
What am I missing or what am I doing wrong?
Thanks for all your answers.
Honza
Did you register the authenticationProvider? You can find examples in our unit tests on how to do so:
https://github.com/parse-community/parse-server/blob/5813fd0bf8350a97d529e5e608e7620b2b65fd0c/spec/AuthenticationAdapters.spec.js#L139
I also got this error and looked at the _linkWith(provider, options) source code. It checks if options has an authData field (which in turn should contain id and credentials). If so, it uses options.authData. Otherwise it falls back on looking up a previously registered authentication provider mentioned in the previous answer.
This is a fragment of the code I'm using:
const authData = {
"id": profile.getId(),
"id_token": id_token
}
const options = {
"authData": authData
}
const user = new Parse.User();
user._linkWith('google', options).then(function(user) {
console.log('Successful user._linkWith(). returned user=' + JSON.stringify(user))
}, function(error) {
console.log('Error linking/creating user: ' + error)
alert('Error linking/creating user: ' + error)
// TODO handle error
})

How to use servicebus topic sessions in azure functionapp using javascript

I have an Azure Functionapp that processes some data and pushes that data into an Azure servicebus topic.
I require sessions to be enabled on my servicebus topic subscription. I cannot seem to find a way to set the session id when using the javascript functionapp API.
Here is a modified extract from my function app:
module.exports = function (context, streamInput) {
context.bindings.outputSbMsg = [];
context.bindings.logMessage = [];
function push(response) {
let message = {
body: CrowdSourceDatum.encode(response).finish()
, customProperties: {
protoType: manifest.Type
, version: manifest.Version
, id: functionId
, rootType: manifest.RootType
}
, brokerProperties: {
SessionId: "1"
}
context.bindings.outputSbMsg.push(message);
}
.......... some magic happens here.
push(crowdSourceDatum);
context.done();
}
But the sessionId does not seem to get set at all. Any idea on how its possible to enable this?
I tested sessionid on my function, I can set the session id property of a message and view it in Service Bus explorer. Here is my sample code.
var connectionString = 'servicebus_connectionstring';
var serviceBusService = azure.createServiceBusService(connectionString);
var message = {
body: '',
customProperties:
{
messagenumber: 0
},
brokerProperties:
{
SessionId: "1"
}
};
message.body= 'This is Message #101';
serviceBusService.sendTopicMessage('testtopic', message, function(error)
{
if (error)
{
console.log(error);
}
});
Here is the test result.
Please make sure you have enabled the portioning and sessions when you created the topic and the subscription.

Categories

Resources