How to get password from HTTP basic authentication

三世轮回 提交于 2019-12-20 08:56:59

问题


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?


回答1:


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);
}



回答2:


The username and password were originally sent in the HTTP Authorization header (base64 encoded) so you could use that; but if the user maintains a session using cookies, they won't necessarily send that header each time.



来源:https://stackoverflow.com/questions/16000517/how-to-get-password-from-http-basic-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!