How do I extract the username and password out of a URL in a servlet filter?

不打扰是莪最后的温柔 提交于 2019-12-01 22:42:46

My coworker found this thread that implies this isn't possible in modern browsers. They refuse to send the username:password part of a url over the wire for security reasons.

    URL url = new URL(custom_url);
    String userInfo = url.getUserInfo();

    String[] userInfoArray = userInfo.split(":");
    System.out.println("username"+userInfoArray[0]);
    System.out.println("password"+userInfoArray[1]);   

I'll add something to this answer

If the password contains the character :, you must specify a limit on your split.

So:

String[] userInfoArray = userInfo.split(":");

Becomes:

String[] userInfoArray = userInfo.split(":", 2);

2 means the pattern : is applied only one time (so the resulting length array is at maximum 2)

For passwords with '@', e.g. "http://user:p@ssw0rd@private.uri.org/some/service":

    final String authority = uri.getAuthority();

    if (authority != null) {
        final String[] userInfo = authority.split(":", 2);

        if (userInfo.length > 1) {
            this.username = userInfo[0];
            int passDelim = userInfo[1].lastIndexOf('@');

            if (passDelim != -1) {
                this.password = userInfo[1].substring(0, passDelim);
            }
        }
    }

Note that in this case trying to use getUserInfo() won't help since userInfo of the URI is null.

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