Merge pull request #420 from PaoloPia/dev

Sample Web Part to consume MS Graph via AAD (tutorial demo)
This commit is contained in:
Paolo Pialorsi 2018-02-19 12:49:05 +01:00 committed by GitHub
commit e704708b02
25 changed files with 752 additions and 0 deletions

View File

@ -0,0 +1,25 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
# change these settings to your own preference
indent_style = space
indent_size = 2
# we recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[{package,bower}.json]
indent_style = space
indent_size = 2

View File

@ -0,0 +1,32 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
solution
temp
*.sppkg
# Coverage directory used by tools like istanbul
coverage
# OSX
.DS_Store
# Visual Studio files
.ntvs_analysis.dat
.vs
bin
obj
# Resx Generated Code
*.resx.ts
# Styles Generated Code
*.scss.ts

View File

@ -0,0 +1,8 @@
{
"@microsoft/generator-sharepoint": {
"version": "1.4.1",
"libraryName": "spfx-api-scopes-tutorial",
"libraryId": "6b58cc7d-badc-4721-bfe2-9e4d91efd07c",
"environment": "spo"
}
}

View File

@ -0,0 +1,69 @@
# Consuming APIs secured with Azure Active Directory within SharePoint Framework
## Summary
This sub folders contains a client-side project that is related to the tutorial available at the following URL: https://docs.microsoft.com/en-us/sharepoint/dev/spfx/use-aad-tutorial
![The UI of the sample application](images/use-aad-tutorial-video.gif)
## Solution
| Solution | Author(s) |
| ------------- | ------------- |
| spfx-api-scopes-tutorial | Paolo Pialorsi (PiaSys.com - @PaoloPia) |
## Version history
| Version | Date | Comments |
| ------------- | ------------- | ------------- |
| 1.0.0 | February 18th 2018 | 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.**
----------
## Build and run the tutorials
To build and run this client-side project, you will need to clone and build the tutorials project.
Clone this repo by executing the following command in your console:
```
git clone https://github.com/SharePoint/sp-dev-fx-webparts.git
```
Navigate to the cloned repo folder which should be the same as the repo name:
```
cd sp-dev-fx-webparts
```
Navigate to the `tutorials` folder:
```
cd tutorials
```
Navigate to the `specific web part` folder:
```
cd 'subfolder'
```
Now run the following command to install the npm packages:
```
npm install
```
This will install the required npm packages and depedencies to build and run the client-side project.
Once the npm packages are installed, run the command to preview your web parts in SharePoint Workbench:
```
gulp serve
```
<img src="https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/tutorials" />

View File

@ -0,0 +1,18 @@
{
"$schema": "https://dev.office.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"graph-consumer-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/graphConsumer/GraphConsumerWebPart.js",
"manifest": "./src/webparts/graphConsumer/GraphConsumerWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"GraphConsumerWebPartStrings": "lib/webparts/graphConsumer/loc/{locale}.js"
}
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://dev.office.com/json-schemas/spfx-build/copy-assets.schema.json",
"deployCdnPath": "temp/deploy"
}

View File

@ -0,0 +1,7 @@
{
"$schema": "https://dev.office.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./temp/deploy/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "spfx-api-scopes-tutorial",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,19 @@
{
"$schema": "https://dev.office.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "spfx-api-scopes-tutorial-client-side-solution",
"id": "6b58cc7d-badc-4721-bfe2-9e4d91efd07c",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"webApiPermissionRequests": [
{
"resource": "Microsoft Graph",
"scope": "User.ReadBasic.All"
}
]
},
"paths": {
"zippedPackage": "solution/spfx-api-scopes-tutorial.sppkg"
}
}

View File

@ -0,0 +1,10 @@
{
"$schema": "https://dev.office.com/json-schemas/core-build/serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://localhost:5432/workbench",
"api": {
"port": 5432,
"entryPath": "node_modules/@microsoft/sp-webpart-workbench/lib/api/"
}
}

View File

@ -0,0 +1,45 @@
{
"$schema": "https://dev.office.com/json-schemas/core-build/tslint.schema.json",
// Display errors as warnings
"displayAsWarning": true,
// The TSLint task may have been configured with several custom lint rules
// before this config file is read (for example lint rules from the tslint-microsoft-contrib
// project). If true, this flag will deactivate any of these rules.
"removeExistingRules": true,
// When true, the TSLint task is configured with some default TSLint "rules.":
"useDefaultConfigAsBase": false,
// Since removeExistingRules=true and useDefaultConfigAsBase=false, there will be no lint rules
// which are active, other than the list of rules below.
"lintConfig": {
// Opt-in to Lint rules which help to eliminate bugs in JavaScript
"rules": {
"class-name": false,
"export-name": false,
"forin": false,
"label-position": false,
"member-access": true,
"no-arg": false,
"no-console": false,
"no-construct": false,
"no-duplicate-case": true,
"no-duplicate-variable": true,
"no-eval": false,
"no-function-expression": true,
"no-internal-module": true,
"no-shadowed-variable": true,
"no-switch-case-fall-through": true,
"no-unnecessary-semicolons": true,
"no-unused-expression": true,
"no-use-before-declare": true,
"no-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"valid-typeof": true,
"variable-name": false,
"whitespace": false
}
}
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://dev.office.com/json-schemas/spfx-build/write-manifests.schema.json",
"cdnBasePath": "<!-- PATH TO CDN -->"
}

View File

@ -0,0 +1,7 @@
'use strict';
const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
build.initialize(gulp);

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

View File

@ -0,0 +1,33 @@
{
"name": "spfx-api-scopes-tutorial",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"react": "15.6.2",
"react-dom": "15.6.2",
"@types/react": "15.6.6",
"@types/react-dom": "15.5.6",
"@microsoft/sp-core-library": "~1.4.1",
"@microsoft/sp-webpart-base": "~1.4.1",
"@microsoft/sp-lodash-subset": "~1.4.1",
"@microsoft/sp-office-ui-fabric-core": "~1.4.1",
"@types/webpack-env": ">=1.12.1 <1.14.0"
},
"devDependencies": {
"@microsoft/sp-build-web": "~1.4.1",
"@microsoft/sp-module-interfaces": "~1.4.1",
"@microsoft/sp-webpart-workbench": "~1.4.1",
"gulp": "~3.9.1",
"@types/chai": ">=3.4.34 <3.6.0",
"@types/mocha": ">=2.2.33 <2.6.0",
"ajv": "~5.2.2"
}
}

View File

@ -0,0 +1,26 @@
{
"$schema": "https://dev.office.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "0c2bdcfd-b8ea-474d-acea-a1c17bff2310",
"alias": "GraphConsumerWebPart",
"componentType": "WebPart",
// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,
// If true, the component can only be installed on sites where Custom Script is allowed.
// Components that allow authors to embed arbitrary script code should set this to true.
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
"requiresCustomScript": false,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
"group": { "default": "Other" },
"title": { "default": "GraphConsumer" },
"description": { "default": "Sample Web Part to show how to consume the Microsoft Graph from SPFx" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "GraphConsumer"
}
}]
}

View File

@ -0,0 +1,62 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneChoiceGroup
} from '@microsoft/sp-webpart-base';
import * as strings from 'GraphConsumerWebPartStrings';
import GraphConsumer from './components/GraphConsumer';
import { IGraphConsumerProps } from './components/IGraphConsumerProps';
import { ClientMode } from './components/ClientMode';
export interface IGraphConsumerWebPartProps {
clientMode: ClientMode;
}
export default class GraphConsumerWebPart extends BaseClientSideWebPart<IGraphConsumerWebPartProps> {
public render(): void {
const element: React.ReactElement<IGraphConsumerProps > = React.createElement(
GraphConsumer,
{
clientMode: this.properties.clientMode,
context: this.context,
}
);
ReactDom.render(element, this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneChoiceGroup('clientMode', {
label: strings.ClientModeLabel,
options: [
{ key: ClientMode.aad, text: "AadHttpClient"},
{ key: ClientMode.graph, text: "MSGraphClient"},
]
}),
]
}
]
}
]
};
}
}

View File

@ -0,0 +1,4 @@
export enum ClientMode {
aad,
graph,
}

View File

@ -0,0 +1,73 @@
@import '~@microsoft/sp-office-ui-fabric-core/dist/sass/SPFabricCore.scss';
.graphConsumer {
.container {
max-width: 700px;
margin: 0px auto;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
.row {
@include ms-Grid-row;
@include ms-fontColor-white;
background-color: $ms-color-themeDark;
padding: 20px;
}
.column {
@include ms-Grid-col;
@include ms-lg10;
@include ms-xl8;
@include ms-xlPush2;
@include ms-lgPush1;
}
.title {
@include ms-font-xl;
@include ms-fontColor-white;
}
.form {
@include ms-font-l;
@include ms-fontColor-white;
}
label {
@include ms-fontColor-white;
}
.button {
// Our button
text-decoration: none;
height: 32px;
// Primary Button
min-width: 80px;
background-color: $ms-color-themePrimary;
border-color: $ms-color-themePrimary;
color: $ms-color-white;
// Basic Button
outline: transparent;
position: relative;
font-family: "Segoe UI WestEuropean","Segoe UI",-apple-system,BlinkMacSystemFont,Roboto,"Helvetica Neue",sans-serif;
-webkit-font-smoothing: antialiased;
font-size: $ms-font-size-m;
font-weight: $ms-font-weight-regular;
border-width: 0;
text-align: center;
cursor: pointer;
display: inline-block;
padding: 0 16px;
.label {
font-weight: $ms-font-weight-semibold;
font-size: $ms-font-size-m;
height: 32px;
line-height: 32px;
margin: 0 4px;
vertical-align: top;
display: inline-block;
}
}
}

View File

@ -0,0 +1,241 @@
import * as React from 'react';
import styles from './GraphConsumer.module.scss';
import * as strings from 'GraphConsumerWebPartStrings';
import { IGraphConsumerProps } from './IGraphConsumerProps';
import { IGraphConsumerState } from './IGraphConsumerState';
import { ClientMode } from './ClientMode';
import { IUserItem } from './IUserItem';
import { escape } from '@microsoft/sp-lodash-subset';
import {
autobind,
PrimaryButton,
TextField,
Label,
DetailsList,
DetailsListLayoutMode,
CheckboxVisibility,
SelectionMode
} from 'office-ui-fabric-react';
import { AadHttpClient } from "@microsoft/sp-http";
import { MSGraphClient } from "@microsoft/sp-client-preview";
// Configure the columns for the DetailsList component
let _usersListColumns = [
{
key: 'displayName',
name: 'Display name',
fieldName: 'displayName',
minWidth: 50,
maxWidth: 100,
isResizable: true
},
{
key: 'mail',
name: 'Mail',
fieldName: 'mail',
minWidth: 50,
maxWidth: 100,
isResizable: true
},
{
key: 'userPrincipalName',
name: 'User Principal Name',
fieldName: 'userPrincipalName',
minWidth: 100,
maxWidth: 200,
isResizable: true
},
];
let _fakeUsers : Array<IUserItem> = [
{ displayName: "User 1", mail: 'mail-user1@domain.com', userPrincipalName: "mail-user1@domain.com" },
{ displayName: "User 2", mail: 'mail-user2@domain.com', userPrincipalName: "mail-user2@domain.com" },
{ displayName: "User 3", mail: 'mail-user3@domain.com', userPrincipalName: "mail-user3@domain.com" },
{ displayName: "User 4", mail: 'mail-user4@domain.com', userPrincipalName: "mail-user4@domain.com" },
];
export default class GraphConsumer extends React.Component<IGraphConsumerProps, IGraphConsumerState> {
constructor(props: IGraphConsumerProps, state: IGraphConsumerState) {
super(props);
// Initialize the state of the component
this.state = {
// users: _fakeUsers,
users: [],
searchFor: ""
};
}
public render(): React.ReactElement<IGraphConsumerProps> {
return (
<div className={ styles.graphConsumer }>
<div className={ styles.container }>
<div className={ styles.row }>
<div className={ styles.column }>
<span className={ styles.title }>Search for a user!</span>
<p className={ styles.form }>
<TextField
label={ strings.SearchFor }
required={ true }
value={ this.state.searchFor }
onChanged={ this._onSearchForChanged }
onGetErrorMessage={ this._getSearchForErrorMessage }
/>
</p>
<p className={ styles.form }>
<PrimaryButton
text='Search'
title='Search'
onClick={ this._search }
/>
</p>
{
(this.state.users != null && this.state.users.length > 0) ?
<p className={ styles.form }>
<DetailsList
items={ this.state.users }
columns={ _usersListColumns }
setKey='set'
checkboxVisibility={ CheckboxVisibility.hidden }
selectionMode={ SelectionMode.none }
layoutMode={ DetailsListLayoutMode.fixedColumns }
compact={ true }
/>
</p>
: null
}
</div>
</div>
</div>
</div>
);
}
@autobind
private _onSearchForChanged(newValue: string): void {
// Update the component state accordingly to the current user's input
this.setState({
searchFor: newValue,
});
}
private _getSearchForErrorMessage(value: string): string {
// The search for text cannot contain spaces
return (value == null || value.length == 0 || value.indexOf(" ") < 0)
? ''
: `${strings.SearchForValidationErrorMessage}`;
}
@autobind
private _search(): void {
console.log(this.props.clientMode);
// Based on the clientMode value search users
switch (this.props.clientMode)
{
case ClientMode.aad:
this._searchWithAad();
break;
case ClientMode.graph:
this._searchWithGraph();
break;
}
}
private _searchWithAad(): void {
// Log the current operation
console.log("Using _searchWithAad() method");
// Using Graph here, but any 1st or 3rd party REST API that requires Azure AD auth can be used here.
const aadClient: AadHttpClient = new AadHttpClient(
this.props.context.serviceScope,
"https://graph.microsoft.com"
);
// Search for the users with givenName, surname, or displayName equal to the searchFor value
aadClient
.get(
`https://graph.microsoft.com/v1.0/users?$select=displayName,mail,userPrincipalName&$filter=(givenName%20eq%20'${escape(this.state.searchFor)}')%20or%20(surname%20eq%20'${escape(this.state.searchFor)}')%20or%20(displayName%20eq%20'${escape(this.state.searchFor)}')`,
AadHttpClient.configurations.v1
)
.then(response => {
return response.json();
})
.then(json => {
// Prepare the output array
var users: Array<IUserItem> = new Array<IUserItem>();
// Log the result in the console for testing purposes
console.log(json);
// Map the JSON response to the output array
json.value.map((item: any) => {
users.push( {
displayName: item.displayName,
mail: item.mail,
userPrincipalName: item.userPrincipalName,
});
});
// Update the component state accordingly to the result
this.setState(
{
users: users,
}
);
})
.catch(error => {
console.error(error);
});
}
private _searchWithGraph(): void {
// Log the current operation
console.log("Using _searchWithGraph() method");
const graphClient: MSGraphClient = this.props.context.serviceScope.consume(
MSGraphClient.serviceKey
);
// From https://github.com/microsoftgraph/msgraph-sdk-javascript sample
graphClient
.api("users")
.version("v1.0")
.select("displayName,mail,userPrincipalName")
.filter(`(givenName eq '${escape(this.state.searchFor)}') or (surname eq '${escape(this.state.searchFor)}') or (displayName eq '${escape(this.state.searchFor)}')`)
.get((err, res) => {
if (err) {
console.error(err);
return;
}
// Prepare the output array
var users: Array<IUserItem> = new Array<IUserItem>();
// Map the JSON response to the output array
res.value.map((item: any) => {
users.push( {
displayName: item.displayName,
mail: item.mail,
userPrincipalName: item.userPrincipalName,
});
});
// Update the component state accordingly to the result
this.setState(
{
users: users,
}
);
});
}
}

View File

@ -0,0 +1,7 @@
import { WebPartContext } from '@microsoft/sp-webpart-base';
import { ClientMode } from './ClientMode';
export interface IGraphConsumerProps {
clientMode: ClientMode;
context: WebPartContext;
}

View File

@ -0,0 +1,6 @@
import { IUserItem } from './IUserItem';
export interface IGraphConsumerState {
users: Array<IUserItem>;
searchFor: string;
}

View File

@ -0,0 +1,6 @@
export interface IUserItem {
displayName: string;
mail: string;
userPrincipalName: string;
}

View File

@ -0,0 +1,9 @@
define([], function() {
return {
"PropertyPaneDescription": "Description",
"BasicGroupName": "Group Name",
"ClientModeLabel": "Client Mode",
"SearchFor": "Search for",
"SearchForValidationErrorMessage": "Invalid value for 'Search for' field"
}
});

View File

@ -0,0 +1,12 @@
declare interface IGraphConsumerWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
ClientModeLabel: string;
SearchFor: string;
SearchForValidationErrorMessage: string;
}
declare module 'GraphConsumerWebPartStrings' {
const strings: IGraphConsumerWebPartStrings;
export = strings;
}

View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "commonjs",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"es6-promise",
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection"
]
}
}