如何通過AzureAD平台提供的授權方式訪問sharepoint online
- 2020 年 6 月 8 日
- 筆記
官方文檔:
1.//docs.microsoft.com/zh-cn/previous-versions/azure/dn645543(v=azure.100)?redirectedfrom=MSDN
2.//docs.microsoft.com/zh-cn/previous-versions/azure/dn645545%28v%3dazure.100%29
AzureAD的簡單介紹:Azure Active Directory(Azure AD)使用OAuth 2.0使您能夠授權對Azure AD租戶中的Web應用程式和Web API的訪問。 OAuth 2.0的Azure AD實施符合OAuth 2.0 RFC 6749,並已擴展為保護第三方Web API。此設計使您可以將AAD用作開發的Web應用程式和Web API的完整安全平台。
上個本篇要用到的圖:
在開始之前需要擁有一個AzureAD,我申請的是Office365的開發者帳號,其中包括Sharepoint online和AzureAD的訂閱。在AzureAD上註冊一個客戶端app,按上文提到的我們通過這個app來訪問SharePoint online。
1.首先我們進入AzureAD註冊一個app
2.填入name,選擇app的訪問賬戶類型和app類型。我們用戶選擇第三種,app選擇web ,以及一個訪問時返回的url。
3.這是創建之後的app基礎資訊(很重要的資訊)。
通過上面的步驟,我們成功註冊了一個應用程式。
之後我們通過使用用戶名密碼或者用戶名證書這兩種方式來獲取Token。
1.在上面步驟我們只是申請了一個app,接下來需要一個密碼(密碼需要保存,創建之後會隱藏)。申請步驟如下
條件滿足上程式碼,token即在AuthenticationResult對象中:
1 public async static Task<AuthenticationResult> AcquireTokenAsync(string resource, string tenantId,string clientId,string clientSecret) 2 { 3 if(string.IsNullOrEmpty(resource) || string.IsNullOrEmpty(tenantId) || string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret)) 4 { 5 throw new Exception("The parameters can not be null or empty"); 6 } 7 AuthenticationContext authenticationContext = new AuthenticationContext($"//login.microsoftonline.com/{tenantId}"); 8 ClientCredential clientCredential = new ClientCredential(clientId, clientSecret); 9 AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(resource, clientCredential); 10 return authenticationResult; 11 }
2.第二種方式是通過證書的方式獲取token,首先準備證書,先自製一個安裝在本地。
打開mmc,證書位置
接著我們導出一個cer證書和一個帶密碼的pfx證書。接下來我們要用到powershell來生成證書憑證,紅框中是我們需要更新到AzureAD上的。
下載app manifest將拷貝的keyCredentials內容複製進去再重新上傳(或者通過powershell的方式實現更新不需要下載再上傳)。
更新之後如下:
最後的一步,需要給這個app賦予許可權,按自己需求分配:
另外需要獲取租戶管理員的承認
條件滿足上程式碼:
1 public async static Task<AuthenticationResult> AcquireTokenAsync(string resource, string tenantId,string clientId,string certficatePath,string certificatePassword) 2 { 3 if (string.IsNullOrEmpty(resource) || string.IsNullOrEmpty(tenantId) || string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(certficatePath)) 4 { 5 throw new Exception("The parameters can not be null or empty"); 6 } 7 X509Certificate2 certificate = new X509Certificate2(certficatePath, certificatePassword, X509KeyStorageFlags.MachineKeySet); 8 string authority = $"//login.windows.net/{tenantId}"; 9 AuthenticationContext authenticationContext = new AuthenticationContext(authority, false); 10 ClientAssertionCertificate cac = new ClientAssertionCertificate(clientId, certificate); 11 AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(resource, cac); 12 return authenticationResult; 13 }
AzureAD提供了如下多種方法去獲取token,上面只是簡單測試了其中的兩種,原理大致相同。token獲取的步驟是通用的,不僅僅是SharePoint online,也可以是office365下的各個產品或者任何一個應用程式或者一個api,都它可以通過AzureAD來管理授權。