123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
- <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
- <title>Knife4j-OAuth2</title>
- <script src="axios.min.js"></script>
- </head>
- <body>
- <script type="text/javascript">
- (function(){
- function OAuth2(url){
- this.url=url;
- this.code=null;
- this.accessToken=null;
- this.tokenType=null;
- this.state=null;
- //缓存在localStorage中的对象
- this.cacheValue=null;
- }
- OAuth2.prototype.init=function(){
- var local=this.url;
- this.code=this.getKey("code",local,"");
- this.accessToken=this.getKey("access_token",local,"");
- this.tokenType=this.getKey("token_type",local,"Bearer");
- this.state=this.getKey("state",local);
- if(window.localStorage){
- var value=window.localStorage.getItem(this.state);
- if(this.strNotBlank(value)){
- this.cacheValue=JSON.parse(value);
- }
- }
- }
- OAuth2.prototype.auth=function(){
- if(this.strNotBlank(this.code)){
- this.authorizationCode();
- }else{
- this.implicit();
- }
- }
- OAuth2.prototype.getKey=function(key,str,defaultValue){
- var reg=new RegExp(".*?"+key+"=(.*?)(&.*)?$","ig");
- var val=defaultValue;
- if(reg.test(str)){
- val=RegExp.$1;
- }
- return val;
- }
- OAuth2.prototype.strNotBlank=function(str){
- var flag = false;
- if ( str != undefined &&str != null &&str != "") {
- flag = true;
- }
- return flag;
- }
- OAuth2.prototype.implicit=function(){
- this.cacheValue.accessToken=this.tokenType+" "+this.accessToken;
- this.cacheValue.tokenType=this.tokenType;
- this.cacheValue.granted=true;
- window.localStorage.setItem(this.state,JSON.stringify(this.cacheValue))
- window.close();
- }
- OAuth2.prototype.authorizationCode=function(){
- var that=this;
- console.log(this.cacheValue);
- var url=this.cacheValue.tokenUrl;
- var params={
- "grant_type":"authorization_code",
- "code":this.code,
- "redirect_uri":decodeURIComponent(this.cacheValue.redirectUri),
- "client_id":this.cacheValue.clientId,
- "client_secret":this.cacheValue.clientSecret
- }
- let instance=axios.create();
- let requestConfig={
- url: url,
- method: 'post',
- timeout: 0,
- //此data必传,不然默认是data:undefined,https://github.com/axios/axios/issues/86
- //否则axios会忽略请求头Content-Type
- data: null,
- params:params
- }
- instance.request(requestConfig).then(res=>{
- let data=res.data;
- if(data!=null&&data!=undefined) {
- that.cacheValue.accessToken=data.token_type+" "+data.access_token;
- that.cacheValue.tokenType=data.token_type;
- that.cacheValue.granted=true;
- window.localStorage.setItem(that.state,JSON.stringify(that.cacheValue))
- window.close();
- }
-
- })
- }
- var oauth=new OAuth2(window.location.href);
- oauth.init();
- oauth.auth();
- })()
- </script>
- </body>
- </html>
|