Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

javascript - GreaseMonkey script to auto login using HTTP authentication

I've got quite a few GreaseMonkey scripts that I wrote at my work which automatically log me into the internal sites we have here. I've managed to write a script for nearly each one of these sites except for our time sheet application, which uses HTTP authentication.

Is there a way I can use GreaseMonkey to log me into this site automatically?

Edit: I am aware of the store password functionality in browsers, but my scripts go a step further by checking if I'm logged into the site when it loads (by traversing HTML) and then submitting a post to the login page. This removes the step of having to load up the site, entering the login page, entering my credentials, then hitting submit

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is possible to log in using HTTP authentication by setting the "Authorization" HTTP header, with the value of this header set to the string "basic username:password", but with the "username:password" portion of the string Base 64 encoded.

http://frontier.userland.com/stories/storyReader$2159

A bit of researching found that GreaseMonkey has a a function built into it where you can send GET / POST requests to the server called GM_xmlhttpRequest

http://diveintogreasemonkey.org/api/gm_xmlhttprequest.html

So putting it all together (and also getting this JavaScript code to convert strings into base64 I get the following

http://www.webtoolkit.info/javascript-base64.html

var loggedInText = document.getElementById('metanav').firstChild.firstChild.innerHTML;
if (loggedInText != "logged in as jklp") {
    var username = 'jklp';
    var password = 'jklpPass';
    var base64string = Base64.encode(username + ":" + password);

    GM_xmlhttpRequest({
        method: 'GET',
        url: 'http://foo.com/trac/login',
        headers: {
            'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey/0.3',
            'Accept': 'application/atom+xml,application/xml,text/xml',
            'Authorization':'Basic ' + base64string,
        }
    });
}

So when I now visit the site, it traverses the DOM and if I'm not logged in, it automagically logs me in.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...