Using EWS API send email method get 401 unauthorized - outlook

I'm very new to EWS API. Now I've a problem when I Send Email using EWS sample. Still getting the error:
401 unauthorized.
Here is my sample code:
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new WebCredentials("user1#contoso.com", "password");
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl("user1#contoso.com", RedirectionUrlValidationCallback);
EmailMessage email = new EmailMessage(service);
email.ToRecipients.Add("user1#contoso.com");
email.Subject = "HelloWorld";
email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API");
email.Send();
The error in the email.Send() function. Any help for this?
Related link:https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/get-started-with-ews-managed-api-client-applications
I searched all links but no correct answer.

I've checked your provide link and not found any problem. In general, There is no problem in writing this way. The problem should be related to your server environment or account as wannadream mentioned.
You can refer to the following links:
"(401) Unauthorized" error when you use an EWS application to impersonate a user in Office365 Dedicated/ITAR
Exchange Web Service API and 401 unauthorized exception
Also, could you please change your account to test it?

Shot in the dark, but easy to try: several years ago I was getting unexplained 401s, and found some web post that mentioned adding an empty cookie container to the service object, i.e.:
service.CookieContainer = new CookieContainer();
It seemed to do the trick at the time, but not sure if it's still a thing.

Related

Error on returning message from bot (Forbidden)

I am creating a bot on facebook and as per the logs I am having , The message is reaching the bot but when the bot is responding I am getting the below error
"System.UnauthorizedAccessException: Authorization for Microsoft App ID failed with status code Forbidden at Microsoft.Bot.Connector.JwtTokenRefresher.d__2.MoveNext()"
I tried on facebook/skype and it's the same error. I added message.From but still facing some issue.
Here is my message returning code.
Activity replyMessage = message.CreateReply();
replyMessage.Text = "Text";
replyMessage.TextFormat = "plain";
await connector.Conversations.ReplyToActivityAsync(replyMessage);
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
Have you registered the bot on the Bot Framework portal? If so, make sure that you are using the correct MicrosoftAppId and MicrosoftAppPassword in your project's web.config. The error you are having it seems an authentication issue, which basically means that your settings in the web.config are not the expected ones

Invalid grant when accessing Google API

I'm trying to invoke any of the Google API using "Service account" authorization access. I have downloaded ".pk2" file and activated "URL Shortener API" in Services tab of Google API console. Whenever I try to invoke any API (URL shortener or Adsense). I've got following exception -
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "invalid_grant"
}
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:303)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:323)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:345)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:526)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:287)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:836)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:412)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:345)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:463)
Below is code snippet -
HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
JsonFactory JSON_FACTORY = new JacksonFactory();
File privateKey = new File(ReportAdsense.class.getResource("mykey.p12").toURI());
GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId("my_valid_account_id#developer.gserviceaccount.com")
.setServiceAccountScopes(UrlshortenerScopes.URLSHORTENER)
.setServiceAccountPrivateKeyFromP12File(privateKey)
.build();
Urlshortener service = new Urlshortener.Builder(new NetHttpTransport(), JSON_FACTORY, null).setHttpRequestInitializer(credential).build();
UrlHistory history = service.url().list().execute();
First of all "Service account" will not work for Adsense, since it requires user authorization. Hence for Adsense you should use Oauth 2.0. When you are authorized first time using URL https://accounts.google.com/o/oauth2/token, copy-paste and hardcode your refresh token. Than you can use it to get access token, specify client_id, client_secret and your refresh_token to get new access token. Now access token can be used in your application.
Regarding your error, I have faced with similar issue and spent plenty of time to resolve it. First of all, make sure that you are using valid ServiceAccountId - it should point to email which finishes with "developer.gserviceaccount.com". Make sure, that you specified account scopes and activated services in Google Console API.
I fixed this issue by synchronizing system clock in my machine.
There are a lot of topics with similar error without answers. Even more, some people says, that sometimes it works, sometimes it returns invalid grant. It could work on one machine and fail on another. I don't know if it is system clock issue, but I would avoid using Service Account API, since looks like there are bugs and support would not help you

GoogleConntectionFactory can't create connection

G'day everybody!
I've got error like this:
WARN/DefaultRequestDirector(22739): Authentication error: Unable to respond to any of
these challenges: {authsub=WWW-Authenticate: AuthSub
realm="https://www.google.com/accounts/AuthSubRequest" allowed-
scopes="https://www.googleapis.com/auth/userinfo.email,
https://www.googleapis.com/auth/userinfo.profile,
https://www.googleapis.com/auth/userinfo.id"}
It's happend when I wanna get connection:
AccessGrant accessGrant = new AccessGrant(accessToken);
Connection<Google> connection = connectionFactory.createConnection(accessGrant);
As the result, I catch exception as Auth 401.
Did any one that problem befor?
It looks like you are using the old AuthSub authentication when you should be using OAuth2 authentication. I suggest you take a look at the example application, specifically see in SocialConfig how to create ProviderSignInController which is used for sign in.
I've found why it was happened. The problem was in scope. I set only https://www.googleapis.com/auth/plus.me scope. It wasn't enough for create connection.
As result, I had the next message:
WARN/DefaultRequestDirector(22739): Authentication error: Unable to respond to any of
these challenges: {authsub=WWW-Authenticate: AuthSub
realm="https://www.google.com/accounts/AuthSubRequest" allowed-
scopes="https://www.googleapis.com/auth/userinfo.email,
https://www.googleapis.com/auth/userinfo.profile,
https://www.googleapis.com/auth/userinfo.id"}
As you can see google oauth2 asks for https://www.googleapis.com/auth/userinfo.email, https://www.googleapis.com/auth/userinfo.profile, https://www.googleapis.com/auth/userinfo.id scopes.
After I had added this scopes and I got a new error likes "invalid_scope".
Problem was in connection url.
I created connection url as:
connectionFactory.getOAuthOperations().buildAuthorizeUrl(GrantType.AUTHORIZATION_CODE, params);
where params:
OAuth2Parameters params = new OAuth2Parameters();
params.setRedirectUri(redirectUri);
params.setScope("https://www.googleapis.com/auth/userinfo.email+" + "https://www.googleapis.com/auth/userinfo.profile+" + "https://www.googleapis.com/auth/userinfo.id+" +
"https://www.googleapis.com/auth/plus.me");
In this case, symbol "+" was decoded to another one and Google oauth2 api couldn't recognize scope set.
I hope this solution will help somebody in future.

gdata SetAuthenticationToken() - 403 forbidden

I am just trying to get list of Albums in a web app using following c# code.
For AccessToken, I wen to OAuthPlaygound and generated an accessToken
with Picasa in scope using valid consumer key and password which relevant to my web application.
Issue :When I execute following code, I get 403 forbidden error along with message as "Invalid Token" error on last line if I use SetAuthenticationToken() option.
However, if I use setUserCredentialss(), it works. Could anyone please
help me in this? Is it that token generated using OAuth Playground
doesn't work here? Or to use client library token should also be geenrated using it? Is there any workaround?
PicasaService service = new PicasaService("codesamples.google.com");
service.SetAuthenticationToken(accessToken); //Doesn't works
//service.setUserCredentials("myUsername", "myPassword"); //Works
AlbumQuery query = new AlbumQuery(PicasaQuery.CreatePicasaUri(username));
PicasaFeed feed = service.Query(query);

Why do I get 401 errors connecting to the Dynamics CRM Metadata service?

I am connecting to CRM with the intention of retrieving a list of picklist values. On my development machine I am working under my own login name and all works fine. On the test server, the code executes under the NETWORK SERVICE account. When it connects to the CRM web service everything is great. When it connects to the metadata service I get 401 Unauthorised messages.
This is the first time I have used the metadata service so I am hoping someone can tell me why I get the error. The connection is configured using the code below and the failure happens when you try to retrieve the picklist data.
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.OrganizationName = config.AppSettings.Settings["CrmTargetOrganisation"].Value;
token.AuthenticationType = 0;
MetadataService service = new MetadataService();
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
service.Url = config.AppSettings.Settings["CrmMetadataServiceUrl"].Value;
service.CrmAuthenticationTokenValue = token;
service.UnsafeAuthenticatedConnectionSharing = true;
I suspect it might be a Kerberos / delegation issue, to make sure it is try replacing DefaultCredentials with
new System.Security.Net.NetworkCredentials("username","password","domain");
See if that still gives you a 401.
This is the quick way I normally try to see if it is kerbos/security related.
I need a bit more information about your environment to make any other intelligent comments.
Hope it helps.
In my case (yes, we still use CRM 4), the website in IIS wasn't bound to the hostname being used to access the metadata service on port 5555.

Resources