Interact with a JSF application which use basic authentication programmatically - vb.net

I am having difficulties interacting with a website which use basic authentication to authenticate the user.
I am working on visual basic and i have already tried to use
Dim req As HttpWebRequest = HttpWebRequest.Create("http://url.to.website.com")
adding the headers directly to the web request:
req.Headers.Add("Authorization: Basic " & Convert.ToBase64String(Encoding.Default.GetBytes("user" & ":" & "password")))
or using the network credentials:
req.Credentials = New Net.NetworkCredential("user", "password")
receiving always the same response code: 401 Unauthorized
Using Firefox developer tools i can analyze and resend some web requests and only using Firefox i am able to authenticate correctly.
Firefox report these headers:
Host: url.to.website.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http.//url.to.website.com/portal/data/pub
DNT: 1
Authorization: Basic ZmFrZTpwYXNzd29yZA==
Connection: keep-alive
So i have tried to set it manaually this way:
req.Host = "url.to.website.com"
req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0"
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
req.Referer = "https://url.to.website.com/some/path/to/file.jsf"
req.ContentType = "application/x-www-form-urlencoded"
req.KeepAlive = True
req.PreAuthenticate = True
req.Method = "POST"
req.Headers.Add("Authorization: Basic " & Convert.ToBase64String(Encoding.Default.GetBytes("user" & ":" & "password")))
with no success (receiving always the same response code: 401 Unauthorized)
Another try was with a web-browser:
WebBrowser1.Navigate("url", Nothing, Nothing, "Authorization: Basic " & Convert.ToBase64String(Encoding.Default.GetBytes(AUTH_USER & ":" & AUTH_PASSWORD)))
My objective is to authenticate, then query some pages and collect responses in order to parse them and use it later in the application.
How can i solve the issue about authentication?
The website is written using JSF and i have no control over it.
Update:
My problem is about authentication, not yet about the jsf application.
While using Firefox all work fine (I can send a request to the website and it will authenticate me right) but while using the HttpWebRequest the authentication fails, even if I set the same headers, as Written before .
I have to figure out the difference between the two requests

I had to get this working for Dukes Forest Java EE Tutorial Port to Wildfly. The code was already written, but the header was case sensitive. Anyway, the code used there is as follows:
/* Client filter for basic HTTP auth */
class AuthClientRequestFilter implements ClientRequestFilter {
private final String user;
private final String password;
public AuthClientRequestFilter(String user, String password) {
this.user = user;
this.password = password;
}
#Override
public void filter(ClientRequestContext requestContext) throws IOException {
try {
requestContext.getHeaders().add(
"Authorization",
"Basic " + DatatypeConverter.printBase64Binary(
(user+":"+password).getBytes("UTF-8"))
);
} catch (UnsupportedEncodingException ex) { }
}
}
The DatatypeConverter is imported from javax.xml.bind. This code was called from the following routine, which has the HTTPClient:
Client client = ClientBuilder.newClient();
client.register(new AuthClientRequestFilter("jack#example.com", "1234"));
Response resp = client.target(ENDPOINT)
.request(MediaType.APPLICATION_XML)
.post(Entity.entity(order, MediaType.APPLICATION_XML), Response.class);
int status = resp.getStatus();
if (status == 200) {
success = true;
}
logger.log(Level.INFO, "[PaymentHandler] Response status {0}", status);
client.close();
return success;
This client code posts to a RESTful service.

Related

Model Binding returns null model

I have been unable to resolve an issue with Model Binding in an action.
It DOES bind, but not all of the time. Sometimes, the value is null and so of course it throws an error.
It seems to happen about 50% of the time, sometimes after the user has been logged in for a 4 minutes or longer.
This is the action:
[HttpPost]
public IActionResult Post([FromBody]Csr csr)
{
try
{
if(csr == null)
{
throw new Exception("Associate Controller recieved csr parameter when posting a new CSR");
}
//csr.ParentCsrId = this.GetCurrentCsr().CsrId;
csr.InsertedDate = DateTime.Now;
csr.UpdatedDate = DateTime.Now;
return Ok(_associateRepository.Add(csr));
}
catch (Exception ex)
{
LogException(ex, "Associate Controller", "Post([FromBody]Csr csr)");
throw ex;
}
}
The exception is thrown and logged correctly.
This is the data that was posted according to the browser:
Headers:
POST /api/associate HTTP/1.1
Host: portal.5-15globalenergy.it
Connection: keep-alive
Content-Length: 557
Accept: application/json
Origin: https://portal.5-15globalenergy.it
Authorization: Bearer xxxzy User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36
Content-Type: application/json
Referer: https://portal.5-15globalenergy.it/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Body:
{"csrTypeId":1,"countryId":2,"stateCode":"SO","birthCountryId":2,"birthStateCode":"SO","city":"Sondrio","streetPart":"STAZIONE","birthCity":"Sondrio","firstName":"Test","lastName":"User","maritalStatusId":2,"citizenshipCountryId":2,"personalTaxNum":"xxxxxx","streetName":"VIA SAN GOTTARDO","streetNum":"11","zip":"53216","landPhone":"231562145","mobilePhone":"231562145","email":"test#GMAIL.IT","bankAccountKey":"123625478325621","birthDate":"18/04/1969","orderStatusId":3,"streetCode":"","parentCsrId":"2130","syncStatusId":1,"languageId":3}
If there is an error in binding, is there a way to trap this?
I finally got this resolved. Here is the takeaway: If you get a null model, yet data was passed in the Web Request, it means that ModelBinding failed.
In my case, a misformatted date string could not be converted to a date. The result is the entire model is null, not just the data field.
The way to get the Errors is through the ModelState object. In my case, no error message was returned. But an Exception Object WAS returned.
Here is the code to concatenate it into a string:
string desc = "";
foreach (var modelState in ViewData.ModelState.Values)
{
foreach (var error in modelState.Errors)
{
if(!String.IsNullOrWhiteSpace(error.ErrorMessage))
desc = desc + " " + error.ErrorMessage.ToString();
if(error.Exception != null)
{
desc = desc + " Exception: " + error.Exception.ToString();
}
}
}

VBA ServerXMLHTTP proxy is fine with https but fails on http

I'm trying to write a macro to do some querying from the web to update an Access database. For some reason, VBA refuses to play friendly with http, but is totally content to do https.
Here's my requesting function:
Function httpRequest(ByVal url As String, useProxy As Boolean) As String
Dim response As String
Dim proxy As String
Dim xhr As Object
'Make HTTP requester object
Set xhr = CreateObject("MSXML2.ServerXMLHTTP.6.0")
If useProxy Then
If Left(url, 5) = "https" Then
proxy = "proxyb1secure:8443"
Else
proxy = "proxyb1:8080"
End If
xhr.setProxy 2, proxy
End If
xhr.Open "GET", url, False
'send the request. THIS LINE TIMES OUT ON HTTP
xhr.Send
'fetch the whole page
response = xhr.responseText
'clean up
Set xhr = Nothing
'return
httpRequest = response
End Function
And my testing function:
Function testProxy()
'This one works
MsgBox (httpRequest("https://www.bing.com/search?q=stackoverflow", True))
'This one doesn't.
MsgBox (httpRequest("http://www.bing.com/search?q=stackoverflow", True))
End Function
I'm certain I'm going after the right name and port, because I've tested the same thing via Java, and it's content to do both flavors (i.e. everything works perfectly in the following code).
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.bing.com/search?q=stackoverflow");
HttpURLConnection con = (HttpURLConnection) url.openConnection(getProxyForURL(url));
System.out.println(con.getResponseCode() + " " + con.getResponseMessage());
InputStream is = con.getInputStream();
int c;
StringBuilder sb = new StringBuilder();
while ((c = is.read()) != -1) {
sb.append((char) c);
}
String page = sb.toString();
System.out.println(page);
}
public static Proxy getProxyForURL(URL url) {
if (url.getProtocol().equals("https")) {
return new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyb1secure", 8443));
} else {
return new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyb1", 8080));
}
}
What trickery of VBA am I missing?
Mystery solved. Turns out this is a security feature revolving around the user agent (of all things...).
Java used these HTTP headers (which were successful):
GET http://www.bing.com/search?q=stackoverflow HTTP/1.1
Accept: */*
Accept-Language: en-us
Proxy-Connection: Keep-Alive
User-Agent: Java/1.7.0_79
Host: www.bing.com
and Access sent these (which were unsuccessful):
GET http://www.bing.com/search?q=stackoverflow HTTP/1.1
Accept: */*
Accept-Language: en-us
User-Agent: Mozilla/4.0 (compatible; Win32; WinHttp.WinHttpRequest.5)
Proxy-Connection: Keep-Alive
Host: www.bing.com
by simply adding a
xhr.setRequestHeader "User-Agent", "PayMeNoAttention"
it magically goes through. And to confirm the theory, adding Access' user-agent to Java caused it to fail. So. That's definitely what's up.
This is likely an attempt by our brilliant network techs to block macro viruses from contacting malicious sites.

WebAPI 2 with OWIN middleware and token-based authentication: OPTIONS request returns "unsupported_grant_type" error

WEbAPI provides end-point for authentication request: http:\...\token
Authentication request should be sent using Method "POST" and Body like
"grant_type=password&username=name&password=mypassword"
This WebAPI is used by Front-End which is written using AngularJS.
Sometimes before sending "POST" request with valid Body, a "OPTIONS" request is sent without Body.
As result the following error is returned by WebAPI:
Status: 400
{"error":"unsupported_grant_type"}
Is there any solution which can be implemented on Server-side? (in WebAPI)
HTTP Request Method: OPTIONS
Request Header:
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,de;q=0.6,ru;q=0.4,uk;q=0.2
Access-Control-Request-Headers:accept, authorization, content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Host:...
Origin:...
Pragma:no-cache
Proxy-Connection:keep-alive
Referer:...
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36
Response Header:
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 34
Content-Type: application/json;charset=UTF-8
Expires: -1
Server: Microsoft-IIS/7.5
Access-Control-Allow-Origin: *
X-Powered-By: ASP.NET
Date: Thu, 11 Sep 2014 18:05:09 GMT
I just ran into the same issue..I'm using ember and ember-simple-auth. Any preflight requests OPTIONS to the /token endpoint were resulting in a 400 HTTP response and the body had the well known: {error: "unsuported_grant_type"}.
SOLUTION:
I inherit from: OAuthAuthorizationServerProvider and override the MatchEndpoint function:
public override Task MatchEndpoint(OAuthMatchEndpointContext context)
{
if (context.OwinContext.Request.Method == "OPTIONS" && context.IsTokenEndpoint)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] {"POST"});
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "accept", "authorization", "content-type" });
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
context.OwinContext.Response.StatusCode = 200;
context.RequestCompleted();
return Task.FromResult<object>(null);
}
return base.MatchEndpoint(context); }
That seems to take care of it. Hope it helps.
I got the same error when I forgot to add Content-Type: application/x-www-form-urlencoded to the request header.
I was attempting to test my api with Fiddler and wasn't providing the data in the correct format in the Request Body section. Be sure it's added as a key value list separated by '&'.
grant_type=password&username=testUsername&password=testPassword
In this case OPTIONS is a CORS preflight request. It is sent in order to determine whether the actual request (POST) is safe to send. Cross-site requests are preflighted if uses methods other than GET, HEAD or POST or sets custom headers.
In order to avoid a 400 HTTP response, in your Startup class you should enable CORS for the OWIN middleware using UseCors extension method and define your custom System.Web.Cors.CorsPolicy.
using Microsoft.Owin.Cors;
using Microsoft.Owin.Security.OAuth;
using Owin;
namespace AuthorizationServer
{
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions()
{
});
}
}
}

Metro client hangs when calling WCF webserver with wsHttpBinding

I have generated a webservice client with a local wsdl using Metro 1.2 this way:
./wsimport.sh -extension -verbose -wsdllocation service.wsdl -s src -d target service.wsdl -Xendorsed
The wsdl uses SOAP 1.2 and wsHttpBinding. It's supposed to connect to a WCF server that's using NTLM as authentication method.
I have created an Authenticator to handle the NTLM authentication:
public class NtlmAuthenticator extends Authenticator
{
private String username = "";
private String password = "";
public NtlmAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
}
Which I set before each webservice method is called:
#WebEndpoint(name = "WSHttpBinding_ICustomerService")
public ICustomerService getWSHttpBindingICustomerService() {
ICustomerService service =
super.getPort(new QName("http://xmlns.example.com/services/Customer",
"WSHttpBinding_ICustomerService"), ICustomerService.class);
NtlmAuthenticator auth = new NtlmAuthenticator(username, password);
Authenticator.setDefault(auth);
return service;
}
If I use the wrong username/password, I get a 401 Unauthorized back, which is well and all, but when I use the correct username/password, the call hangs and I never get a response!
The request looks like this (captured it with netcat, so host is different, and no https):
POST / HTTP/1.1
Content-type: application/soap+xml;charset="utf-8";action="http://xmlns.example.com/services/ICustomerService/GetCustomer"
Password: [password]
Authorization: Basic [auth]
Username: [username]
Accept: application/soap+xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
User-Agent: JAX-WS RI 2.1.7-b01-
Cache-Control: no-cache
Pragma: no-cache
Host: localhost:5500
Connection: keep-alive
Content-Length: 603
[xml follows]
I have also tried with wget 1.12 (heard that 1.11 had problem with NTLM), but it too never yields a response, just waits.
[...]
---request end---
[writing POST file customerRequest.xml ... done]
HTTP request sent, awaiting response...
I've seen that others have gotten this behaviour before, but I have not been able to find out why. Can anyone shed some light on this? JDK 1.6 on linux.
I found that I missed a line in my generated client code that enabled Addressing and pass it to the getPort super method:
WebServiceFeature wsAddressing = new AddressingFeature(true);
ICustomerService service =
super.getPort(new QName("http://xmlns.example.com/services/Customer",
"WSHttpBinding_ICustomerService"), ICustomerService.class,
wsAddressing);
Why metro didn't generate this is beyond me. The method looked like this in the end:
#WebEndpoint(name = "WSHttpBinding_ICustomerService")
public ICustomerService getWSHttpBindingICustomerService() {
WebServiceFeature wsAddressing = new AddressingFeature(true);
ICustomerService service =
super.getPort(new QName("http://xmlns.example.com/services/Customer",
"WSHttpBinding_ICustomerService"), ICustomerService.class,
wsAddressing);
NtlmAuthenticator auth = new NtlmAuthenticator(username, password);
Authenticator.setDefault(auth);
return service;
}
This in turn added a SOAP header to the message:
<S:Header>
<To xmlns="http://www.w3.org/2005/08/addressing">https://services.example.com/CustomerService.svc</To>
<Action xmlns="http://www.w3.org/2005/08/addressing">http://xmlns.example.com/services/ICustomerService/GetCustomer</Action>
<ReplyTo xmlns="http://www.w3.org/2005/08/addressing">
<Address>http://www.w3.org/2005/08/addressing/anonymous</Address>
</ReplyTo>
<MessageID xmlns="http://www.w3.org/2005/08/addressing">uuid:d33c2888-abfa-474d-8729-95d2bcd17a96</MessageID>
</S:Header>

Login to gmail account

I need to be able to login to my gmail account, then i get cookies and will have access to other google services. But i can't login to my gmail(or any goolgle) account. I found some posts on this site how to do it, but none works for me. i do :
string formUrl = "https://www.google.com/accounts/ServiceLoginAuth";
string formParams = string.Format("Email={0}&Passwd={1}&signIn={2}&PersistentCookie={3}&GALX={4}",
"autokuzov.top", "1QAZ2wsx", "Sign in", "yes", "CfFosrEhu-0");
string cookieHeader;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Referer = "https://www.google.com/accounts/ServiceLoginAuth";
req.Method = "POST";
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.2.7) Gecko/20100713 Firefox/3.6.7";
req.AllowAutoRedirect = false;
req.CookieContainer = new CookieContainer();
req.Headers.Add(HttpRequestHeader.CacheControl, "no-cache=set-cookie");
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string s = sr.ReadToEnd();
}
Response return : "Your browser's cookie functionality is turned off. Please turn it on."
I also tried make req.Headers.Add(HttpRequestHeader.CacheControl, "no-cache=set-cookie"); but it was unseccussfull too.
Does anybody know where is a problem ?
"Your browser's cookie functionality
is turned off. Please turn it on."
You will probably need to have 3rd party cookies enabled in your browser. These are off by default in some browsers. You get the same warning in Firefox when using the Gmail Manager plugin if you disable 3rd party cookies.