68f7f67761 | ||
---|---|---|
.. | ||
assets | ||
bot | ||
webpart | ||
README.md |
README.md
SharePoint web part sample with SSO
Summary
Web parts is a special kind of SharePoint controls that can be supported by the Bot Framework. This sample will show you how to embed a Bot Framework bot into a SharePoint web site with SSO.
There are two parts included in this sample:
- A login bot sample
- A web parts sample
The web parts embeds the login bot by using a webchat. As the user has already login in the SharePoint website, we could use SSO to authorize the bot. This sample shows how to do this including:
- Detect and intercept OAuth process.
- Use SharePoint library to get the exchange token and send it back to the bot.
This demo does not include any threat models and is designed for educational purposes only. When you design a production system, threat-modelling is an important task to make sure your system is secure and provide a way to quickly identify potential source of data breaches. IETF RFC 6819 and OAuth 2.0 for Browser-Based Apps is a good starting point for threat-modelling when using OAuth 2.0.
Used SharePoint Framework Version
Applies to
Prerequisites
-
Node.js version 10.19 (Node.js v9.x, v11.x, and v12.x are not currently supported with SharePoint Framework development)
# determine node version node --version
-
python version 2.7
# determine python version python --version
Solution
Solution | Author(s) |
---|---|
web part | Bot Framework Discussions (msbots@service.microsoft.com) Stephan Bisser (@stephanbisser, bisser.io) |
bot | Bot Framework Discussions (msbots@service.microsoft.com) |
Version history
Version | Date | Comments |
---|---|---|
1.0 | Nov 10, 2020 | Initial release |
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.
Minimal Path to Awesome
Enlist
-
Clone the repository
git clone https://github.com/pnp/sp-dev-fx-webparts.git
Setup bot with Direct Line
-
In a terminal, navigate to
sp-dev-fx-webparts
cd sp-dev-fx-webparts
-
Navigate to the folder for this solution:
cd samples cd react-bot-framework-sso
-
Install modules
npm install
-
Register connections. You can get it done by deploy your bot to Azure. Save your bot service endpoint like: "https://YOUR_BOT.azurewebsites.net". Save your AAD Id as
YOUR_APP_ID
, AAD Name asYOUR_APP_Name
and secret asYOUR_APP_PSW
also. -
Connect to direct line, copy one of the Secret Key values as YOUR_DIRECT_LINE_SECRET and store this for later. This is your ‘Direct Line Secret’.
-
Add
DirectLineSecret
to an.env
config file under./bot
MicrosoftAppId=YOUR_APP_ID MicrosoftAppPassword=YOUR_APP_PSW DirectLineSecret=YOUR_DIRECT_LINE_SECRET
Setup OAuth via Azure Active Directory for the Bot
Check here for more information about getting an AADv2 application setup for use in Azure Bot Service.
- Go to your Azure Active Directory
- Open your bot's application registration
- Save the tenant ID
- Select the "Overview" blade
- On the main pane, copy the content of "Directory (tenant) ID" as
YOUR_APP_TENANT
and store this for later
- Update Authentication
- Select the "Authentication" blade
- Click "Add a platform" to add web if Web is not added
- In "Redirect URIs" section, add a new entry
https://token.botframework.com/.auth/web/redirect
- Update App Registration Manifest
- Select the "Manifest" blade
- Set
accessTokenAcceptedVersion
to2
- Set
- Select the "Manifest" blade
- Add a scope
- Select the "Expose an API" blade
- Click the "Add a scope" button under "Scopes defined by this API"
- Click "Save and continue"
- Add a scope named
YOUR_AAD_SCOPE_NAME
- Set "Who can consent?" to "Admins and users"
- Add an admin consent display name
- Add an admin consent description
- Click "Add scope"
- Save the Scope URL to configure authentication for the bot in the Bot Registration in the next section
- api://123a45b6-789c-01de-f23g-h4ij5k67a8bc/<YOUR_AAD_SCOPE_NAME>
- Select API permissions
- Click "API Permissions", select"Add a permission"
- Select "My APIs",
YOUR_APP_ID
, and enableYOUR_AAD_SCOPE_NAME
scope\
Otherwise the non-admin user cannot use SSO.
Setup Authentication via Azure Bot Services for the Bot
Check the Add authentication to your bot via Azure Bot Service article for more information about adding authentication to your bot.
- Add OAuth Connection for the bot to the Bot Channel Registration
- In the Bot Channel Registration open the settings blade
- Under "OAuth Connection Settings" click the "Add Setting" button
- Add new Connection Setting
- Set the connection "Name"
- Set the "Service Provider" to "Azure Active Directory 2"
- Add the Client ID as
YOUR_APP_ID
, Client secret asYOUR_APP_PSW
, and Tenant ID asYOUR_APP_TENANT
- Set the "Token Exchange URL" to the scope URL that was created in the previous section
- api://123a45b6-789c-01de-f23g-h4ij5k67a8bc/<YOUR_AAD_SCOPE_NAME>
- Set the "Scopes" field to the scopes you want the bot to have permission to access (ie.
user.read
)
- Add new Connection Setting
Republish bot
-
Update
.env
withConnectionName
to.env
config file under./bot
ConnectionName=YOUR_CONNECTION_NAME
-
Republish your bot with new config or restart it in local use:
npm start
Setup web parts
-
Edit
BotSignInToast.tsx
to set your AAD scope uri(scopeUri
) withapi://YOUR_APP_ID
directly likeapi://123a45b6-789c-01de-f23g-h4ij5k67a8bc
:return tokenProvider.getToken(scopeUri, true).then((token: string) => {
-
Add the following config to
./config/package-solution.json
:"webApiPermissionRequests": [ + { + "resource": "<YOUR_APP_Name>", + "scope": "<YOUR_AAD_SCOPE_NAME>" + } ],
-
Install modules
cd ../webpart npm install
-
Publish and host webpart, prepare for approving permissions
-
Refer Connect to Azure AD-secured APIs to publish and approve permissions from admin site
- Please ensure your service principal had been enabled for your AAD account.
- Check "Managed application in local directory" in your AAD overview blade in Azure Portal
- Go to SharePoint admin center
- Find "API Access", approve "<YOUR_APP_Name>"
- Please ensure your service principal had been enabled for your AAD account.
-
(Opt. for hosted bot service) Config CORS
CORS must be set on bot app service to enable SharePoint client to get resource from bot service. Follow these steps to add your workbench to bot app service CORS configuration:- Go to your azure portal
- Navigate to your bot app service, search for CORS settings
- Add https://localhost:4321 and https://<YOUR_SITE>.sharepoint.com to CORS origins
Setup OAuth via Azure Active Directory for the SharePoint
The following operations will need an admin account.
- Go to your Azure Active Directory
- Open "App registrations", find "SharePoint Online Client Extensibility Web Application Principal"
- Save the client ID
- Select the "Overview" blade
- On the main pane, copy the content of "Application ID" as YOUR_SHAREPOINT_ID and store this for later usage
- Update App Registration Manifest
- Select the "Manifest" blade
- Set
accessTokenAcceptedVersion
to2
- Set
- Select the "Manifest" blade
Add a client application to the OAuth for the Bot
- Open your bot's application registration
- Select the "Expose an API" blade
- Click the "Add a client application" under "Authorized client applications"
- Set the client id to the
YOUR_SHAREPOINT_ID
- Check the box next to the scope we added in the previous step under "Authorized scopes"
- Click "Add application"
- Set the client id to the
Test web parts
-
Go to
webpart
folder, in the command line rungulp serve
Now web parts is running locally.
-
Open online test page with user account: https://<YOUR_SITE>.sharepoint.com/_layouts/15/Workbench.aspx
-
Config bot endpoint
Add the web parts, set bot endpoint to https://YOUR_BOT.azurewebsites.net, refresh this page, then you can successfully connect bot with SharePoint.
Features
Web Chat integration with SSO
First a store is used to intercept activities with OAuth card. When the client receives an OAuth request, the client will ask the user if it should use SSO to login instead.
const store = useMemo(
() =>
createStore({}, ({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY' && action.payload.activity.from.role === 'bot') {
const activity =
(action.payload.activity.attachments || []).find(
({ contentType }) => contentType === 'application/vnd.microsoft.card.oauth'
) || {};
const { content } = activity;
if (content) {
const { tokenExchangeResource } = content;
const { uri } = tokenExchangeResource;
if (uri) {
dispatch({
type: 'WEB_CHAT/SET_NOTIFICATION',
payload: {
data: { content },
id: 'signin',
level: 'info',
message: 'Please sign in to the app.'
}
});
return false;
}
}
}
return next(action);
}),
[]
);
Web Chat could use toast for custom prompts:
const toastMiddleware = () => next => ({ notification, ...otherArgs }) => {
const { id } = notification;
if (id === 'signin') {
return <BotSignInToast notification={notification} context={props.context}/>;
}
else if (id === 'traditionalbotauthentication') {
return <TraditionalBotAuthenticationToast notification={notification} />;
}
return next({ notification, ...otherArgs });
};
In the toast, aadTokenProvider
is used to get the required token for exchange. If succeed, send an invoke activity back for authentication:
context.aadTokenProviderFactory.getTokenProvider().then((tokenProvider: AadTokenProvider) => {
return tokenProvider.getToken('api://123a45b6-789c-01de-f23g-h4ij5k67a8bc/scope', true).then((token: string) => {
const { connectionName, tokenExchangeResource } = content;
const { tokenId } = tokenExchangeResource;
if (token) {
postActivity({
channelData: { invokeId },
type: 'invoke',
name: 'signin/tokenExchange',
value: {
id: tokenId,
connectionName,
token,
},
});
}
});
});
If the SSO approach failed, fallback to traditional sign in link:
const handleClick = useCallback(() => {
dismissNotification(id);
performCardAction(signin);
}, [dismissNotification, id, performCardAction, signin]);
Note: The first time users try SSO, users may be presented with an OAuth card to log in. This is because users have not yet given consent to the bot's Azure AD app. To avoid this, users can grant admin consent for any graph permissions requested by the Azure AD app.
Note: due to a SDK bug, the consent card could not be shown properly yet. Granting admin consent may be necessary to workaround this.