Spring MVC returns 405 for api call made from my android client - spring-mvc

I have an android app which is making api requests to my server running Spring MVC. The RestController works fine when I make a request from the browser but it responds with 404 when I am making requests from android. Not sure why
Here is code snippet from Android app making requests
public class AsyncFetch extends AsyncTask<Pair<String, String>, String, String> {
public ProgressDialog pdLoading;
private HttpURLConnection conn;
private String urlStr;
private String requestMethod = "GET";
public AsyncFetch(String endpoint, Context ctx)
{
pdLoading = new ProgressDialog(ctx);
Properties reader = PropertiesReader.getInstance().getProperties(ctx, "app.properties");
String host = reader.getProperty("host", "10.0.2.2");
String port = reader.getProperty("port", "8080");
String protocol = reader.getProperty("protocol", "http");
String context = reader.getProperty("context", "");
this.urlStr = protocol+"://"+host+":"+port+context+endpoint;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(Pair<String, String>... params) {
URL url;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod(requestMethod);
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made`enter code here`
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
Spring MVC Controller
#RestController
public class ApiController {
#RequestMapping(value = "homefeed", method=RequestMethod.GET)
public String homefeed(#RequestParam(value="userId", required = false) Integer id, #RequestParam(value="search", required = false) String search, #RequestParam(value="page", required = false, defaultValue = "0") Integer page) { ... }
}
localhost:8080/api/homefeed -- works
127.0.0.1:8080/api/homefeed -- works
My Public IP:8080/api/homefeed -- does not works
10.0.2.2:8080/api/homefeed -- android emulator to localhost -- does not work
10.0.2.2:8080/Some resource other than the api endpoint -- works
Any help is highly appreciable, have wasted quiet some time in debugging.

Related

Problem to execute https connection from a servlet: http 404 error occours

From my Tomcat's servlet I execute an https connection to an external servlet.
This is the code:
HttpsURLConnection hpcon = null;
try {
URL url = new URL(surl);
hpcon = (HttpsURLConnection) url.openConnection();
hpcon.setRequestMethod("POST");
hpcon.setDoInput(true);
hpcon.setDoOutput(true);
hpcon.setUseCaches(false);
hpcon.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
OutputStreamWriter wr = new OutputStreamWriter(hpcon.getOutputStream());
String params = "user=" + URLEncoder.encode(user, "UTF-8");
params += "&psswd=" + URLEncoder.encode(pssw, "UTF-8");
params += "&metodo=" + URLEncoder.encode(metodo, "UTF-8");
wr.write(params);
wr.flush();
wr.close();
hpcon.connect();
int respCode = hpcon.getResponseCode();
if (respCode == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(hpcon.getInputStream()));
String response = "";
String output;
while ((output = br.readLine()) != null) {
response += output;
}
if (response.indexOf("-") > 0) {
response = "-12";
System.out.println("ret = -12 - response = " + response);
}
br.close();
} else {
ret = "-11";
System.out.println("ret = -11 - respCode = " + respCode);
}
} catch (Exception e) {
e.printStackTrace();
ret = "-10";
System.out.println("ret = -10");
} finally {
if (hpcon != null) {
hpcon.disconnect();
}
}
Where surl is the full url of a servlet present in a different domain and the three parameters are read from a db table (the third really is fixed and is the operation that is make by the external servlet).
The result is:
ret = -11 - respCode = 404
Before make the connection I turn off the certificate's verify using the above code:
try {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (Exception e) {
e.printStackTrace();
}
If I execute the same servlet manually from a browser with parameters in get mode all run correctly.
I tried to execute it on my code using the get mode and passing the three parameters in query string, but the result is the same.
How can I do to resolve the problem?

Spring ws Unauthorized [401]

I'm trying to consume a soap service. The service has no certificate, but receives as a property of the request username and password.
but I'm getting the following error:
org.springframework.ws.client.WebServiceTransportException: Unauthorized [401]
I tried in several ways to pass the username and password.
Using the soapui I was able to make the requisition. In soapui I pass the username and password through request properties.
#Bean
Jaxb2Marshaller jaxb2Marshaller() {
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setPackagesToScan("ce.gov.s2gpr.compras.licita.business.model.service.bean");
return jaxb2Marshaller;
}
#Bean
public WebServiceTemplate webServiceTemplate() {
WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
webServiceTemplate.setMarshaller(jaxb2Marshaller());
webServiceTemplate.setUnmarshaller(jaxb2Marshaller());
webServiceTemplate.setDefaultUri(defaultUri);
HttpsUrlConnectionMessageSender sender = new HttpsUrlConnectionMessageSender();
sender.setTrustManagers(new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
});
webServiceTemplate.setMessageSenders(new WebServiceMessageSender[]{sender, httpComponentsMessageSender()});
return webServiceTemplate;
}
#Bean
public HttpComponentsMessageSender httpComponentsMessageSender() {
HttpComponentsMessageSender httpComponentsMessageSender = new HttpComponentsMessageSender();
httpComponentsMessageSender.setConnectionTimeout(timeout);
httpComponentsMessageSender.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);
httpComponentsMessageSender.setReadTimeout(timeout);
httpComponentsMessageSender.setCredentials(new UsernamePasswordCredentials(userName, userPassword));
return httpComponentsMessageSender;
}
I tried in several ways to pass the username and password, but I received the same error.
#SuppressWarnings("unchecked")
public AtualizacaoItensGruposResponse testeSoap(PgeTO dto) {
ObjectFactory factory = new ObjectFactory();
AtualizacaoItensGrupos itens = factory.createAtualizacaoItensGrupos();
itens.setArg0(dto);
JAXBElement<AtualizacaoItensGrupos> request = factory.createAtualizacaoItensGrupos(itens);
try {
WebServiceMessageCallback wsCallback = message -> {
TransportContext context = TransportContextHolder.getTransportContext();
WebServiceConnection connection = context.getConnection();
HttpUrlConnection conn = (HttpUrlConnection) connection;
conn.getConnection().setRequestProperty("Username", "");
conn.getConnection().setRequestProperty("Password", "");
conn.getConnection().setRequestProperty("username", "");
conn.getConnection().setRequestProperty("password", "");
conn.getConnection().addRequestProperty("Username", "");
conn.getConnection().addRequestProperty("Password", "");
conn.getConnection().addRequestProperty("username", "");
conn.getConnection().addRequestProperty("password", "");
conn.getConnection().addRequestProperty("s2gpr.integracao.cotacao.item_licitacao.webservice.user", "");
conn.getConnection().addRequestProperty("s2gpr.integracao.cotacao.item_licitacao.webservice.password", "");
};
webServiceTemplate.marshalSendAndReceive(request, wsCallback);
return null;
} catch (Exception e) {
log.error(e.getMessage());
throw new ClientLicitaWebException("Ocorreu um erro ao enviar as informações para o sistema LicitaWeb");
}
}

HttpModule Web Api

I'm trying to get an auth basic on my web api. I've written a simple HttpModule to check it
public class BasicAuth : IHttpModule
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
private const string Realm = "MyRealm";
public void Init(HttpApplication context)
{
// Register event handlers
context.AuthorizeRequest += new EventHandler(OnApplicationAuthenticateRequest);
context.EndRequest += new EventHandler(OnApplicationEndRequest);
}
private static void SetPrincipal(IPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
private bool CheckPassword(string username, string password)
{
var parameters = new DynamicParameters();
parameters.Add("#UserName", username);
parameters.Add("#Password", password);
con.Open();
try
{
var query = //query to db to check username and password
return query.Count() == 1 ? true : false;
}
catch
{
return false;
}
finally
{
con.Close();
}
}
private bool AuthenticateUser(string credentials)
{
try
{
var encoding = Encoding.GetEncoding("iso-8859-1");
credentials = encoding.GetString(Convert.FromBase64String(credentials));
int separator = credentials.IndexOf(':');
string name = credentials.Substring(0, separator);
string password = credentials.Substring(separator + 1);
if (CheckPassword(name, password))
{
var identity = new GenericIdentity(name);
SetPrincipal(new GenericPrincipal(identity, null));
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
private void OnApplicationAuthenticateRequest(object sender, EventArgs e)
{
var authHeader = request.Headers["Authorization"];
if (authHeader != null)
{
var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);
// RFC 2617 sec 1.2, "scheme" name is case-insensitive
if (authHeaderVal.Scheme.Equals("basic",
StringComparison.OrdinalIgnoreCase) &&
authHeaderVal.Parameter != null)
{
if (AuthenticateUser(authHeaderVal.Parameter))
{
//user is authenticated
}
else
{
HttpContext.Current.Response.StatusCode = 401;
}
}
else
{
HttpContext.Current.Response.StatusCode = 401;
}
}
catch
{
HttpContext.Current.Response.StatusCode = 401;
}
}
private static void OnApplicationEndRequest(object sender, EventArgs e)
{
var response = HttpContext.Current.Response;
if (response.StatusCode == 401)
{
response.Headers.Add("WWW-Authenticate",
string.Format("Basic realm=\"{0}\"", Realm));
}
}
public void Dispose()
{
}
}
well, this code works pretty well, except the fact it asks for basic auth even on controller I don't put the [Authorize] tag on. And when it occurs, it gives the right data back.
Let me explain:
My HistoryController has [Authorize] attribute, to make a POST request I have to send Header auth to get data, if I don't do it, I receive 401 status code and a custom error.
My HomeController doesn't have [Authorize] attribute, if i make a get request on my homepage, the browser popups the authentication request, but if I hit Cancel it shows my home page. (The page is sent back with 401 error, checked with fiddler).
What am I doing wrong?

SAML2 assertion encryption using public key (opensaml)

I've recently tried to encrypt Saml2 assertion using relaying-party service public key. Unfortunately I can't finalise even the test phase
here is my code
public class EncryptionTest {
public static void main(String args[]){
try {
// The Assertion to be encrypted
FileInputStream fis;
DataInputStream in, in2;
File f = new File("src/main/resources/AssertionTest");
byte[] buffer = new byte[(int) f.length()];
in = new DataInputStream(new FileInputStream(f));
in.readFully(buffer);
in.close();
//Assertion = DataInputStream.readUTF(in);
String in_assert = new String(buffer);
System.out.println(in_assert);
org.apache.axiom.om.OMElement OMElementAssertion = org.apache.axiom.om.util.AXIOMUtil.stringToOM(in_assert);
Assertion assertion = convertOMElementToAssertion2(OMElementAssertion);
// Assume this contains a recipient's RSA public key
Credential keyEncryptionCredential;
keyEncryptionCredential = getCredentialFromFilePath("src/main/resources/cert.pem");
EncryptionParameters encParams = new EncryptionParameters();
encParams.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);
KeyEncryptionParameters kekParams = new KeyEncryptionParameters();
kekParams.setEncryptionCredential(keyEncryptionCredential);
kekParams.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP);
KeyInfoGeneratorFactory kigf =
Configuration.getGlobalSecurityConfiguration()
.getKeyInfoGeneratorManager().getDefaultManager()
.getFactory(keyEncryptionCredential);
kekParams.setKeyInfoGenerator(kigf.newInstance());
Encrypter samlEncrypter = new Encrypter(encParams, kekParams);
samlEncrypter.setKeyPlacement(KeyPlacement.PEER);
EncryptedAssertion encryptedAssertion = samlEncrypter.encrypt(assertion);
System.out.println(encryptedAssertion);
} catch (EncryptionException e) {
e.printStackTrace();
} catch (CertificateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (KeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (XMLStreamException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
public static Credential getCredentialFromFilePath(String certPath) throws IOException, CertificateException, KeyException {
InputStream inStream = new FileInputStream(certPath);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(inStream);
inStream.close();
//"Show yourself!"
System.out.println(cert.toString());
BasicX509Credential cred = new BasicX509Credential();
cred.setEntityCertificate((java.security.cert.X509Certificate) cert);
cred.setPrivateKey(null);
//System.out.println(cred.toString());
return cred;
//return (Credential) org.opensaml.xml.security.SecurityHelper.getSimpleCredential( (X509Certificate) cert, privatekey);
}
public static Assertion convertOMElementToAssertion2(OMElement element) {
Element assertionSAMLDOOM = (Element) new StAXOMBuilder(DOOMAbstractFactory.getOMFactory(), element.getXMLStreamReader()).getDocumentElement();
try {
UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(Assertion.DEFAULT_ELEMENT_NAME);
return (Assertion) unmarshaller.unmarshall(assertionSAMLDOOM);
} catch (Exception e1) {
System.out.println("error: " + e1.toString());
}
return null;
}
}
I constantly recive Null pointer exception in
KeyInfoGeneratorFactory kigf =
Configuration.getGlobalSecurityConfiguration()
.getKeyInfoGeneratorManager().getDefaultManager()
.getFactory(keyEncryptionCredential);
kekParams.setKeyInfoGenerator(kigf.newInstance());
How can I set GlobalSecurityConfiguration or is there different approach of encrypting Assertion which will work?
This question was laying open for too long. The problem was initialization of OpenSaml.
Simple
DefaultBootstrap.bootstrap();
helped and solved problem.

How to create a web server? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I understand that there are already alot of web server out there.
But i feel like creating one for learning purpose.
Is it something i should try to figure out and any guides or tutorials on this?
In java:
Create a ServerSocket and have this continually listen for connections - when a connection request comes in handle it by by parsing the HTTP request header, get the resource indicated and add some header information before sending back to the client. eg.
public class Server implements Runnable {
protected volatile boolean keepProcessing = true;
protected ServerSocket serverSocket;
protected static final int DEFAULT_TIMEOUT = 100000;
protected ExecutorService executor = Executors.newCachedThreadPool();
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(DEFAULT_TIMEOUT);
}
#Override
public void run() {
while (keepProcessing) {
try {
Socket socket = serverSocket.accept();
System.out.println("client accepted");
executor.execute(new HttpRequest(socket));
} catch (Exception e) {
}
}
closeIgnoringException(serverSocket);
}
protected void closeIgnoringException(ServerSocket serverSocket) {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException ignore) {
}
}
}
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
try {
executor.execute(new WebServer(6789));
} catch (Exception e) {
e.printStackTrace();
}
}
}
final class HttpRequest implements Runnable {
final static String CRLF = "\r\n";
private Socket socket;
public HttpRequest(Socket socket) {
this.socket = socket;
}
public void run() {
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private void processRequest() throws Exception {
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
String requestLine = br.readLine();
System.out.println();
System.out.println(requestLine);
List<String> tokens = Arrays.asList(requestLine.split(" "));
Iterator<String> it = tokens.iterator();
it.next(); // skip over the method, which should be "GET"
String fileName = it.next();
fileName = "." + fileName;
FileInputStream fis = null;
boolean fileExists = true;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false;
}
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
String contentType = null;
if (fileExists) {
statusLine = "HTTP/1.0 200 OK";
contentType = contentType(fileName);
contentTypeLine = "Content-type: " + contentType + CRLF;
} else {
statusLine = "HTTP/1.0 404 NOT FOUND";
contentType = "text/html";
contentTypeLine = "Content-type: " + contentType + CRLF;
entityBody = "<HTML>" + "<HEAD><TITLE>Not Found</TITLE></HEAD>"
+ "<BODY>" + statusLine + " Not Found</BODY></HTML>";
}
os.writeBytes(statusLine);
os.writeBytes(contentTypeLine);
os.writeBytes(CRLF);
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes(entityBody);
}
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
os.close();
br.close();
socket.close();
}
private static void sendBytes(InputStream fis, DataOutputStream os)
throws Exception {
byte[] buffer = new byte[1024];
int bytes = 0;
while ((bytes = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytes);
}
}
private static String contentType(String fileName) {
if (fileName.endsWith(".htm") || fileName.endsWith(".html")) {
return "text/html";
}
if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
return "image/jpeg";
}
if (fileName.endsWith(".gif")) {
return "image/gif";
}
if (fileName.endsWith(".txt")) {
return "text/plain";
}
if (fileName.endsWith(".pdf")) {
return "application/pdf";
}
return "application/octet-stream";
}
}
A Simple Webserver in C++ for Windows
Hope this helps you ; )
Alternatives
This project contains a modular web server in CodePlex
This article explains how to write a simple web server application using C# from CodeGuru
Start with understanding TCP/IP and the whole Internet protocol suite.
Then learn the HTTP 1.0 and 1.1 protocols.
That should start you on the way to understanding what you need to write in order to create a webserver from scratch.
Try asio from boost!
Boost.Asio is a cross-platform C++ library for network and low-level I/O programming that provides developers with a consistent asynchronous model using a modern C++ approach.
Most scripting language are capable and have plenty of examples on writing web servers. This route will give you a gentle introduction.

Resources