Send array string with post httpClient ionic - web-services

I want to send params and recive another ones, and I got an issue with my method to sending these parametres (array of string and string) with post method of HttpClient in ionic.
The error (isn't the CORS Security, cause i run with my device too and i got the same issue):
Failed to load resource: the server responded with a status of 404 (Not Found).
Access to XMLHttpRequest at 'http://localhost:64411/getLabels' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
My code from ionic:
var apiURL = 'http://localhost:64411/';
pathGetLabels: string = apiURL + 'getLabels';
constructor(public http: HttpClient, public material: MaterialProvider, public hp : Http) {
}
loadLabels(lbls: any){
return this.http.post(this.pathGetLabels, lbls ,Language);}
The array got no problems and this is:
Array(6)
0: "USER"
1: "Password"
2: "SaveAccount"
3: "lbl_login"
4: "ForgetPass"
5: "Register"
length: 6
And the code of Web Service Api Rest:
[Route("getLabels/{paramOne}/{paramTwo}")]
public HttpResponseMessage getLabels([FromBody]string[] paramOne, string idL)
{
var labels = LanguagesRepository.GetLabels(paramOne, idL);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, labels);
return response;
}
I tried to do these things to and I got the same issue:
return this.http.get(this.pathGetLabels+ JSON.stringify(lbls) +"/"+Language);
return this.http.get(this.pathGetLabels+ JSON.stringify(lbls), Language);

Related

HTTP session is not maintained between two localhosts (gwt/react client running on port 3000, local tomcat server running on 8080) bcz of CORS domain?

Did anybody faced the above issue, CORS cookie is not getting stored in the browser even after enabling the CORS on the server-side to accept the preflight request and return as accepted on the very first call. All the requests originate from clients who always hit the servers with a new HTTP session id. I felt like enabling the CORS works only against the secured domain like HTTPS, not HTTP.
I have verified the first request and response headers, the response has the proper JSESSIONID is passed as the Set-Cookie value. But the subsequent requests were not referencing this cookie.
solution 1: add this bean
#Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowCredentials(true);
configuration.setAllowedMethods(Arrays.asList("GET", "POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
solution 2: add this to your controller
#CrossOrigin(origins = { "http://localhost:3000" })
**like this:**
#CrossOrigin(origins = { "http://localhost:3000" })
public class RoleController {
#Autowired
private RoleService roleService;
}

AWS Cognito TOKEN endpoint fails to convert authorization code to token

My app first uses the Cognito LOGIN endpoint to obtain an Authorization Code. It then uses the TOKEN endpoint to try and obtain tokens (id_token, access_token, refresh_token) but that fails with unauthorized_client.
I do not understand why, the same client is used to access the LOGIN, and that succeeded in returning an authorization code. I'm following the documentation for the TOKEN endpoint
string clientId = ...
string clientSecret = ...
Uri redirectUri = new Uri("myapp://myhost");
string authorization_code = ... // obtained via HTTP GET on LOGIN endpoint
string accessTokenUrl = "https://<domain>.auth.<region>.amazoncognito.com/oauth2/token";
var queryValues = new Dictionary<string, string>
{
{ "grant_type", "authorization_code" },
{ "code", authorization_code },
{ "redirect_uri", redirectUri.AbsoluteUri },
{ "client_id", clientId},
};
using (HttpClient client = new HttpClient())
{
// Authorization Basic header with Base64Encoded (clientId::clientSecret)
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}",
clientId,
clientSecret))));
// Url Encoded Content
var content = new FormUrlEncodedContent(queryValues);
// HTTPS POST
HttpResponseMessage response = await client.PostAsync(accessTokenUrl, content).ConfigureAwait(false);
string text = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
// test = {"error" : "unauthorized_client"}
}
The problem is two-fold:
1- System.Uri.AbsoluteUri adds a trailing / in the returned string so that my redirectUri becomes myapp://myhost/ instead of myapp://myhost
2- AWS Cognito TOKEN endpoint does not accept trailing / in a redirectURI.
The solution:
I now call redirectUri.OriginalUri instead of redirectUri.AbsoluteUri where I build the query to preserve the redirectUri as it was when I built it.
(I don't really have control over this since in my case Xamarin.Auth.OAuthAuthenticator2 calls Uri.AbsoluteUri on my behalf and transforms the redirectUri string I gave it, so I'm going to have to fix Xamarin.Auth).

Call HTTP (non SSL/HTTPS) REST from Firebase hosted site, using XMLHttpResponse

I am trying to build a Firebase hosted page that will connect to a (Django) HTTP web service using XMLHttpRequest in the below script.
<script>
function UserAction() {
var req = createRequest(); // defined below
// Create the callback functions:
var handleResponse = function (status, response) {
alert("status " + status + " response: " + response)
}
var handleStateChange = function () {
switch (req.readyState) {
case 0 : // UNINITIALIZED
case 1 : // LOADING
case 2 : // LOADED
case 3 : // INTERACTIVE
break;
case 4 : // COMPLETED
alert("case 4" + req.responseType);
handleResponse(req.status, req.responseJson);
break;
default: alert("error");
}
}
req.onreadystatechange = handleStateChange;
req.open("GET", "https://foo.org:/bar/getid/?Id=" + document.getElementById('ID').value, true);
req.send();
function createRequest() {
var result = null;
if (window.XMLHttpRequest) {
// FireFox, Safari, etc.
result = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
// MSIE
window.alert("windows");
result = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
// No known mechanism -- consider aborting the application
window.alert("no known mechanism");
}
return result;
}
}</script>
Using Chrome FireBase throws 404 error. Django server does not register any connection.
Using FireFox FireBase throws 404 error. But Django server throws
'code 400, message Bad HTTP/0.9 request type ('\x16\x03\x01\x00\xcc\x01\x00\x00\xc8\x03\x03\xdf\x04{\x9f\xe4\xb2\xc2ij\x8d\x14\xd5\xaa\xdcu\x14+&\xa4\xa1\xdf\xdc\xd8\x9b?\xea\xbdh\xb8')`
I did find this in the FireBase documentation here, making me think this is not possible. But hopefully I am wrong, or there is a way to do this in development/test, but not production.
SSL only: Firebase Hosting is SSL-only, meaning that content will only
be served over HTTPS. As you are developing your application make sure
that all external resources not hosted on Firebase Hosting are loaded
over SSL (HTTPS), including any external scripts. Most browsers do not
allow users to load "mixed content" (SSL and non-SSL traffic).
thanks

Jersey filter giving server error

I am using jersey filter.
In My code logic in AuthenticationFilter.java, if the authorization header is empty, then return the access denied error message.
First time I am hitting the application through rest client tool using the URL without attaching the header
http://localhost:8080/JerseyDemos2/rest/pocservice
Get the status 401 with error message "you cannot access this resource". This is right.
When i tried to hit second time thorugh rest client tool, and server return the exception message.
I deployed my application in tomcat 7.x both windows and linux
Why it give the error when we hit the second time.
How to resolve this
#Provider
public class AuthenticationFilter implements javax.ws.rs.container.ContainerRequestFilter {
#Context
private ResourceInfo resourceInfo;
private static final String AUTHORIZATION_PROPERTY = "Authorization";
private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED).entity("You cannot access this resource").build();
#Override
public void filter(ContainerRequestContext requestContext) {
// Get request headers
final MultivaluedMap<String, String> headers = requestContext.getHeaders();
// Fetch authorization header
final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY);
// If no authorization information present; block access
if (authorization == null || authorization.isEmpty()) {
requestContext.abortWith(ACCESS_DENIED);
return;
}
}
} }
Error message:
Dec 19, 2016 6:26:18 PM org.glassfish.jersey.server.ServerRuntime$Responder writeResponse
SEVERE: An I/O error has occurred while writing a response message entity to the container output stream.
java.lang.IllegalStateException: The output stream has already been closed.
at org.glassfish.jersey.message.internal.CommittingOutputStream.setStreamProvider(CommittingOutputStream.java:147)
at org.glassfish.jersey.message.internal.OutboundMessageContext.setStreamProvider(OutboundMessageContext.java:803)
......
Please help me
Thanks in advance.
I Removed static variable
private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED).entity("You cannot access this resource").build();
and i declared local variable. now its working fine.
#Provider
public class AuthenticationFilter implements javax.ws.rs.container.ContainerRequestFilter {
#Context
private ResourceInfo resourceInfo;
private static final String AUTHORIZATION_PROPERTY = "Authorization";
#Override
public void filter(ContainerRequestContext requestContext) {
Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED).entity("You cannot access this resource").build();
// Get request headers
final MultivaluedMap<String, String> headers = requestContext.getHeaders();
// Fetch authorization header
final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY);
// If no authorization information present; block access
if (authorization == null || authorization.isEmpty()) {
requestContext.abortWith(ACCESS_DENIED);
return;
}
}
} }
You're trying to write in a response that was written before. The full log shows where is it happening. Upload the log and the code where the httpresponse is used/modified.

Can't get a response at CORS request

I have the following Javascript code to make a XMLHttpRequest to a server:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
return xhr;
}
function makeCorsRequest(word) {
var url = "https://localhost:8080/Method/Dictionary/" + word;
var xhr = createCORSRequest('GET', url);
xhr.onload = function() {
var responseText = xhr.responseText;
document.querySelector("#bar").innerHTML = responseText;
};
xhr.onerror = function() {
document.querySelector("#bar").innerHTML = 'Connection not allowed';
};
xhr.send();
}
makeCorsRequest("word");
At the server, I've got a REST structure (written using Jersey) similiar to:
#Path("/Dictionary")
public class Main{
public Definition returnDefinition(String word){
Definition definition = new Definition();
try{
...//play with Definition object
return definition;
}
catch(IOException IOE){
...
return definition;
}
}
#Path("{word}")
#GET
#Produces("text/xml ; charset=UTF-8") //"Definition" is already set as a XMLRoot element
public Definition main (#PathParam("word") String word){
return returnDefinition(word);
}
}
I try to make this request in two environments:
First environment: The JS code is inside a normal web page. In this case, I receive the following error after trying to make the request:
XMLHttpRequest cannot load http://localhost:8080/Method/Dictionary/word. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Second environment: The JS code is inside a content script (that is itself inside a chrome extension). In this case, after about 30s of trying to make the request, I receive this:
Failed to load resource: net::ERR_TIMED_OUT
How to proceed?
EDIT: I've added a command to print something at the console in the beginning of the server method. And it is not printed. So, the requests are not reaching the server.
Origin 'null' happens if you are running the page as a file in the browser, using the file:// protocol, rather than set it up in a local webserver and access it using http://.