generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 2
/
authProvider.ts
199 lines (168 loc) · 7.34 KB
/
authProvider.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import { ClientApplication } from "@azure/msal-node";
//import { FilePersistenceWithDataProtection, DataProtectionScope } from "@azure/msal-node-extensions";
import { requestConfig, ewsRequestConfig } from 'authConfig'
import { shell } from "electron";
import { PublicClientApplication } from '@azure/msal-node';
import { AuthenticationProvider } from '@microsoft/microsoft-graph-client';
import { CryptoProvider } from '@azure/msal-node';
import { AuthorizationCodeRequest } from '@azure/msal-node';
import { SilentFlowRequest } from "@azure/msal-node";
import { AuthenticationResult } from "@azure/msal-node";
import { PkceCodes } from "@azure/msal-common";
import { MSGraphAccount } from "types";
import MSGraphPlugin from "MSGraphPlugin";
import { ConfidentialClientApplication } from "@azure/msal-node";
import { ObsidianTokenCachePlugin } from "ObsidianTokenCachePlugin";
const { safeStorage } = require('@electron/remote')
export const MSAL_ACCESS_TOKEN_LOCALSTORAGE_KEY = 'msal-access_token'
export const MSGRAPH_ACCOUNTS_LOCALSTORAGE_KEY = 'msgraph-accounts'
export class MSALAuthProvider implements AuthenticationProvider {
// todo: somehow persist the tokens
authConfig = {
verifier: "",
challenge: "",
}
msalClient: ClientApplication = null
account: MSGraphAccount = null
cachePlugin: ObsidianTokenCachePlugin
constructor(account: MSGraphAccount) {
this.account = account
this.cachePlugin = new ObsidianTokenCachePlugin(account.displayName)
if (account.clientSecret && account.clientSecret.trim()) {
this.msalClient = new ConfidentialClientApplication({
auth: {
clientId: account.clientId,
clientSecret: account.clientSecret,
authority: account.authority,
},
cache: {
cachePlugin: this.cachePlugin
}
});
} else {
this.msalClient = new PublicClientApplication({
auth: {
clientId: account.clientId,
authority: account.authority,
},
cache: {
cachePlugin: this.cachePlugin
}
});
}
const cryptoProvider = new CryptoProvider();
cryptoProvider.generatePkceCodes()
.then((codes: PkceCodes) => {
this.authConfig.challenge = codes.challenge
this.authConfig.verifier = codes.verifier
})
}
removeAccessToken = async () => {
this.cachePlugin.deleteFromCache()
}
isInitialized = (): boolean => {
return this.cachePlugin.isInitialized()
}
getTokenSilently = async (): Promise<string> => {
// retrieve all cached accounts
const accounts = await this.msalClient.getTokenCache().getAllAccounts();
if (accounts.length > 0) {
// todo: logic to choose the correct account
// for now, just use the first one
const account = accounts[0]
const config = this.account.type == "MSGraph" ? requestConfig : ewsRequestConfig(this.account.baseUri);
const silentRequest: SilentFlowRequest = {
...config.request.silentRequest,
account: account
}
return this.msalClient.acquireTokenSilent(silentRequest)
.then((authResponse: AuthenticationResult) => {
return authResponse.accessToken
})
.then((accessToken: string) => {
console.info("Successfully obtained access token from cache!")
return accessToken
})
.catch((error: unknown) => {
return ""
})
} else {
return ""
}
}
/**
* This method will get called before every request to the msgraph server
* This should return a Promise that resolves to an accessToken (in case of success) or rejects with error (in case of failure)
* Basically this method will contain the implementation for getting and refreshing accessTokens
*/
getAccessToken = async () => {
const access_token = await this.getTokenSilently()
if (access_token !== "") {
return access_token
} else {
msalLogin(this)
let total_waiting_time = 0
const max_waiting_time = 60000 // 1 minute
const ms = 500
while (this.cachePlugin.acquired == false && total_waiting_time <= max_waiting_time) {
await new Promise(resolve => {
setTimeout(resolve, ms)
})
total_waiting_time += ms
}
if (this.cachePlugin.acquired == false) {
console.log("Could not acquire token!")
return ""
} else {
console.info("Successfully logged in!")
return await this.getTokenSilently()
}
}
}
}
export function msalLogin(msalProvider: MSALAuthProvider) {
const pkceCodes = {
challengeMethod: "S256", // Use SHA256 Algorithm
verifier: msalProvider.authConfig.verifier,
challenge: msalProvider.authConfig.challenge
};
const config = msalProvider.account.type == "MSGraph" ? requestConfig : ewsRequestConfig(msalProvider.account.baseUri);
const authCodeUrlParams = {
...config.request.authCodeUrlParameters, // redirectUri, scopes
state: msalProvider.account.displayName,
codeChallenge: pkceCodes.challenge, // PKCE Code Challenge
codeChallengeMethod: pkceCodes.challengeMethod, // PKCE Code Challenge Method
};
msalProvider.msalClient.getAuthCodeUrl(authCodeUrlParams)
.then((response:any) => {
shell.openExternal(response);
})
.catch((error:any) => console.log(JSON.stringify(error)));
}
export function msalRedirect(plugin: MSGraphPlugin, query: any) {
const displayName = query.state;
if (!(displayName in plugin.msalProviders)) {
console.error("Invalid auth request: unknown account!")
return
}
const authProvider = plugin.msalProviders[displayName]
const config = authProvider.account.type == "MSGraph" ? requestConfig : ewsRequestConfig(authProvider.account.baseUri);
// Add PKCE code verifier to token request object
const tokenRequest: AuthorizationCodeRequest = {
...config.request.tokenRequest,
code: query.code as string,
codeVerifier: authProvider.authConfig.verifier, // PKCE Code Verifier
clientInfo: query.client_info as string
};
authProvider.msalClient.acquireTokenByCode(tokenRequest).then((response: AuthenticationResult) => {
authProvider.cachePlugin.acquired = true
}).catch((error: unknown) => {
console.log(error)
authProvider.cachePlugin.acquired = false
})
}
export async function refreshAllTokens(plugin: MSGraphPlugin) {
await Promise.all(Object.values(plugin.msalProviders).map(
async (provider) => {if (provider.account.enabled) provider.getTokenSilently()}
))
}