How to validate credentials in EWS Java API - exchange-server

I am using EWSJavaAPI 1.1.5. I am trying to login with invalid credentials, but I don't get any exceptions.
Please advise how to detect and handle invalid login.
Here is my code:
String host = "myhost";
ExchangeService service = null;
try {
service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials("wrongemail",
"wrongpass");
service.setCredentials(credentials);
service.setUrl(new java.net.URI("https://" + host
+ "/EWS/Exchange.asmx"));
} catch (Exception e) {
e.printStackTrace();
}

Found it, i had to bind the service to a folder:
Folder.bind(service, WellKnownFolderName.Inbox);
and if the credentials are wrong, HttpErrorException is thrown.

Related

Can't seem to send email with jhipster application

I'm trying to make a simple form that when submited sends and email to a fixed email.
I'm using spring and i've searched on how to configure the application.yml and i'm using the mailsend method that seems to have been generated with my jhipster application.
I've built my FE service to connect to the back end :
sendForm(): Observable<any>{
return this.http.post(SERVER_API_URL + 'api/sendForm', "");
}
i've built the onsubmit method to make the subscribe to the method above:
onSubmit() {
this.auth.sendForm().subscribe( data => {
console.log(data);
})
}
i've hard coded the mail resource just to mock an email to make sure its working:
#PostMapping("/sendForm")
public void sendForm() {
this.mailService.sendEmail("mymail#gmail.com","Header","texto",false,true);
}
the sendMail method that im sending the information for the mail submition is autogenerated and I believe it should be working
#Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
isMultipart, isHtml, to, subject, content);
// Prepare message using a Spring helper
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name());
message.setTo(to);
message.setFrom(jHipsterProperties.getMail().getFrom());
message.setSubject(subject);
message.setText(content, isHtml);
javaMailSender.send(mimeMessage);
log.debug("Sent email to User '{}'", to);
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.warn("Email could not be sent to user '{}'", to, e);
} else {
log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
}
}
}
and heres my application-dev.yml (i'm still on dev)
spring:
profiles:
active: dev
mail:
host: smtp.gmail.com
port: 587
username: gmailuserid#gmail.com #Replace this field with your Gmail username.
password: ************ #Replace this field with your Gmail password.
protocol: smtp
tls: true
properties.mail.smtp:
auth: true
starttls.enable: true
ssl.trust: smtp.gmail.com
the errors im getting goes as follows:
org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localh
ost, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect. Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeo
ut -1;
All I expect is a mail with the mock i've used and I cant seem to be able to put this working.
I hope i've not made the post to long and that everything is well explained.
Thank you in advance for anyone willing to help
Apparently somewhy the properties-prod.yml wasnt being loaded to the server. I had to create a config file with all the configurations for it to work

SSH.NET does not capture exception message

We are using Cerberus FTP server. And for the client I am using SSH.NET library to connect to server and upload a file. I was able to connect and upload files to FTP server without issue most of the time.
However when destination path does not exists on the FTP server, the SSH.NET library throws exception as expected. However Exception's Message property is empty.
var sftpClient = new SftpClient(host,username,password);
sftp.connect();
var destination = "SomeInvalidPath\myfile.txt"
using (var fs = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read))
{
try
{
sftp.UploadFile(fs, destination);
}
catch (Exception ex)
{
// ex.Message is empty ???
Logger.Current.Error(ex, "Error while FTP");
}
}
Not sure if this SSH.NET library issue or FTP server needs to propagate errors back to client?
Update 1
Stack trace
" at Renci.SshNet.Sftp.SftpSession.RequestOpen(String path, Flags
flags, Boolean nullOnError)\r\n at
Renci.SshNet.SftpClient.InternalUploadFile(Stream input, String path,
Flags flags, SftpUploadAsyncResult asyncResult, Action1
uploadCallback)\r\n at Renci.SshNet.SftpClient.UploadFile(Stream
input, String path, Action1 uploadCallback)\r\n at XXXXXX

SFTP error : com.jcraft.jsch.JSchException: invalid server's version string

I have the below code to SFTP to a location
public static void putFile(String username, String host, String password, String remotefile, String localfile){
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession(username, host, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.put(localfile, remotefile);
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
}
I am able to SFTP the document from my local machine using the above code. However when I am trying from a different environment to SFTP to the same location I am getting the follow error.
com.jcraft.jsch.JSchException: invalid server's version string at
com.jcraft.jsch.Session.connect(Session.java:253)
Note : I am using jsch-0.1.31.jar file.
on printing out session.getClientVersion() I am getting "SSH-2.0-JSCH-0.1.31".
I tried to upgrade the jar file to jsch-0.1.51.jar then session.getClientVersion() = "SSH-1.5-JSCH-0.1.51" and I am getting the following error
com.jcraft.jsch.JSchException: Session.connect: java.net.SocketException: Connection reset at com.jcraft.jsch.Session.connect(Session.java:558)
Please can you help me on what parameters should I be looking into and what is causing it to run from my local machine and upload to the same SFTP location and not from other environment?
As noted by #Kenster, the exception is about server's version string, not client's. The "invalid server's version string" exception is thrown by following code in Session.connect:
if(i==buf.buffer.length ||
i<7 || // SSH-1.99 or SSH-2.0
(buf.buffer[4]=='1' && buf.buffer[6]!='9') // SSH-1.5
){
throw new JSchException("invalid server's version string");
}
First, I would try to connect with some client that logs the version string and see yourself. For example with WinSCP, search its log for a pattern like:
. 2014-09-03 17:01:20.596 Server version: SSH-2.0-OpenSSH_5.3
(I'm the author of WinSCP)
Though possibly it's not about version string at all. I would rather believe the error raised by the new version, the Connection reset. The old version may fail to detect that the connection was aborted prematurely and tries to validate some random or incomplete data.
The Connection reset may indicate wide variety of different errors
Server refusing a connection from the other location
Some firewall or proxy not allowing the connection to pass through

How to authenticate UpgradeableApp API for migrating Google Apps Marketplace Apps from v1 to v2?

we are using https://www.googleapis.com/appsmarket/v2/upgradableApp to migrate the oauth1.0 app to oauth2.0 app.
We are referring to https://developers.google.com/apps-marketplace/v1migratev2
while making the call we are getting "Invalid OAuth Header" error (401)
We are using consumer key and consumer secret alone. we are not using any token.
I am sure that we are missing something here. But not sure what it is. Any pointers to this issue will help us.
Thanks in advance.
Here is the sample code
HttpClient client = new HttpClient();
PutMethod method = new PutMethod("https://www.googleapis.com/appsmarket/v2/upgradableApp///");
method.addRequestHeader("Authorization", "oAuth");
method.addRequestHeader("Consumer Key","");
method.addRequestHeader("Consumer Key Secret","");
try {
int status = client.executeMethod(method);
System.out.println("status:" + status);
System.out.println("response:" + method.getResponseBodyAsString());
}
catch (HttpException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
Result :
status:::401
response::{"error":{"errors":[{"domain":"global","reason":"authError","message":"Invalid OAuth > header","locationType":"header","location":"Authorization"}],"code":401,"message":"In
valid OAuth header"}}
We tried with the following code using OAuth 1.0 API for Google and it worked fine.
OAuthRequest request = new OAuthRequest(Verb.PUT, api.getUpdateDomainEndpoint(listingId, chromeWSId, domain));
request.addOAuthParameter(OAuthConstants.TIMESTAMP, api.getTimestampService().getTimestampInSeconds());
request.addOAuthParameter(OAuthConstants.NONCE, api.getTimestampService().getNonce());
request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, config.getApiKey());
request.addOAuthParameter(OAuthConstants.SIGN_METHOD, api.getSignatureService().getSignatureMethod());
request.addOAuthParameter(OAuthConstants.VERSION, getVersion());
request.addOAuthParameter(OAuthConstants.SIGNATURE, getSignature(request, token));
String oauthHeader = api.getHeaderExtractor().extract(request);
request.addHeader(OAuthConstants.HEADER, oauthHeader);

How can I open a facebook.session with access token and permissions in android?

How can I open a session with the specified permission?
I open a com.facebook.Session with API Session#openActiveSessionWithAccessToken() in an android.app.Service.
And then the opened session is used to get me/friendrequests by sending a request.
It results in an error as below:
{HttpStatus: 403, errorCode: 289, errorType: OAuthException, errorMessage: (#289) Requires extended permission: read_requests} ;
The permissions retrieved by using mSession.getPermissions() before creating the requests are as follows:
[read_requests, read_mailbox, manage_notifications]
Could you tell me what's wrong with my code?
Or could you tell me what should I do?
Code:
private static final List<String> PERMISSIONS = Arrays.asList("read_requests", "read_mailbox", "manage_notifications");
....
AccessToken token =
AccessToken.createFromExistingAccessToken(mAccount.getAccessToken(), new Date(mAccount.getExpireTime()), null,
AccessTokenSource.CLIENT_TOKEN, PERMISSIONS);
mSession = Session.openActiveSessionWithAccessToken(mContext, token, new StatusCallback(){
#Override
public void call(Session aSession, SessionState aState, Exception aException) {
if (aException != null) {
Log.i(Log.Tag.OTHER, TAG + "#createSession#call " + aException.getMessage());
}
//getNewInfos();
}
});
I have solved this problem.

Resources