Mailkit Can't authenticate with O365 oAuth2 account - oauth-2.0

I tried to authenticate on a O365 application I created on the Azure portal and it doesn't work as expected.
The following code works well but it's using a login/password and it's not recommended by Microsoft. (found here https://github.com/jstedfast/MailKit/issues/989)
var scopes = new[] { "https://outlook.office365.com/IMAP.AccessAsUser.All" };
var confidentialClientApplication = PublicClientApplicationBuilder.Create(_clientId).WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs).Build();
SecureString securePassword = new NetworkCredential("", _userPassword).SecurePassword;
var acquireTokenByUsernamePasswordParameterBuilder = confidentialClientApplication.AcquireTokenByUsernamePassword(scopes, _userMail, securePassword);
var authenticationResult = acquireTokenByUsernamePasswordParameterBuilder.ExecuteAsync().Result;
if (_debugCall)
{
imapClient = new ImapClient(new ProtocolLogger(_configurationId + "_IMAP_" + DateTime.Now.ToString("yyyyMMddHHssffff") + ".log"));
}
else
{
imapClient = new ImapClient();
}
imapClient.CheckCertificateRevocation = false;
imapClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
imapClient.Connect(_webServiceUrl, _webServicePort, SecureSocketOptions.Auto);
imapClient.Authenticate(new SaslMechanismOAuth2(_userMail, authenticationResult.AccessToken));
if (string.IsNullOrEmpty(_folder))
{
oFolder = imapClient.Inbox;
}
else
{
oFolder = imapClient.GetFolder(_folder);
}
oFolder.Open(FolderAccess.ReadWrite);
In fact I want to be able to authenticate using the tenanid, client secret and clientid but without the interactive mode (as the app is a windows services).
So I tried to use another code with the tenantid, clientSecret and ClientId but I receive the "Authentication failed" error message :
var confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(_clientId)
.WithClientSecret(_clientSecret)
.WithRedirectUri("http://localhost")
.WithAuthority(new Uri("https://login.microsoftonline.com/" + _tenantid + "/"))
.Build();
var scopes = new[] { "https://outlook.office365.com/.default" };
var authenticationResult = confidentialClientApplication.AcquireTokenForClient(scopes);
var authToken = authenticationResult.ExecuteAsync().Result;
var oauth2 = new SaslMechanismOAuth2(_userMail, authToken.AccessToken);
imapClient = new ImapClient(new ProtocolLogger("TEST_IMAP_" + DateTime.Now.ToString("yyyyMMddHHssffff") + ".log"));
imapClient.CheckCertificateRevocation = false;
imapClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
imapClient.Connect(_webServiceUrl, _webServicePort, SecureSocketOptions.Auto);
imapClient.Authenticate(oauth2);
I've the following permission for my app on the Azure portal:
MSGraph
IMAP.AccessAsUser.All
Mail.Read
Mail.ReadWrite
Mail.Send
Did I miss something? I'm afraid it may be impossible? The official sample on Mailkit website use the interactive mode.
Btw, I'm using Mailkit v2.4
Thank you for your help.

It appears that OAUTH2 authentication with Office365 via the non-interactive method is unsupported by the Microsoft Exchange IMAP/POP3/SMTP protocols and that the only way to get access to Office365 mail using the non-interactive method of OAUTH2 authentication is via the Microsoft.Graph API.
I've been getting a lot of questions about this over the past few months and as far as I'm aware, no one (myself included) has been able to find a way to make this work.
I keep hoping to see someone trying to do this (even in another language) here on StackOverflow with an accepted answer. So far, all I've seen are questions about OAuth2 using the interactive approach (which, as you've seen, I have written documentation for and is known to work well with MailKit).

Related

Difference between oauth2/v2 vs oidc Spotify API

i'm currently trying to connect via UNO-Plattform sample to the Spotify API.
https://github.com/unoplatform/Uno.Samples/blob/master/UI/Authentication.OidcDemo/Authentication.OidcDemo/Authentication.OidcDemo.Shared/MainPage.xaml.cs
Therefore I have updated the PrepareClient method.
private async void PrepareClient()
{
var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().OriginalString;
// Create options for endpoint discovery
var options = new OidcClientOptions
{
Authority = "https://accounts.spotify.com", //"https://demo.duendesoftware.com/",
ClientId = "7c1....a45",
ClientSecret = "4b..a",
Scope = "playlist-read-private",
RedirectUri = redirectUri,
PostLogoutRedirectUri = redirectUri,
ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect,
Flow = OidcClientOptions.AuthenticationFlow.AuthorizationCode
};
// Create the client. In production application, this is often created and stored
// directly in the Application class.
_oidcClient = new OidcClient(options);
var extra_parameters = new Dictionary<string, string>();
//extra_parameters.Add("response_type", "token"); // if i add this line i get an error
_loginState = await _oidcClient.PrepareLoginAsync(extra_parameters);
btnSignin.IsEnabled = true;
// Same for logout url.
//If i add this line a get an error
//_logoutUrl = new Uri(await _oidcClient.PrepareLogoutAsync(new LogoutRequest()));
btnSignout.IsEnabled = true;
}
private async void SignIn_Clicked(object sender, RoutedEventArgs e)
{
var startUri = new Uri(_loginState.StartUrl);
// Important: there should be NO await before calling .AuthenticateAsync() - at least
// on WebAssembly, in order to prevent triggering the popup blocker mechanisms.
var userResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri);
if (userResult.ResponseStatus != WebAuthenticationStatus.Success)
{
txtAuthResult.Text = "Canceled";
// Error or user cancellation
return;
}
// User authentication process completed successfully.
// Now we need to get authorization tokens from the response
var authenticationResult = await _oidcClient.ProcessResponseAsync(userResult.ResponseData, _loginState);
if (authenticationResult.IsError)
{
var errorMessage = authenticationResult.Error;
// TODO: do something with error message
txtAuthResult.Text = $"Error {errorMessage}";
return;
}
// That's completed. Here you have to token, ready to do something
var token = authenticationResult.AccessToken;
var refreshToken = authenticationResult.RefreshToken;
// TODO: make something useful with the tokens
txtAuthResult.Text = $"Success, token is {token}";
}
If i use Postman for authentication, i can use the URL
curl --location --request GET 'https://accounts.spotify.com/authorize?response_type=token&client_id=7c...45&scope=playlist-read-private&redirect_uri=http://localhost:8080&state=test'
and everything works fine and i get the token in the callback url as parameter.
If i add as "extra_parameters" the "response_type" : "token" i get the message, that this parameter is not supported...
I'm a little bit stucked here and don't know how to proceed.
I'm happy about any help in every direction to get this autentication done with uno-plattform.
OIDC can be described as a superset of OAuth2. It is a way for an identity provider to issue tokens and supply info about a user via additional APIs. Read more here.
The Oidc code that you use (probably IdentityModel.OidcClient?) requires a the service you’re calling to implement a few extra endpoints which Spotify has not implemented for their API. This is discussed in this forum topic. Because of the missing Oidc support, your code will try making calls that do not work.
The SpotifyAPI-NET library might also help you authenticate and make API calls instead.

The given token is invalid error in EWS OAuth authentication when using personal account

I have to get the contacts from Exchange server from any account, so we have used the code from below link.
https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth
But it is not working for personal accounts, which is working fine for our organization account. So I have used AadAuthorityAudience property instead of TenantId and changed the scope from EWS.AccessAsUser.All to others. Now authentication got success but getting "The given token is invalid" error while using the token in ExchangeService.
var pcaOptions = new PublicClientApplicationOptions {
ClientId = "77xxxxxxxxxxx92324",
//TenantId = "7887xxxxxxxxxxxxx14",
RedirectUri = "https://login.live.com/oauth20_desktop.srf",
AadAuthorityAudience = AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount};
var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(pcaOptions).Build();
//var ewsScopes = new string[] { "https://outlook.office365.com/EWS.AccessAsUser.All" };
var ewsScopes = new string[] { "User.Read", "Contacts.ReadWrite.Shared" };
var authResult = await pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync();
var ewsClient = new ExchangeService();
ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
//ewsClient.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "araj#concord.net");
ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
// Make an EWS call
var folders = ewsClient.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(10));
What am doing wrong here?
https://outlook.office365.com/EWS.AccessAsUser.All is the right scope to use. The scope is invalid for personal accounts since they're not supported by EWS.

How to get an ACS app-only access token for Project Online

I'm trying to get an AppOnly access token for use in the Authorization Bearer header of my request to a REST endpoint in Project Online (SharePoint). Following is a snippet of the code that I was using to retrieve the access token.
private OAuth2AccessTokenResponse GetAccessTokenResponse()
{
var realm = TokenHelper.GetRealmFromTargetUrl([[our_site_url]]);
var resource = $"00000003-0000-0ff1-ce00-000000000000/[[our_site_authority]]#{realm}";
var formattedClientId = $"{ClientId}#{realm}";
var oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(
formattedClientId,
ClientSecret,
resource);
oauth2Request.Resource = resource;
try
{
var client = new OAuth2S2SClient();
var stsUrl = TokenHelper.AcsMetadataParser.GetStsUrl(realm);
var response = client.Issue(stsUrl, oauth2Request) as OAuth2AccessTokenResponse;
var accessToken = response.AccessToken;
}
catch (WebException wex)
{
using (var sr = new StreamReader(wex.Response.GetResponseStream()))
{
var responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
}
I keep getting 403 Forbidden as the response from the server, even if I include site collection admin credentials with my request. Does anyone out there have any ideas?
After creating a support ticket with Microsoft to figure this out we eventually decided to move away from using app permissions for console application authorization.
Our workaround was to create SharePointOnlineCredentials object using a service account, and then get the Auth cookie from the credentials object to pass with our WebRequest. This solution came from scripts found here: https://github.com/OfficeDev/Project-REST-Basic-Operations

Oauth2 and Access Token in SharePoint App

I am creating an intranet on SharePoint - O365 where I can a widget where I need to pull calendar events and display them for a week. Here is a steps walk through:
a. User log in to Intranet
b. Access token is generated to access Office 365 REST API
c. Calendar events are fetched and displayed.
Here is my problem:
I thought of 2 options to generate the access token
option a: Create a WCF application which accpets user context and generate the token. This will fetch the results and update a list. My intranet app can read a calendar list and update the widget. This didnt work since I was not able to pass the user context from SP to WCF method so that access token can be generated.
Option b: Use the following code (which I have done as of now) but it display the access token in URL which is not good for the client.
var clientId = '>>sample>>';
var replyUrl = '<<>>';
var endpointUrl = 'https://outlook.office365.com/api/v1.0/me/events';
var resource = "https://outlook.office365.com/";
var authServer = 'https://login.windows.net/common/oauth2/authorize?';
var responseType = 'token';
var url = authServer +
"response_type=" + encodeURI(responseType) + "&" +
"client_id=" + encodeURI(clientId) + "&" +
"resource=" + encodeURI(resource) + "&" +
"redirect_uri=" + encodeURI(replyUrl);
window.location = url;
So is there any other way to achieve this??
Ankush
Since you mentioned that you want to use the WCF, are you developing an provided host SharePoint app?
If I understand correctly, we can use the Explicit Authorization Code Grant Flow which didn’t expose the Access token to the user agent. The following diagram illustrates the Authorization Code Grant flow:
And here is the core code to retrieve the access token for the Office 365 resource for you reference:
var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new ADALTokenCache(signInUserId));
try
{
DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
async () =>
{
var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId,
new ClientCredential(SettingsHelper.ClientId,
SettingsHelper.ClientSecret),
new UserIdentifier(userObjectId,
UserIdentifierType.UniqueId));
string token= authResult.AccessToken;
return authResult.AccessToken;
});
var dcr = await discClient.DiscoverCapabilityAsync(capabilityName);
return new OutlookServicesClient(dcr.ServiceEndpointUri,
async () =>
{
var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId,
new ClientCredential(SettingsHelper.ClientId,
SettingsHelper.ClientSecret),
new UserIdentifier(userObjectId,
UserIdentifierType.UniqueId));
return authResult.AccessToken;
});
}
The full code sample you can refer to here. And here is a helpful link that discuss the difference between explicit and implicate authentication flow.

Linq to Twitter - Bad Authentication data

I've the the latest version of Linq to Twitter (3.1.2), and I'm receiving the "Bad Authentication data" error with the code below:
var auth = new ApplicationOnlyAuthorizer
{
CredentialStore = new InMemoryCredentialStore
{
ConsumerKey = "xxxx",
ConsumerSecret = "xxxx"
}
};
using (var twitter = new TwitterContext(auth))
{
var users = twitter.User.Where(s => s.Type == UserType.Search && s.Query == "filter:verified").ToList();
}
I thought at first that it could be Twitter taking a while to accept my new credentials, but I used Twitter's OAuth tool with my keys, and they produced tokens without issue. Any ideas what I'm missing here?
I could not find a duplicate, as the code referenced # https://stackoverflow.com/questions/16387037/twitter-api-application-only-authentication-with-linq2twitter#= is no longer valid in the version I am running.
That query doesn't support Application-Only authorization. Here's the Twitter docs to that:
https://dev.twitter.com/rest/reference/get/users/search
Instead, you can use SingleUserAuthorizer, documented here:
https://github.com/JoeMayo/LinqToTwitter/wiki/Single-User-Authorization
Like this:
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"],
AccessToken = ConfigurationManager.AppSettings["accessToken"],
AccessTokenSecret = ConfigurationManager.AppSettings["accessTokenSecret"]
}
};
To find out what type of authorization is possible, you can visit the L2T wiki at:
https://github.com/JoeMayo/LinqToTwitter/wiki
and each API query and command has a link at the bottom of the page to the corresponding Twitter API documentation.

Resources