14 KiB
Sharepoint webpart 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) |
---|---|
webpart | STCA BF Channel and ABS (stcabfchannel@microsoft.com) Stephan Bisser (@stephanbisser, bisser.io) |
bot | STCA BF Channel and ABS (stcabfchannel@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 [Placeholder]
Setup bot with Direct Line
-
In a terminal, navigate to
[Placeholder]
cd [Placeholder]
-
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 as YOUR_APP_Name and secret as YOUR_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 ‘Direct Line Secret’ 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 enable YOUR_AAD_SCOPE_NAME scope
Otherwise the non-admin user cannot use SSO.
Setup Authentication via Azure Bot Services for the Bot
Check here 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 as YOUR_APP_PSW, and Tenant ID as YOUR_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
with ConnectionName to .env config file under ./botConnectionName=YOUR_CONNECTION_NAME
-
Republish your bot with new config or restart it in local use:
npm start
Setup web parts
-
Edit "BotSignInToast.tsx" file 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>" + } ],
-
Publish and host webpart, prepare for approving permissions
-
Refer Connect to Azure AD-secured APIs to publish and approve permissions from admin site
- Go to sharepoint admin center
- Find "API Access", approve "<YOUR_APP_Name>"
-
(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 configration:- 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
-
In the command line run
cd ../webpart npm install gulp 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 connet bot with SharePoint.
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"
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 here, the consent card could not be shown properly yet. Granting admin consent may be necessary to workaround this.