Access User of Proxy in HttpServletRequest - java

I need to acess the name of the user of the Proxy, our server is Jboss6.4, when this user enter in my URL, I'm using ServletRequestListener, with the object HttpServletRequest, but I can't find the user.
String user1= request.getUserPrincipal().getName();
String user2 = request.getRemoteUser();
Both's are null, I need to do authentication without use a typical modal window or formular, I want to do this automatic, my idea it's use the LogonId of the User that he use in the Proxyof the browser and afterwards check in my LDAP directory if exist and the rights are correct.
To acess to the URL, the user first has to login in the browser because we have a proxy, my idea is take the id of the user from the proxy, but Ican't find it..

Unless your proxy is setting a header containing the username in the forwarded HTTP requests, you won't have the ability to retrieve the username used to connect to the proxy.
What you want to achieve looks like SSO but a simple proxy won't achieve SSO.

Related

Programmatically authenticate user with Keycloak in java

I have been looking through the Keycloak documentation but cannot see how to do this. With Java, I'd like to take a valid userid and password and then generate a token. How can I do this?
--EDIT 2018-08-31--
You can use the Authorization Client Java API. Once you have created an AuthzClient object, you can pass the username and password to the AuthzClient#authorization(username, password) or AuthzClient#obtainAccessToken(username, password) method to authenticate the user and get the access token (and/or ID token in the first case):
// create a new instance based on the configuration defined in keycloak-authz.json
AuthzClient authzClient = AuthzClient.create();
// send the authorization request to the server in order to
// obtain an access token granted to the user
AccessTokenResponse response = authzClient.obtainAccessToken("alice", "alice");
On a side note, if possible, you'd rather reuse one of the Keycloak Java Adapters to cover more features, such as other authentication methods (the user is typically redirected to Keycloack WUI where you can enforce very flexible authentication and authorization policies).

getting username from siteminder sso

My Application requires a Siteminder SSO login. I am able to capture the SM_USER which is the Employee Id by
request.getHeader("SM_USER");
Now I want to capture the Employee Name which is stored in Cookie.
I used request.getHeader("Cookie");
The cookie which I am getting is like
lcid=1033; IDEALDOMAIN=53AvKXzgyShYOE5+I4sX4Q==; SUPERUSER=False; ADIDMAPPINGFLAG=7LQlj8/2nvgLQlH4X/M4Gw==; INITMAPPINGSTATE=True; LDAPVALIDATIONFLAG=53AvKXzgyShYOE5+I4sX4Q==; SSOCONTENTNAME=IXK93MPqLZSIGwzx7YZ31XI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1H/OrUJVQ3YfgkRFKu12oL5BubfjveknmK4r8wp8r3LTq/Rz58zkiwUj1J0qNAQ5BlHbL53vJdBZebQT0lpjTQ2KTOi96JlPkWhR2AnG71ZaIbfUsWz9QPYH55zc9KzbJE0AreyD/eJG9XcSkP6cV7gjsUDCUZk2i+H2iqO3tNQDMgUuZb65i7+CQKWlYixHYuo66zvrUql//1hdm8YiBDzNPRm4SIVKOcZkPk/H9MQYnTWa5fKppDVShcyCSNF6YME8038qg5mv5m7oF+0AfyxmzHeJ+Ddvy95NO
Now How can I get the username from this Cookie
Just like you are using request.getHeader("SM_USER") to obtain the userid, the usual suggestion in the Siteminder world is to use the so-called Response for Siteminder to help you retrieve whatever user attributes you need, in the case the Employee Name, and make them available in the Header for you. In short, you would need to ask your Siteminder administrator to configure this for you.
Since Cookie lives on a Browser, so unless the Cookie is encrypted, the user on the Browser would be able to tamper it and render the Cookie useless. If a Cooke is encrypted, then your program would need to know how to decrypt it and hence you would have a far more challenging task to do.

Preventing login attacks from curl/http post in spring app

I have a spring web app hosted on amazon and I am facing login attacks from some automated machines. From my logs, it is clear that they are bypassing login page, and are using something like :
curl --data "j_username=xxx&j_password=yyy" http://www.mysecureurl.com/j_spring_security_check
My question is how to prevent such attacks. Is there a way I can block such logins which are not coming directly from login page via some spring configuration ?
I will then implement further security measures like captcha, lockout-after-3-wrong-attempts etc when user tries from login page.
You can implement the a Cross-site Request Forgery (CSRF)- Nonce-Token Pattern.
In other words,
generate a random token (for every user an different).
put this token in the user session
an add it as a hidden field in the user login form
if you receive a login request than the check if the submitted token matches the token form the session - if not then send them a access denid
BTW:
you can use this pattern not only for your login page, but for all requests that change the server state. (to prevent CSRF-Attacs)
Spring Security >= 3.2 has a build in CSRF-Prevetion
If all requests coming from the same IP address you can use hasIpAddress expression:
<security:intercept-url pattern="/secure" access="isAuthenticated() and !hasIpAddress('11.11.111.11')" />
It is more temporary hack, because attackers can change their IP.
Here is how I solved my problem, thanks to all the answers above.
1.Added a custom filter to my spring security :
<custom-filter position="FORM_LOGIN_FILTER" ref="loginFilter" />
2.In the login controller, generated a random string and put that in http session
String random = UUID.randomUUID().toString().toLowerCase().replaceAll("-", "");
request.getSession().setAttribute("userKeyInSession", random);
3.Also passed this random key to login page so that the login jsp can submit this as hidden parameter along with form submit.
model.addAttribute("userKey", random);
return "login";
4.In the LoginFilter, I now do a simple string comparison between the request parameter and the random value in the session. If they do not match, I reject and do not proceed with authentication.
More to do: Captcha etc for preventing attacks from UI now..
Looks like you are using the default request login parameters provided by Spring-Security.
The default name attribute and password attribute value is j_username and j_password.
So if you change your login page's username and password parameters name attribute to something specific to you app , then you will be able to avoid such attacks , because in that case only you will be knowing the actual values attribute name and password and no one else and thus no one will be able be able to send http hack request to you app.

Authenticate credentials with LDAP for specific requests

I have a web application that I deploy using JBoss 5.2. In order for a user to use the application, he/she must authenticate with an LDAP server (using simple authentication) with a username and password. This is all done through setting up the login-config.xml for JBoss and providing a <login-module> with our implementation.
The problem comes in here: After having logged in, I have a scenario that requires the user to provide a username & password when a particular action is performed (which I will also authenticate with the LDAP server). I want to be able to reuse the same mechanism that I use for authenticating the user into the web application.
My form to log in to the application posts to j_security_check so in accordance with this, I was trying to send a request to j_security_check but JBOSS returns a 404. From reading around a bit, I've gathered j_security_check cannot be accessed by any arbitrary request and must be in response to a challenged request to a secured resource.
So then, how can I authenticate the second set of credentials the user has provided with the same LDAP server?
EDIT:
To clarify, the question is how to send the user's credential inputs to the LDAP server for authentication. Grabbing the input from the user, etc. is all done. All that is left is to take this input and send it to the LDAP server and get the response (which is where I am stuck).
If it helps to mention, the login to the web application uses a custom class that extends UsernamePasswordLoginModule.
So, after lots of research, I ended up finding a solution for JBoss environments (which is what I'm using).
Once you capture the user's credentials, you send them to your server via a POST/GET and your server can perform the following to use whatever authentication policy you have configured (in login-config.xml) to verify the credentials:
WebAuthentication webAuthentication = new WebAuthentication();
boolean success = webAuthentication.login(username, password);
To expand on this, I was also able to check the user's role/group via the HttpServletRequest (which is passed into my server-side handler):
boolean userIsInRole = servletRequest.isUserInRole("nameOfGroup")
The spring security documentation explains it
Wanted to add another answer for JBoss 6.2+, where WebAuthentication no longer exists.
I've used the creation of a LoginContext to achieve the same result:
String SECURITY_DOMAIN_NAME = "ssd"; // the security domain's name from standalone.xml
String username = "user";
String password = "password";
LoginContext lc = null;
try {
lc = new LoginContext(SECURITY_DOMAIN_NAME, new UsernamePasswordHandler(username, password.toCharArray()));
lc.login();
// successful login
} catch (LoginException loginException) {
// failed login
}
And the use uf lc.getSubject().getPrincipals() to verify roles.

Authentification using a user id stored in the session - security risk / bad practice?

I am developing a small REST-webservice for non critical data which will mainly be accessed by a smartphone application. For limiting the access of the users to their individual data (the authorization does not need groups or roles), I need to implement some sort of basic authentification.
As the service will be accessed over HTTP, using HTTP-Authentification seems to be no good idea as the username and password will be sent in cleartext on every request and need to be stored on the client device.
Thus, my idea was to implement authentification the following way:
The user logs on using a login method of my webservice passing their username / password
This method checks the validity of the username / password combination (based on a database containing salted and hashed passwords)
If the login is successful, the id of the user (primary key of the database table) is stored in the session as an attribute
In the following requests, this attribute is used to authentificate the user
In code, my login method would look like the following:
User user = this.authentificate(username, password);
HttpSession session = request.getSession(true);
if (user != null)
session.setAttribute("UserId", user.getId());
else
session.invalidate();
Afterwards, I would be able to authentificate the user based on the session:
int userId = (int) request.getSession().getAttribute("UserId");
User currentUser = getUserById(userId);
Can this approach be considered as "secure" (no easy session highjacking possible - as far as I understood https://stackoverflow.com/a/5838191/232175 , the attributes' values won't leave the server)?
Are there any downsides or alternatives?
With regard to storing the user id in the session, I think that is OK, but you have another problem.
First, I would assume that the login method would be over HTTPS, otherwise the username and password would be sent in clear text to the login method and you are right back to the same problem you had before.
Second, if the login method were over HTTPS, then the session cookie would be an HTTPS cookie and all other API calls would also need to be over HTTPS. If subsequent calls were over HTTP, they would get a new session cookie and the user id would be unavailable in that session.
If you really want secure authentication without HTTPS, you would need to use a shared secret signing scheme (e.g. HMAC) or an asymmetric signing system like RSA to have the client sign requests and then validate those signed requests server side.

Categories