Giter Site home page Giter Site logo

officedev / office-add-in-nodejs-sso Goto Github PK

View Code? Open in Web Editor NEW
54.0 54.0 35.0 1010 KB

[MOVED] The getAccessToken API in Office.js enables users who are signed into Office to get access to an AAD-protected add-in and to Microsoft Graph without needing to sign-in again. This sample is built on Node.js and express.

License: Other

JavaScript 71.20% HTML 2.18% CSS 18.02% PowerShell 1.10% Shell 0.12% Pug 7.38%

office-add-in-nodejs-sso's Introduction

[MOVED] Office Add-in that that supports Single Sign-on to Office, the Add-in, and Microsoft Graph

Note: This sample was moved to the PnP-OfficeAddins repo and is located at https://github.com/OfficeDev/PnP-OfficeAddins/tree/main/Samples/auth/Office-Add-in-NodeJS-SSO

This repo is archived and no longer actively maintained. Security vulnerabilities may exist in the project, or its dependencies. If you plan to reuse or run any code from this repo, be sure to perform appropriate security checks on the code or dependencies first. Do not use this project as the starting point of a production Office Add-in. Always start your production code by using the Office/SharePoint development workload in Visual Studio, or the Yeoman generator for Office Add-ins, and follow security best practices as you develop the add-in.

The getAccessToken API in Office.js enables users who are signed into Office to get access to an AAD-protected add-in and to Microsoft Graph without needing to sign-in again.

There are three versions of the sample in this repo, one of which has its own README file:

  • In the Begin folder is the starting point for the SSO walkthrough at at Create a Node.js Office Add-in that uses single sign-on. Please follow the instructions in the article.
  • In the Complete folder is the completed sample you would have if you completed the walkthrough. To use this version, follow the instructions in the article Create a Node.js Office Add-in that uses single sign-on, but substitute "Complete" for "Begin" in those instructions and skip the sections Code the client-side and Code the server-side.
  • In the SSOAutoSetup folder is essentially the same complete sample (with some slight differences in folder structure), but it contains a utility that will automate most of the registration and configuration. Instructions are in the README in that folder. Use this version if you would like to see a working SSO sample right away. However, we recommend that at some point you go through the manual process of registration and configuration that is documented in Create a Node.js Office Add-in that uses single sign-on, if you have never registered an app with AAD before. Doing so will give you a better understanding of what AAD does and the significance of the configuration steps.

These samples are built on Node.JS, Express, and Microsoft Authentication Library for JavaScript (msal.js).

Features

Integrating data from online service providers increases the value and adoption of your add-ins. This code sample shows you how to connect your add-in to Microsoft Graph. Use this code sample to:

  • Build an Add-in using Node.js, Express, msal.js, and Office.js.
  • Connect to Microsoft Graph from an Office Add-in.
  • Use the OneDrive REST APIs from Microsoft Graph.
  • Use the Express routes and middleware to implement the OAuth 2.0 authorization framework in an add-in.
  • See how to use the Single Sign-on (SSO) API.
  • See how an add-in can fall back to an interactive sign-in in scenarios where SSO is not available.
  • Use the msal.js library to implement a fallback authentication/authorization system that is invoked when Office SSO is not available.
  • Show a dialog using the Office UI namespace when Office SSO is not available.
  • Use add-in commands in an add-in.

Applies to

  • Excel on Windows (subscription)
  • PowerPoint on Windows (subscription)
  • Word on Windows (subscription)

Prerequisites

To run this code sample, the following are required.

  • A code editor. We recommend Visual Studio Code which was used to create the sample.
  • A Microsoft 365 account which you can get by joining the Microsoft 365 Developer Program that includes a free 1 year subscription to Microsoft 365. During the preview phase, the SSO requires Microsoft 365 (which includes the subscription version of Office). You should use the latest monthly version and build from the Insiders channel. You need to be an Office Insider to get this version. For more information, see Be an Office Insider.

    Note: When a build graduates to the production semi-annual channel, support for preview features, including SSO, is turned off for that build.

  • At least a few files and folders stored on OneDrive for Business in your Microsoft 365 subscription.
  • A Microsoft Azure Tenant. This add-in requires Azure Active Directory (AD). Azure AD provides identity services that applications use for authentication and authorization. A trial subscription can be acquired here: Microsoft Azure.

Solution

Solution Author(s)
Office Add-in Microsoft Graph ASP.NET Microsoft

Version history

Version Date Comments
1.0 May 10, 2017 Initial release
1.0 September 15, 2017 Added support for 2FA.
1.0 December 8, 2017 Added extensive error handling.
1.0 January 7, 2019 Added information about web application security practices.
2.0 October 26, 2019 Changed to use new API and added Display Dialog API fallback.
2.1 August 11, 2020 Removed preview note because the API has released.

Disclaimer

THIS CODE IS PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.


To use the project

Please go to the README in the Complete or SSOAutoSetup folder for the next steps.

Security note

These samples send a hardcoded query parameter on the URL for the Microsoft Graph REST API. If you modify this code in a production add-in and any part of query parameter comes from user input, be sure that it is sanitized so that it cannot be used in a Response header injection attack.

Questions and comments

We'd love to get your feedback about this sample. You can send your feedback to us in the Issues section of this repository. Questions about developing Office Add-ins should be posted to Stack Overflow. Ensure your questions are tagged with [office-js] and [MicrosoftGraph].

Join the Microsoft 365 Developer Program

Get a free sandbox, tools, and other resources you need to build solutions for the Microsoft 365 platform.

Additional resources

Copyright

Copyright (c) 2019 Microsoft Corporation. All rights reserved.

This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

office-add-in-nodejs-sso's People

Contributors

alexjerabek avatar ardabeyazoglu avatar davidchesnut avatar dependabot[bot] avatar elizabethsamuel-msft avatar lauragra avatar lindalu-msft avatar microsoftopensource avatar msftgits avatar o365devx avatar rick-kirkham avatar saskodh avatar supernova-eng avatar tcourtneyowen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

office-add-in-nodejs-sso's Issues

getAccessTokenAsync give me 5001 error

Hi,
I follow all the steps given in the example and then when I try to run the add-in in power-point on-line Build:16.0.8812.5630. I got the next error:

error-2017-11-15 10-12-01

Code:5001
Message: An internal error has occurred
name: Internal Error

Any ideas what this is happening? Can I use the SSO in this build version?

Thanks for your help.

Office Online SSO

Hi, I'm successfully running the completed project locally in Excel on Windows. By following the guide carefully I understood that the SSO should work also on Excel Online. However when I try to run in it there I get the following error:
Office Online SSO Error
I can't figure it out what is exactly the problem and where these reply urls can be configured.
I'm developing an add-in locally and I would like to be able to run it on Excel Online since it would be easier for debugging.

getAccessTokenAsync give me 5013 error in Windows 10

Hey there I used this repository to better understand how to set up SSO for a Excel application and I am running across a strange issue.

I got this project working locally on my Mac and then pushed the code for the server and the client side add in to a cloud platform. Then I modified the manifest file to point to the application I have running in the cloud.

With the modified manifest file on my mac everything works fine. I am connecting to this application I have running the cloud and I am able to successfully login via SSO in Excel.

But this is the strange part, when I copied the manifest file that is pointing to my cloud app to a Windows 10 computer and side loaded the manifest file it give me an error when I call getAccessTokenAsync. This is what the result object looks like when I am running the add in on my Windows 10 machine.

{
  "status":"failed",
  "error":{
    "name":"API Call Failed",
    "message":"Invalid input arguments.",
    "code":5013
  }
} 

Since this app is running the cloud I am passing the same input arguments on both the Mac and Windows version (({forceConsent: false}, callback)). I am not sure why it would work on my Mac but not on my Windows 10 machine. I also can't seem to find what exactly this error code is supposed to mean.

Do you know if I need to add something special to the manifest file for the Windows 10 configuration?

OfficeRuntime.auth.getAccessToken() always return 13007 error code in a particular tenant

I've done this nodejs SSO setup in multiple tenants and never had this problem before. With the same setup, this particular office 365 tenant across all users with different access level can't seem to get the bootstrap token from OfficeRuntime.

Expected Behavior

OfficeRuntime.auth.getAccessToken() should provide add-in with bootstrap token that can be exchanged using on-behalf-of flow to get graph token.

Current Behavior

OfficeRuntime.auth.getAccessToken() returns 13007 error instead

Steps to Reproduce, or Live Example

Follow setup guide to create app registration and set it up with the "Complete" version of the demo app.
Make sure all permissions are already consented by user before running the add-in
Then put a breakpoint after OfficeRuntime.auth.getAccessToken()

Context

I can't get graph token to let the add-in getting information from graph API. This add-in becomes non-functional.

Your Environment

  • Platform [PC desktop, Mac, iOS, Office Online]: Office Online
  • Host [Excel, Word, PowerPoint, etc.]: Word
  • Office version number: not sure how to find out
  • Operating System: Windows 10 Pro
  • Browser (if using Office Online): Chrome/Edge Chromium

Useful logs

I notice in this particular tenant. Every time OfficeRuntime.auth.getAccessToken() is executed, the log on the word online window display this error log:

authorize:82 
Unsafe JavaScript attempt to initiate navigation for frame with origin 'https://<tenant>-my.sharepoint.com' from frame with URL 
'https://login.microsoftonline.com/<tenant-id>/oauth2/authorize?response_type=token&client_id=<app-id>&resource=api%3A%2F%2F<add-in-domain>%2F<id>&redirect_uri=https%3A%2F%2F<tenant>-my.sharepoint.com%2F_forms%2Fsinglesignon.aspx&state=<id>%7Capi%3A%2F%2F<add-in-domain>%2F<id>&client-request-id=<id>&x-client-SKU=Js&x-client-Ver=1.0.16&prompt=none&login_hint=<user>%40<tenant>.<domain>&domain_hint=<tenant>.<domain>'. 
The frame attempting navigation of the top-level window is sandboxed, but the flag of 'allow-top-navigation' or 
'allow-top-navigation-by-user-activation' is not set.

I've read this from microsoft documentation (https://docs.microsoft.com/en-us/office/dev/add-ins/develop/troubleshoot-sso-in-office-add-ins):
I can confirm that openid and profile permissions have already been added and granted, so that can't be the issue.
image
another question that might help me identify the issue is "How do i check if the logged in user has a Microsoft Account (MSA) identity?"

And if they do, does that mean these set of users cannot use the SSO until SSO is not a preview feature anymore?

Get file from Sharepoint

I use this for a Word Add-in and getting Data from graph works fine. But i also try to get a file from SharePoint but get an Unauthorized because the Token is valid for Graph and not for my SharePoint site.

do you have a tipp or idea, how i get the right Token for Sharepoint? i tried to get the token with auth.acquireTokenOnBehalfOf(jwt, ['Files.Read.All'], 'myTenant.sharepoint.com'); but it doesnt work.

Thank you
Dominik

@Rick-Kirkham @ardabeyazoglu

Add-in is not sideloading in outlook when uploaded as custom add-in

I followed all the steps specified here to test SSO for outlook in local. I uploaded manifest file(attached below) as custom add-in, but when I close the store popup, it not showing up beside store icon.

Current outlook version is: Outlook 2016 version 1803 (16.0.9126.2295)

And here is manifest file:
manifest.txt

I am not sure what I am doing wrong, please help me with this.

Does SSO work on Desktop clients?

Is this supposed to work on desktop clients? I read that getAccessToken is in preview mode for desktop clients. Am I missing some updates to the api? I am building for Outlook

No access_token response

Hi
I lunched complete sample but when my code ran to exchangeForToken in auth.ts and res.json() the values return only { refresh_token: 'xxx', id_token: 'xxx' } no access_token, then i got undefined and can't complete sample.

What is i missed ?

Thank you for your help.

{name : "Internal Error", message : "An internal error has occurred.", code : 5001} When using getAccessTokenAsync

Hello,

I have an error when using getTokenAsync in my Addin for outlook (angular 1.5 + nodejs):
{name : "Internal Error",
message : "An internal error has occurred.",
code : 5001}

I tried a lot of things to get rid of this error but nothing is working.

It was working before, never had this error, I didn't touch the code for 2 months and when I get back I have this.

Thank you in advance for your answer.

Aurélien

UnauthorizedError: Unable to verify JWT.jwt expired

Hi I followed the instructions online uploaded the xml on office online however when i click the get one drive files button nothing comes out and i get this error from the console. Please help thank you

Office.context.auth undefined

I am creating a POC for Outlook add-in SSO. I have followed the complete article and testing the solution but getting basic errors. Not sure if I am doing anything wrong.

Office.context.auth.getAccessTokenAsync({forceConsent: false}, function (result) { if (result.status === "succeeded") { accessToken = result.value; getData("/api/values", accessToken); } else { console.log("Code: " + result.error.code); console.log("Message: " + result.error.message); console.log("name: " + result.error.name); document.getElementById("getGraphAccessTokenButton").disabled = true; } });

I was debugging above block of code and getting Office.context.auth is undefined.

Thanks in advance for your help.

Office.context.auth sometimes undefined

Hi,

i wrote an Office-Add-in for Word and use SSO. Sometimes my api calls work fine but most time the Office.context.auth is undefined so i can´t call getAccessTokenAsync.

tried to call it later with a btn click or with Office.onReady().then(() => {...}) but it doesn´t help.

I use Office 365 ProPlus.
Word Version is 1812

jwt issuer invalid. expected: https://login.microsoftonline.com/******/v2.0

Hi,

When I tried to run nodejs-sso example, everything works fine until const {jwt} = auth.verifyJWT(req, {scp: 'access_as_user'}); throws the error jwt issuer invalid. expected: https://login.microsoftonline.com/*****/v2.0. When I checked the expected url and the issuer i placed in the code, they are exactly the same. However, when i decode jwt token i see that iss claim is different than this.

Why do i get a jwt token with a different iss claim ?

NOTE: The iss claim in the decoded token is "https://login.microsoftonline.com/a2b0309e-37c1-486d-bdbd-4d91b7d25cd5/v2.0".

Error 13006 : An unexpected error occurred in the client.

Hi,
Thank you for this sample :)
I launched the completed version but I have an error in the console when trying to get the OneDrive files :
Error 13006 : An unexpected error occurred in the client. Error occurred in the authentication request from Office.
I tried on Windows Excel and online Excel.
I changed nothing except the application id in the manifest.

Thank you for your help

package and deploy word addin in sharepoint catalog

Hi,

I am newly developing word addin using yo generator and I created a sample task pane javascript addin and it is running absolutely fine when I am starting the node.js server. My query is how can I consume the word addin in word online without starting the server. Can I put the package somewhere in SharePoint site and making a CDN for that. I have no idea how to package resouces. I know we can put the manifest in app catalog for SharePoint online but not sure about how the js files and other files can be packaged and placed.

Can you please guide me on this if you have idea on this.

Thanks,
Himanjan

Nodemon runs in endless loop

I completed all the steps. But the "tsc-w": "tsc -p tsconfig.json --watch" command fails with -p flag is included.
Once I get past that step removing -p flag, npm run start results in endless loop.
image

The scope is not valid

Hi,

I followed the tutorial with the code in this repo to create a simple office365 word addin, and only changed the ids, secrets etc. however it doesn't work when it attempts to get an access token to retrive drive files.

Here is the url (decoded) of the token request when i check in network:
https://login.live.com/oauth20_authorize.srf?client_id=00000000481710A4&response_type=token&redirect_uri=https://p.sfx.ms/sa.html&state={"client_id":"00000000481710A4","network":"windows","display":"none","callback":"_hellojs_bd2pxupx","state":"","redirect_uri":"https://p.sfx.ms/sa.html","scope":"api://localhost:3000/dad7312f-6ccd-4026-8a80-86441223c790/access_as_user"}&scope=api://localhost:3000/dad7312f-6ccd-4026-8a80-86441223c790/access_as_user

The response says The+provided+value+for+the+input+parameter+'scope'+is+not+valid.+The+scope+'api://localhost:3000/dad7312f-6ccd-4026-8a80-86441223c790/access_as_user'+does+not+exist.`

The app id and resource url are already taken from application config page in developer portal, so they are correct. However, I dont know where the client_id in the url above is coming from.

getAccessTokenAsync - Token lacks signature part and can't be decoded

I'm creating an outlook add-in, and trying to create SSO access. I am getting the app-token, via office.context.auth.getaccesstokenasync and pushing it to a expressjs middleware component, just like in this example here in the repository. Decoding in the auth.ts fails. After having a look at the token itself, it seems invalid as it is one ,-section short.

It works flawlessly in our own tenant (using Addin in Outlook on Win 10):
screenshot_1

The token is incomplete in our customers tenant with the same configuration:
screenshot_2

Any hint where to look here?

Token version mis match with new App Registration (Preview)

For this sample I had registered my App in apps.dev.microsoft.com, the getAccessTokenAsync() method returns v2.0 token. Using this token I was able to get graph v2.0 token everything works fine.

When I registered the app under the Azure Portal -> App Registration (Preview), the getAccessTokenAsync() method returns the v1.0 token. So, JWT token validation fails and I am unable to get the graph token.

I would like to know is this going to be v1.0 token in future or is this bug in preview?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.