OAuth2身份验证用于使用Aspose连接到EWS服务器的身份验证不起作用
我是C#开发和学习阶段的新手。 我目前正在努力将EWS身份验证从基本身份验证升级到OAuth身份验证。 但是,以下是我的代码
using JsonConvert = Newtonsoft.Json.JsonConvert;
using Aspose.Email.Clients;
using Aspose.Email.Common.Utils;
using Aspose.Email.Tests.TestUtils;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Text;
namespace TestNS
{
/// <summary>
/// Azure resource owner password credential (ROPC) token provider
/// https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc
/// https://portal.azure.com
/// https://developer.microsoft.com/en-us/graph/graph-explorer/#
/// token parser https://jwt.io
/// </summary>
internal class AzureROPCTokenProvider : ITokenProvider
{
private const string uriFormat = "https://login.microsoftonline.com/{0}/oauth2/v2.0/token";
private const string bodyFormat =
"client_id={0}" +
"&scope={1}" +
"&username={2}" +
"&password={3}" +
"&grant_type={4}";
private readonly string scope;
private const string grant_type = "password";
private readonly object tokenSyncObj = new object();
private OAuthToken token;
private readonly string tenant;
private readonly string clientId;
private readonly string clientSecret;
private readonly string userName;
private readonly string password;
/// <summary>
/// Initializes a new instance of the <see cref="AzureROPCTokenProvider"/> class
/// </summary>
/// <param name="tenant"></param>
/// <param name="clientId"></param>
/// <param name="clientSecret"></param>
/// <param name="scope"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <param name="scopeAr"></param>
public AzureROPCTokenProvider(
string tenant,
string clientId,
string clientSecret,
string userName,
string password,
string[] scopeAr)
{
this.tenant = tenant;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.userName = userName;
this.password = password;
this.scope = string.Join(" ", scopeAr);
}
/// <summary>
/// Gets oAuth access token.
/// </summary>
/// <param name="ignoreExistingToken">
/// If ignoreExistingToken is true, requests new token from a server. Otherwise behaviour is depended on whether token exists or not.
/// If token exists and its expiration date is not expired returns current token, otherwise requests new token from a server.
/// </param>
/// <returns>Returns oAuth access token</returns>
public virtual OAuthToken GetAccessToken(bool ignoreExistingToken)
{
lock (tokenSyncObj)
{
if (this.token != null && !this.token.Expired && !ignoreExistingToken)
return this.token;
token = null;
string uri = string.Format(uriFormat, string.IsNullOrWhiteSpace(tenant) ? "common" : tenant);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
string body = string.Format(bodyFormat,
HttpUtility.UrlEncode(clientId),
HttpUtility.UrlEncode(scope),
HttpUtility.UrlEncode(userName),
HttpUtility.UrlEncode(password),
HttpUtility.UrlEncode(grant_type));
byte[] bytes = Encoding.ASCII.GetBytes(body);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
MemoryStream ms = new MemoryStream(bytes);
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(bytes, 0, bytes.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StringBuilder responseText = new StringBuilder();
bytes = new byte[1024];
int read = 0;
using (Stream stream = response.GetResponseStream())
{
while ((read = stream.Read(bytes, 0, bytes.Length)) > 0)
responseText.Append(Encoding.ASCII.GetString(bytes, 0, read));
}
string jsonString = responseText.ToString();
AzureTokenResponse t = JsonConvert.DeserializeObject<AzureTokenResponse>(jsonString);
token = new OAuthToken(
t.access_token,
TokenType.AccessToken,
DateTime.Now.AddSeconds(t.expires_in));
return token;
}
}
/// <summary>
/// Gets oAuth access token.
/// If token exists and its expiration date is not expired returns current token, otherwise requests new token from a server.
/// </summary>
/// <returns>Returns oAuth access token</returns>
public OAuthToken GetAccessToken()
{
return GetAccessToken(false);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public virtual void Dispose()
{
}
}
/// <summary>
/// A success response contains a JSON OAuth 2.0 response with the following parameters.
/// </summary>
public class AzureTokenResponse
{
/// <summary>
/// The requested access token. The calling web service can use this token to authenticate to the receiving web service.
/// </summary>
public string access_token { get; set; }
/// <summary>
/// Indicates the token type value. The only type that Azure AD supports is Bearer For more information about bearer tokens,
/// see The OAuth 2.0 Authorization Framework: Bearer Token Usage (RFC 6750).
/// </summary>
public string token_type { get; set; }
/// <summary>
/// How long the access token is valid (in seconds).
/// </summary>
public int expires_in { get; set; }
/// <summary>
/// How long the access token is valid (in seconds).
/// </summary>
public int ext_expires_in { get; set; }
/// <summary>
/// The time when the access token expires.
/// The date is represented as the number of seconds from 1970-01-01T00:00:00Z UTC until the expiration time.
/// This value is used to determine the lifetime of cached tokens.
/// </summary>
public int expires_on { get; set; }
/// <summary>
/// The App ID URI of the receiving web service.
/// </summary>
public string resource { get; set; }
/// <summary>
/// If an access token was returned, this parameter lists the scopes the access token is valid for.
/// </summary>
public string scope { get; set; }
/// <summary>
/// Issued if the original scope parameter included the openid scope.
/// </summary>
public string id_token { get; set; }
/// <summary>
/// Issued if the original scope parameter included offline_access.
/// </summary>
public string refresh_token { get; set; }
}
}
ITokenProvider tokenProvider = new AzureROPCTokenProvider(
"Tenant",
"ClientId",
"ClientSecret",
"EMail",
"Password",
scopes);
const string mailboxUri = "https://outlook.office365.com/ews/exchange.asmx";
ICredentials credentials = new OAuthNetworkCredential(tokenProvider);
using (IEWSClient ewsClient = EWSClient.GetEWSClient(mailboxUri, credentials))
{
}
从而得到错误响应
System.Net.WebException
HResult=0x80131509
Message=The remote server returned an error: (400) Bad Request.
Source=System
StackTrace:
at System.Net.HttpWebRequest.GetResponse()
at DataLoadLibrary.Emai.AzureROPCTokenProvider.GetAccessToken(Boolean ignoreExistingToken) in C:\path\to\file\DataLoadLibrary\Email\AzureROPCTokenProvider .cs:line 97
at DataLoadLibrary.Emai.AzureROPCTokenProvider.GetAccessToken() inC:\path\to\file\DataLoadLibrary\Email\AzureROPCTokenProvider .cs:line 123
at #=zh9Fqfcq_HoOXkObKc3_xqZJZ5tEDCTrUjh8nD$EvlR1sjwBuAg==.GetWebRequest(Uri #=zYomVKA4=)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at #=z59FR9EVW5_PdyTyl2BGNIgxEQwbI$$thui3I5Af7oPUiZ1$E9A==.GetFolder(GetFolderType GetFolder1)
at Aspose.Email.Clients.Exchange.WebService.EWSClient.GetEWSClient(String mailboxUri, ICredentials credentials, WebProxy proxy)
,通过浏览代码,我可以发现它没有使用传递给类的客户端秘密, 。然后,我修改了身体httputitions.urlencode(clientsecret));
。不幸的是我得到了同样的例外
I am very new to C# development and in my learning stage.
I'm currently working on upgrading the EWS Authentication from basic to Oauth authentication.
Following is my code
using JsonConvert = Newtonsoft.Json.JsonConvert;
using Aspose.Email.Clients;
using Aspose.Email.Common.Utils;
using Aspose.Email.Tests.TestUtils;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Text;
namespace TestNS
{
/// <summary>
/// Azure resource owner password credential (ROPC) token provider
/// https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc
/// https://portal.azure.com
/// https://developer.microsoft.com/en-us/graph/graph-explorer/#
/// token parser https://jwt.io
/// </summary>
internal class AzureROPCTokenProvider : ITokenProvider
{
private const string uriFormat = "https://login.microsoftonline.com/{0}/oauth2/v2.0/token";
private const string bodyFormat =
"client_id={0}" +
"&scope={1}" +
"&username={2}" +
"&password={3}" +
"&grant_type={4}";
private readonly string scope;
private const string grant_type = "password";
private readonly object tokenSyncObj = new object();
private OAuthToken token;
private readonly string tenant;
private readonly string clientId;
private readonly string clientSecret;
private readonly string userName;
private readonly string password;
/// <summary>
/// Initializes a new instance of the <see cref="AzureROPCTokenProvider"/> class
/// </summary>
/// <param name="tenant"></param>
/// <param name="clientId"></param>
/// <param name="clientSecret"></param>
/// <param name="scope"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <param name="scopeAr"></param>
public AzureROPCTokenProvider(
string tenant,
string clientId,
string clientSecret,
string userName,
string password,
string[] scopeAr)
{
this.tenant = tenant;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.userName = userName;
this.password = password;
this.scope = string.Join(" ", scopeAr);
}
/// <summary>
/// Gets oAuth access token.
/// </summary>
/// <param name="ignoreExistingToken">
/// If ignoreExistingToken is true, requests new token from a server. Otherwise behaviour is depended on whether token exists or not.
/// If token exists and its expiration date is not expired returns current token, otherwise requests new token from a server.
/// </param>
/// <returns>Returns oAuth access token</returns>
public virtual OAuthToken GetAccessToken(bool ignoreExistingToken)
{
lock (tokenSyncObj)
{
if (this.token != null && !this.token.Expired && !ignoreExistingToken)
return this.token;
token = null;
string uri = string.Format(uriFormat, string.IsNullOrWhiteSpace(tenant) ? "common" : tenant);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
string body = string.Format(bodyFormat,
HttpUtility.UrlEncode(clientId),
HttpUtility.UrlEncode(scope),
HttpUtility.UrlEncode(userName),
HttpUtility.UrlEncode(password),
HttpUtility.UrlEncode(grant_type));
byte[] bytes = Encoding.ASCII.GetBytes(body);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
MemoryStream ms = new MemoryStream(bytes);
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(bytes, 0, bytes.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StringBuilder responseText = new StringBuilder();
bytes = new byte[1024];
int read = 0;
using (Stream stream = response.GetResponseStream())
{
while ((read = stream.Read(bytes, 0, bytes.Length)) > 0)
responseText.Append(Encoding.ASCII.GetString(bytes, 0, read));
}
string jsonString = responseText.ToString();
AzureTokenResponse t = JsonConvert.DeserializeObject<AzureTokenResponse>(jsonString);
token = new OAuthToken(
t.access_token,
TokenType.AccessToken,
DateTime.Now.AddSeconds(t.expires_in));
return token;
}
}
/// <summary>
/// Gets oAuth access token.
/// If token exists and its expiration date is not expired returns current token, otherwise requests new token from a server.
/// </summary>
/// <returns>Returns oAuth access token</returns>
public OAuthToken GetAccessToken()
{
return GetAccessToken(false);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public virtual void Dispose()
{
}
}
/// <summary>
/// A success response contains a JSON OAuth 2.0 response with the following parameters.
/// </summary>
public class AzureTokenResponse
{
/// <summary>
/// The requested access token. The calling web service can use this token to authenticate to the receiving web service.
/// </summary>
public string access_token { get; set; }
/// <summary>
/// Indicates the token type value. The only type that Azure AD supports is Bearer For more information about bearer tokens,
/// see The OAuth 2.0 Authorization Framework: Bearer Token Usage (RFC 6750).
/// </summary>
public string token_type { get; set; }
/// <summary>
/// How long the access token is valid (in seconds).
/// </summary>
public int expires_in { get; set; }
/// <summary>
/// How long the access token is valid (in seconds).
/// </summary>
public int ext_expires_in { get; set; }
/// <summary>
/// The time when the access token expires.
/// The date is represented as the number of seconds from 1970-01-01T00:00:00Z UTC until the expiration time.
/// This value is used to determine the lifetime of cached tokens.
/// </summary>
public int expires_on { get; set; }
/// <summary>
/// The App ID URI of the receiving web service.
/// </summary>
public string resource { get; set; }
/// <summary>
/// If an access token was returned, this parameter lists the scopes the access token is valid for.
/// </summary>
public string scope { get; set; }
/// <summary>
/// Issued if the original scope parameter included the openid scope.
/// </summary>
public string id_token { get; set; }
/// <summary>
/// Issued if the original scope parameter included offline_access.
/// </summary>
public string refresh_token { get; set; }
}
}
ITokenProvider tokenProvider = new AzureROPCTokenProvider(
"Tenant",
"ClientId",
"ClientSecret",
"EMail",
"Password",
scopes);
const string mailboxUri = "https://outlook.office365.com/ews/exchange.asmx";
ICredentials credentials = new OAuthNetworkCredential(tokenProvider);
using (IEWSClient ewsClient = EWSClient.GetEWSClient(mailboxUri, credentials))
{
}
However, am getting an error response as below
System.Net.WebException
HResult=0x80131509
Message=The remote server returned an error: (400) Bad Request.
Source=System
StackTrace:
at System.Net.HttpWebRequest.GetResponse()
at DataLoadLibrary.Emai.AzureROPCTokenProvider.GetAccessToken(Boolean ignoreExistingToken) in C:\path\to\file\DataLoadLibrary\Email\AzureROPCTokenProvider .cs:line 97
at DataLoadLibrary.Emai.AzureROPCTokenProvider.GetAccessToken() inC:\path\to\file\DataLoadLibrary\Email\AzureROPCTokenProvider .cs:line 123
at #=zh9Fqfcq_HoOXkObKc3_xqZJZ5tEDCTrUjh8nD$EvlR1sjwBuAg==.GetWebRequest(Uri #=zYomVKA4=)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at #=z59FR9EVW5_PdyTyl2BGNIgxEQwbI$thui3I5Af7oPUiZ1$E9A==.GetFolder(GetFolderType GetFolder1)
at Aspose.Email.Clients.Exchange.WebService.EWSClient.GetEWSClient(String mailboxUri, ICredentials credentials, WebProxy proxy)
By going through the code I could find that it is not using the client secret which passed to the class. Then I have modified the body HttpUtility.UrlEncode(ClientSecret));
. Unfortunately I am getting the same exception
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
现代身份验证(IE OAUTH2)得到了EWS的支持。请阅读以下Aspose.Email文章以获取更多详细信息。
使用oauth使用oauth
您可以完整下载代码示例与EWS客户端使用不同权限类型的现代身份验证类型:
与授权身份验证 - ewsmodernauthentication.zip
具有应用程序身份验证 -
zip
我与Aspose一起担任开发人员传教士。
Modern authentication (i.e. oAuth2 ) has been supported by EWS. Please read the following Aspose.Email article for more detail.
Access Mail Services using OAuth
You can download full code examples to use different permission types of modern authentication with EWS client from here:
With Delegated authentication - EWSModernAuthenticationDelegated.zip
With Application authentication - EWSModernAuthenticationApp.zip
Modern authentication with IMAP and SMTP clients - EWSModernAuthenticationImapSmtp.zip
I work with Aspose as Developer Evangelist.