Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get password from HTTP basic authentication

I'm using HTTP BASIC Authentication with Java.

My Servlet sends a JMS message but I need to supply the user and password to authenticate myself while creating the connection:

javax.jms.ConnectionFactory.createConnection(String username, String password) 

I can retrieve the username from HttpServletRequest.getUserPrincipal(). But there seems to be no way to retrieve the password. How do I solve this?

like image 982
Jin Kim Avatar asked Apr 14 '13 15:04

Jin Kim


People also ask

How do I find my Httpservletrequest username and password?

get(AuthorizationPolicy. class. getName()); From the policy object now I am able to get the username and password.

How do I pass username and password in HTTP header?

1 Answer. It is indeed not possible to pass the username and password via query parameters in standard HTTP auth. Instead, you use a special URL format, like this: http://username:[email protected]/ -- this sends the credentials in the standard HTTP "Authorization" header.


1 Answers

The password you are referring to is most probably different from the one provided by users while login. While the use case is not clear from the question, but it appears you are trying to use the username/password provided by external users to create a connection to JMS Connection Factory. This does not sound architecturally secure to me. You should use only one credential for connecting to ConnectionFactory which needs to be protected( treat it like db connections). Better is to use JNDI to lookup ConnectionFactory and bypass the username/password management stuff.

However, in case you have to use the technique, can use following code block.I am copying it from Gitblit project as it was open in my eclipse

Using Java8 Base64 class:

final String authorization = httpRequest.getHeader("Authorization"); if (authorization != null && authorization.toLowerCase().startsWith("basic")) {     // Authorization: Basic base64credentials     String base64Credentials = authorization.substring("Basic".length()).trim();     byte[] credDecoded = Base64.getDecoder().decode(base64Credentials);     String credentials = new String(credDecoded, StandardCharsets.UTF_8);     // credentials = username:password     final String[] values = credentials.split(":", 2); } 
like image 182
Akhilesh Singh Avatar answered Sep 29 '22 17:09

Akhilesh Singh