It would be awesome if we can use OAuth in JavaScript purely in client side.
before start to do that, please let me explain “OAuth2” with this picture in feeeew word (skip to section 2 YQL if you know OAuth2):
OAuth 2
OAuth 2 is widely use as authorize third party application without expose user’s password, OAuth2 using 2 steps verification.
Take github as example:
There are 2 role in this story: Developer Oyang and User Lulu
As Developer Oyang who write an App GIRA http://gira,oyanglul.us which can let user login using Github account.
As User, Lulu don’t want to login in your site with my Github username and password, since Lulu don’t trust Oyang but trust Github.
Solution should be: Oyang redirect Lulu to Github website so Lulu can login there, then github redirect to Oyang’s gira.com and with a signal: “hey, lulu’s password is correct, log she in dude!”.
So that is OAuth 2 actually.
Redirect users to request GitHub access
GET https://github.com/login/oauth/authorize
with parameter
cliend_id: id of your application
scope: permissions your application should have
this will redirect Lulu to github oauth page. Lulu can now login in github then check the permission Oyang’s app request, and decide to accept or not.
GitHub redirects back to your site
if Lulu say “yes”, github will redirect back to Oyang’s app with parameter of a “valided code”. which means apps’s permited and now app can get the Lulu’s access_token now.
POST https://github.com/login/oauth/access_token
with parameter
cliend_id: id of your application
client_secret: password of your application
code: the thing you just got from github.
access_token is just as important as User’s PASSWORD so keep that saft place and never expose to anyone.
client_secret is your app’s password so never expose to anyone either
Done
now Oyang’s App Gira just got the access_token of Lulu, so Gira can make requests to the API on a behalf of a Lulu.
Pure Client Side Implement
Now here comes the problems of Javascript OAuth 2 implementation pure client side.
capture code in step 2
secure client_secret when try request access_token
when github redirect back with code
the first one is easy to solve by check window.location
$(window).on("eshashchange", function() {
if(location.hash="#authdone"){
$.get("https://github.com/login/oauth/access_token",{
client_id:"666dc0b3b994cc362ca2",
client_secret:"your secret",
code:location.search.split("=").pop();
});
}
});
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/85253.html