JavaMail with Oauth and Office365 - oauth

I'm building a simple commandline application in Java, that logs into my email box (IMAP) and downloads all attachments. I used basic authentication, but Microsoft is in the process of disabling that so I try to convert my application to use OAuth instead.
After reading on the different OAuth flows, it seems that for my simple standalone commandline application, where there is no problem to simply hardcode a password, the Resource Owner Password Credentials Grand (as described here) would be the best (or a good) choice. I further based myself on the instructions from this source where it is described how to enable OAuth using recent versions of Javamail.
Putting it all together seems a bit harder, and I keep getting AUTHENTICATE Failed errors.
So, what did I try? I first retrieve my authorization token as follows:
public String getAuthToken() {
try {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost loginPost = new HttpPost("https://login.microsoftonline.com/organizations/oauth2/v2.0/token");
String clientId = "some client UUID";
String scopes = "email openid IMAP.AccessAsUser.All offline_access";
String client_secret = "My client secret, not base64 encoded";
String username = "my emailadress";
String password = "my password, not base64 encoded";
String encodedBody = "client_id=" + clientId
+ "&scope=" + scopes
+ "&client_secret=" + client_secret
+ "&username=" + username
+ "&password=" + password
+ "&grant_type=password";
loginPost.setEntity(new StringEntity(encodedBody, ContentType.APPLICATION_FORM_URLENCODED));
loginPost.addHeader(new BasicHeader("cache-control", "no-cache"));
CloseableHttpResponse loginResponse = client.execute(loginPost);
byte[] response = loginResponse.getEntity().getContent().readAllBytes();
ObjectMapper objectMapper = new ObjectMapper();
JavaType type = objectMapper.constructType(objectMapper.getTypeFactory()
.constructParametricType(Map.class, String.class, String.class));
Map<String, String> parsed = new ObjectMapper().readValue(response, type);
return parsed.get("access_token");
} catch (Exception e) {
e.printStackTrace();
return null;
}
The response from the oauth service is actually a json-object which contains following fields:
Obviously the tokens are much longer, but are not shared here. The access_token itself is in the form of three base64 encoded strings seperated by a . The first, when decoded contains
{
"typ": "JWT",
"nonce": "Vobb8bI7E...",
"alg": "RS256",
"x5t": "2ZQpJ3Up...",
"kid": "2ZQpJ3Up..."
}
the second part is a larger object, containing following fields (redacted as well):
{
"aud": "someuuid",
"iss": "https://sts.windows.net/someuuid/",
"iat": 1658397625,
"nbf": 1658397625,
"exp": 1658402597,
"acct": 0,
"acr": "1",
"aio": "ASQ....",
"amr": [
"pwd"
],
"app_displayname": "myapp",
"appid": "some uuid",
"appidacr": "1",
"family_name": "My Last Name",
"given_name": "My First Name",
"idtyp": "user",
"ipaddr": "some.ip.address.here",
"name": "My Full name",
"oid": "someuuid",
"platf": "14",
"puid": "10032...",
"rh": "0.AToA....",
"scp": "email IMAP.AccessAsUser.All openid profile",
"sub": "enaKK...",
"tenant_region_scope": "EU",
"tid": "someuuid",
"unique_name": "my email",
"upn": "my email",
"uti": "1cc...",
"ver": "1.0",
"wids": [
"some uuid",
"some uuid"
],
"xms_st": {
"sub": "02n7h..."
},
"xms_tcdt": 1571393936
}
The last part is just binary data. I currenly simply pass on the entire access_token as I receive it to JavaMail as follows:
String accesstoken = new OauthTokenFetcher().getAuthToken();
imapReader = new ImapMailBoxReader(
"outlook.office365.com",
"my email",
accesstoken);
LocalDate startDate = LocalDate.of(2022,4,1);
LocalDate endDate = LocalDate.of(2022,7,1);
imapReader.processOnMessages("Inbox", startDate, endDate,this::processMessage);
with ImapMailBoxReader as follows:
public class ImapMailBoxReader {
private String host;
private String username;
private String password;
public ImapMailBoxReader(String host, String username, String password) {
this.host = host;
this.username = username;
this.password = password;
}
public void processOnMessages(String folder, LocalDate since, LocalDate until, Consumer<Message> mailconsumer) {
try {
System.out.println("Password:" + password);
Properties prop = new Properties();
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.debug.auth", "true");
prop.put("mail.imap.sasl.enable", "true");
prop.put("mail.imap.sasl.mechanisms", "XOAUTH2");
prop.put("mail.imap.auth.login.disable", "true");
prop.put("mail.imap.auth.plain.disable", "true");
prop.put("mail.imap.ssl.enable", "true");
// Create the session
//Connect to the server
Session session = Session.getDefaultInstance(prop, null);
session.setDebug(true);
Store store = session.getStore("imap");
store.connect(host, username, password);
//open the inbox folder
Folder inbox = store.getFolder(folder);
inbox.open(Folder.READ_ONLY);
Message[] messages;
if (since != null) {
Date startDate = Date.from(since.atStartOfDay(ZoneId.systemDefault()).toInstant());
SearchTerm newerThan = new ReceivedDateTerm(ComparisonTerm.GE, startDate);
if (until != null) {
Date endDate = Date.from(until.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
SearchTerm olderThan = new ReceivedDateTerm(ComparisonTerm.LT, endDate);
SearchTerm both = new AndTerm(olderThan, newerThan);
messages = inbox.search(both);
} else {
messages = inbox.search(newerThan);
}
} else if (until != null) {
Date endDate = Date.from(until.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
SearchTerm olderThan = new ReceivedDateTerm(ComparisonTerm.LT, endDate);
messages = inbox.search(olderThan);
} else {
messages = inbox.getMessages();
}
for (Message m: messages) {
mailconsumer.accept(m);
}
inbox.close(false);
store.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The above statement fails at the store.connect statement with AUTHENTICATE FAILED.
I probably pass on the token incorrectly? The JavaMail documentation above states that I should not Base64 encode the token, but I received it as such. Am I supposed to send only part of it? Which part then?
Any help would be appreciated.

With a tip from a co-worker without a stackoverflow account, I finally got it to work. The key was that the scopes I used for the OAuth token, are apparantly not allowed for an application. This bit of information is hidden at the bottom of this page.
Summarized, the solution is:
You must configure the IMAP.AccessAsApp permission, instead of IMAP.AccessAsUser.All . This permission can not be found in the same place as the AccessAsUser.All permission, but is hidden under "Office 365 Exchange Online" permissions.
Unlike what you would expect, you must use the https://outlook.office365.com/.default scope in the body payload for the access token request.
That did the trick. It is ridiculous how much difficulty I had to find that information in the documentation pages using search engines.

Please check if you have enabled Allow public client flows setting in azure app registrations. This is required for ROPC as description says.
Allow public client flows
This is under App Registrations -> Overview-> redirect URIs.

I had a similar situation as the OP. I had a Java (swing) standalone app that reads and processes specific messages from the inbox. The app has been running for a couple of years using basic auth. Recently (Early October), Microsoft disable basic auth. I had to scramble to figure out OAUTH. This post got me very close; HOWEVER, the final answer did not work for me.
Getting the access token was easy enough, but authentication ALWAYS failed. Obviously, the permissions/grants for my token were not correct.
My solution:
Configure Microsoft Graph permissions IMAP.AccessAsUser.All . (opposite of OP's solution)
Scope - "email openid https://outlook.office.com/IMAP.AccessAsUser.All"
Everything else pretty much exactly followed OP.
Hope this might help another lost soul.

Related

Microsoft.Graph.GraphServiceClient allows me to create a user but does not allow me to change password

I have a system comprised of an Angular SPA hosted in Azure and some Azure Functions for the APIs. In an administrative app, I created an application that allows admin users to create new user accounts including specifying a password. These new accounts are able to log into the line of business app that I created as well. There is a requirement where we need to allow the same people who created the account to reset a password. For some reason, the code that I wrote to set the password does not work. It seems odd that a user can create an account, including setting the password, but for some reason the same user can't set the password independent of creating the user account. FYI, there are no emails, these are user accounts, so giving the ability to request a password reset is not an option.
Here is the error:
{
"error": {
"code": "Authorization_RequestDenied",
"message": "Access to change password operation is denied.",
"innerError": {
"date": "2021-01-19T21:58:35",
"request-id": "a1bc5b50-83e9-47ae-97c7-bda4f524fa0e",
"client-request-id": "a1bc5b50-83e9-47ae-97c7-bda4f524fa0e"
}
}
}
Here is my code:
//this is the method that works
public async Task<Microsoft.Graph.User> CreateUserAsync(string givenName,
string surname, string displayName, string userPrincipalName, string issuer,
string signInType, string initialPassword, GraphServiceClient graphClient)
{
var user = new Microsoft.Graph.User {
AccountEnabled = true,
GivenName = givenName,
Surname = surname,
DisplayName = displayName,
Identities = new List<ObjectIdentity>() {
new ObjectIdentity {
Issuer = issuer,
IssuerAssignedId = userPrincipalName,
SignInType = signInType
}
},
PasswordProfile = new PasswordProfile {
ForceChangePasswordNextSignIn = false,
Password = initialPassword
}
};
return await graphClient.Users
.Request()
.AddAsync(user);
}
//This one does not work, returns: Access to change password operation is denied.
public async Task<Microsoft.Graph.User> SetPasswordAsync(
string userName, string currentPassword, string newPassword, GraphServiceClient graphClient)
{
await graphClient.Users[userName].ChangePassword(currentPassword, newPassword).Request().PostAsync();
return something here;
}
Seems this is a permission issue here. The function:graphClient.Users[].ChangePassword()is based on reset password rest API,as the official doc indicated, only delegated permission works here and permission :UserAuthenticationMethod.ReadWrite.All is needed.
After I granted this permission to my app:
it works perfectly for me:
Let me know if you have any further questions.

Get 404 "The resource could not be found" when call /beta/informationprotection/policy/labels

according to documentation we may use the following endpoints for fetching sensitivity labels:
/me/informationProtection/policy/labels (using delegated permissions)
/informationProtection/policy/labels (using application permission. App should have InformationProtectionPolicy.Read.All permission to use this end point)
The following C# code uses app permissions and it works on tenant1:
static void Main(string[] args)
{
string accessToken = getTokenImpl().Result;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("User-Agent", "PostmanRuntime/7.24.1");
using (var response = client.GetAsync($"https://graph.microsoft.com/beta/informationprotection/policy/labels").Result)
{
using (var content = response.Content)
{
string result = content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine(result);
}
}
}
}
}
private static async Task<string> getTokenImpl()
{
string clientId = "...";
string clientSecret = "...";
string tenant = "{...}.onmicrosoft.com";
string authority = string.Format("https://login.microsoftonline.com/{0}", tenant);
var authContext = new AuthenticationContext(authority);
var creds = new ClientCredential(clientId, clientSecret);
var authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", creds);
return authResult.AccessToken;
}
But it doesn't work on another tenant2 - there it always returns 404 "The resource could not be found" with the following inner exception "User not found to have labels, policy is empty". Here is full response:
{
"error": {
"code": "itemNotFound",
"message": "The resource could not be found.",
"innerError": {
"code": "notFound",
"message": "User not found to have labels, policy is empty",
"target": "userId",
"exception": null,
"date": "2020-11-18T09:29:20",
"request-id": "657ad51c-9cab-49f2-a242-50929cdc6950",
"client-request-id": "657ad51c-9cab-49f2-a242-50929cdc6950"
}
}
}
Interesting that attempt to call endpoint /me/informationProtection/policy/labels with delegated permissions on the same tenant2 gives the same error, but on tenant1 it also works. Did anybody face with this problem or have idea why it may happen? Need to mention that on tenant2 earlier we created and published several sensitivity labels for specific user - this user doesn't have neither O365 license nor Azure subscription. I.e. when you try to login to SPO/Azure and create site/group - sensitivity labels were not shown at all for this user. We tried to remove these sensitivity labels and their policies with audience targeting to this user, but both end points still return error.
PS. AAD app is Ok on tenant2 - it has InformationProtectionPolicy.Read.All permission and admin consent is granted:
Update 2020-11-25: behavior has been changed on both tenants without any change from our side: now on both tenants we get 502 Bad Gateway. Does MS rolls out this functionality globally now? Here is response which we get now from /beta/me/informationProtection/policy/labels:
{
"error":{
"code":"UnknownError",
"message":"<html>\r\n<head><title>502 Bad Gateway</title></head>\r\n<body>\r\n<center><h1>502 Bad Gateway</h1></center>\r\n<hr><center>Microsoft-Azure-Application-Gateway/v2</center>\r\n</body>\r\n</html>\r\n",
"innerError":{
"date":"2020-11-25T12:59:51",
"request-id":"93557ae1-b0d9-44a9-bbea-871f18e379ea",
"client-request-id":"93557ae1-b0d9-44a9-bbea-871f18e379ea"
}
}
}
Update 2020-12-07: it started to work by its own. I.e. MS has fixed that on backend side somehow for the tenant when this issue was reproduced.

Swagger/Swashbuckle + IdentityServer4 Implicit Flow: 401 Error after successful login?

I am trying to implement OAuth to one of my companies' projects and can't resolve the following problem.
We used IdentityServer4 for implementing our own Authorization Server, which works fine so far. The resource I want to protect with OAuth is a WebApi utilizing Swagger/Swashbuckle.
I followed the IdentityServer4 QuickStartExamples to configure the server and this tutorial [Secure Web APIs with Swagger, Swashbuckle, and OAuth2 (part 2)](http://knowyourtoolset.com/2015/08/secure-web-apis-with-swagger-swashbuckle-and-oauth2-part-2 for configuring Swagger/Swashbuckle).
I have a dummy-action which does nothing else than returning a string, that works as expected.
When I decorate the action with [Authorize], a little red icon appears in swagger-ui, indicating that I have to log in to access this method. The Login process works fine: I am redirected to the Quickstart-UI, can login with the testuser "Bob", and I am redirected to swagger-ui after a successful login.
The problem: After the successful login, I still get an 401 error, stating "Authorization has been denied for this request."
I can see that a bearer token is returned by my IdentityServer in swagger-ui, so I guess this part working fine and the problem seems to be swagger/swashbuckle.
Is there maybe anything else I have to do with the token? In the tutorials I read so far, the swagger config is modified as I did it (see below) and that's it, so I guess swagger/swashbuckle should handle this - but maybe I miss out something?
SwaggerConfig.cs:
c.OAuth2("oauth2")
.Description("OAuth2 Implicit Grant")
.Flow("implicit") //also available: password, application (=client credentials?)
.AuthorizationUrl("http://localhost:5000/connect/authorize")
.TokenUrl("http://localhost:5000/connect/token")
.Scopes(scopes =>
{
scopes.Add("My.Web.Api", "THE Api");
});
// etc. .....
c.OperationFilter<AssignOAuth2SecurityRequirements>();
// etc. .....
c.EnableOAuth2Support(
clientId: "swaggerui",
clientSecret: "secret",
realm: "dummyrealm",
appName: "Swagger UI"
);
Filter for Authorize Attribute in SwaggerConfig.cs:
public class AssignOAuth2SecurityRequirements : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
// Determine if the operation has the Authorize attribute
var authorizeAttributes = apiDescription
.ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>();
if (!authorizeAttributes.Any())
return;
// Initialize the operation.security property
if (operation.security == null)
operation.security = new List<IDictionary<string, IEnumerable<string>>>();
// Add the appropriate security definition to the operation
var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
{
{ "oauth2", new [] { "My.Web.Api" } }
};
operation.security.Add(oAuthRequirements);
}
}
IdentityServer api config:
new ApiResource("My.Web.Api", "THE Api")
IdentityServer client config:
new Client
{
ClientId = "swaggerui",
ClientName = "Swagger UI",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
AllowedCorsOrigins = { "http://localhost:5858" },
ClientSecrets =
{
new Secret("secret".Sha256())
},
RedirectUris = { "http://localhost:5858/swagger/ui/o2c-html" },
PostLogoutRedirectUris = { "http://localhost:5858/swagger/ui/o2c-html" },
AllowedScopes =
{
"My.Web.Api"
}
Screenshot of redirection after login:
When using .NET Core (but it would appear that this question is for .NET Framework) I also encountered this same problem. It was solved by ensuring that in the Configure method of Startup you have UseAuthentication before UseAuthorization
(source https://learn.microsoft.com/en-us/aspnet/core/grpc/authn-and-authz?view=aspnetcore-3.1)

Getting Gmail API access and ID token, but refresh token is NULL

Following https://developers.google.com/identity/sign-in/web/server-side-flow After getting the authorization code from JavaScript, and passing it to the server side, we indeed get an access token (and an ID token), but not the required refresh token.
There are many posts around but could not solve it yet.
Any suggestion how to get the refresh token?
thanks!
private String getResponseToken(GoogleClientSecrets clientSecrets,
String authCode) throws IOException {
try {
GoogleTokenResponse tokenResponse =
new GoogleAuthorizationCodeTokenRequest(
new NetHttpTransport(),
JacksonFactory.getDefaultInstance(),
"https://www.googleapis.com/oauth2/v4/token",
// "https://accounts.google.com/o/oauth2/token",
clientSecrets.getDetails().getClientId(),
clientSecrets.getDetails().getClientSecret(),
authCode, //NOTE: was received from JavaScript client
"postmessage" //TODO: what's this?
).execute();
String accessToken = tokenResponse.getAccessToken();
String idToken = tokenResponse.getIdToken();
//TODO: not getting a refresh token... why?!
String refreshToken = tokenResponse.getRefreshToken();
Boolean hasRefreshToken = new Boolean(!(refreshToken == null));
LOGGER.warn("received refresh token: {}", hasRefreshToken);
LOGGER.debug("accessToken: {}, refreshToken: {}, idToken: {}", accessToken, refreshToken, idToken);
return accessToken;
}catch (TokenResponseException tre){...}
Gmail API only gives the refresh token the first time you ask for the users permission. (At least this is what happens to me).
Go to: https://myaccount.google.com/permissions?pli=1, remove the authorization to your app and run your code. You should receive the refresh token.
you should add the
AccessType = "offline"
You need to call the function
new GoogleAuthorizationCodeRequestUrl(...).setAccessType("offline")
or another syntax:
var authReq = new GoogleAuthorizationCodeRequestUrl(new Uri(GoogleAuthConsts.AuthorizationUrl)) {
RedirectUri = Callback,
ClientId = ClientId,
AccessType = "offline",
Scope = string.Join(" ", new[] { Scopes... }),
ApprovalPrompt = "force"
};
in Fiddler you should see the following request:
https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/webmasters&redirect_uri=http://mywebsite.com/google/scapi/callback/&response_type=code&client_id=xxx&access_type=offline
see also here
More details about setAccessType can be found here
after finding how to use the Google APIs at the backend (documentation is somewhat partial..), the issue was fixed at the FrontEnd side by tweaking a parameter:
grantOfflineAccess({
- prompt: 'select_account'
+ prompt: 'consent'
HTH

403 Response From Adobe Experience Manager OAuth 2 Token Endpoint

I am using Postman to test OAuth 2 from a vanilla AEM install.
Postman can successfully obtain the authorization code from /oauth/authorize after I grant access:
But when it tries to use the code to obtain a token from /oauth/token it receives the following response:
HTTP ERROR: 403 Problem accessing /oauth/token. Reason: Forbidden
Powered by Jetty://
Looking in Fiddler it is doing a POST to /oauth/token with the following Name/Values in the body:
client_id: Client ID from /libs/granite/oauth/content/client.html
client_secret:
Client Secret from /libs/granite/oauth/content/client.html
redirect_uri: https://www.getpostman.com/oauth2/callback
grant_type: authorization_code
code: Code returned from previous request to oauth/authorize
Am I missing something?
Would help if you can list some code snippets on how you are building the url and fetching the token.
Here's an example of how we've implemented very similar to what you are trying to do, maybe it'll help.
Define a service like below (snippet) and define the values (host, url, etc) in OSGI (or you can also hard code them for testing purposes)
#Service(value = OauthAuthentication.class)
#Component(immediate = true, label = "My Oauth Authentication", description = "My Oauth Authentication", policy = ConfigurationPolicy.REQUIRE, metatype = true)
#Properties({
#Property(name = Constants.SERVICE_VENDOR, value = "ABC"),
#Property(name = "service.oauth.host", value = "", label = "Oauth Host", description = "Oauth Athentication Server"),
#Property(name = "service.oauth.url", value = "/service/oauth/token", label = "Oauth URL", description = "Oauth Authentication URL relative to the host"),
#Property(name = "service.oauth.clientid", value = "", label = "Oauth Client ID", description = "Oauth client ID to use in the authentication procedure"),
#Property(name = "service.oauth.clientsecret", value = "", label = "Oauth Client Secret", description = "Oauth client secret to use in the authentication procedure"),
#Property(name = "service.oauth.granttype", value = "", label = "Oauth Grant Type", description = "Oauth grant type") })
public class OauthAuthentication {
...
#Activate
private void activate(ComponentContext context) {
Dictionary<String, Object> properties = context.getProperties();
host = OsgiUtil.toString(properties, PROPERTY_SERVICE_OAUTH_HOST,new String());
// Similarly get all values
url =
clientID =
clientSecret =
grantType =
authType = "Basic" + " "+ Base64.encode(new String(clientID + ":" + clientSecret));
}
public static void getAuthorizationToken(
try {
UserManager userManager = resourceResolver.adaptTo(UserManager.class);
Session session = resourceResolver.adaptTo(Session.class);
// Getting the current user
Authorizable auth = userManager.getAuthorizable(session.getUserID());
user = auth.getID();
password = ...
...
...
String serviceURL = (host.startsWith("http") ? "": protocol + "://") + host + url;
httpclient = HttpClients.custom().build();
HttpPost httppost = new HttpPost(serviceURL);
// set params
ArrayList<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
formparams.add(new BasicNameValuePair("username", user));
formparams.add(new BasicNameValuePair("password", password));
formparams.add(new BasicNameValuePair("client_id", clientID));
formparams.add(new BasicNameValuePair("client_secret",clientSecret));
formparams.add(new BasicNameValuePair("grant_type",grantType));
UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(postEntity);
// set header
httppost.addHeader("Authorization", authType);
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == 200) {
if (entity != null) {
object = new JSONObject(EntityUtils.toString(entity));
}
if (object != null) {
accessToken = object.getString("access_token");
////
}
}
}
I found the answer myself and thought I'd share the process I went through as well as the answer because it might help other people new to AEM.
How to find the cause of the error:
Go to CRXDE Lite.
Select console.
Then deselect the stop button to allow new console logs to appear (this is very counter-intuitive to me).
From here I was able to see the cause of the issue:
org.apache.sling.security.impl.ReferrerFilter Rejected empty referrer header for POST request to /oauth/token
Because postman does not place a referrer in the request header I had to tell Apache Sling to allow empty request headers.
To do this:
Go to /system/console/configMgr
Open the Apache Sling Referrer Filter Config
Select the Allow Empty check box
Good way to allow this to list the allowed hosts, otherwise this is against best practices for AEM security checklist.
Its fine for development environment not for production.

Resources