The original article are published here:
https://docs.microsoft.com/en-us/graph/tutorials/angular
https://docs.microsoft.com/en-us/graph/tutorials/react
to make it work with my own web api, I have to make considerable adjustment:
in the react version, there is a need to give the tenant specific authority URL.
class App extends Component {
constructor(props) {
super(props);
this.userAgentApplication = new UserAgentApplication(config.appId,
"https://login.microsoftonline.com/{tentan}", null);
this is how we call the web api:
async componentDidMount() {
try {
// Get the user's access token
var accessToken =
await window.
msal.
acquireTokenSilent(
config.
scopes2);
var timesheets = await api.get(accessToken);
// Update the array of events in state
this.setState({timesheets: timesheets});
The angular version:
export class TimesheetService {
accessToken: string;
constructor(private authService: AuthService,
private alertsService: AlertsService,
private http: HttpClient
) {
//move the following two line to login method within authService and save token in cache.
//this.authService.getAccessToken(OAuthSettings.scopes2).then(data => {
//this.accessToken = data;
this.accessToken = sessionStorage.getItem('access_token');
});
}
getTimeSheets():Observable<TimeSheet[]> {
var header = {headers: new HttpHeaders()
.set('Authorization', 'Bearer ' + this.accessToken)
}
return this.http.get<Array<TimeSheet>>('https://localhost:44301/api/TimeSheets?WeekEnding=2018-10-01',header);
}
export class TimesheetComponent implements OnInit {
private timesheets: TimeSheet[];
constructor(private timesheetService: TimesheetService) { }
ngOnInit() {
this.getTimeSheets();
}
getTimeSheets() {
this.timesheetService.getTimeSheets().subscribe(data => {
this.timesheets = data;
});
}
Most importantly , you need to specific the scope for the web api when acquiring the token, a sample config is as below:
export const OAuthSettings = {
appId: 'xxxxx-xxxx-4edxxxx9-xxxx-xxxxxx',
scopes: [
"user.read",
"calendars.read"
],
scopes2: [
"https://{tenant}}.onmicrosoft.com/webapi/access_as_user"
]
};
Finally you also need to sort out CORS issue.