IdentityServer4.Admin单点登录使用

单点服务器:https://github.com/skoruba/IdentityServer4.Admin

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>登录</title>
        <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
    </head>
    <body>
        
        <div id="app"></div>
        <pre id="results"></pre>
    </body>
    <script src="SSOHelper.js"></script>
    <script>
        // 定义插入html的日志
        $.fn.log = function() {
            var $node = $(this);
            $node.css({
                background: '#F1F3F4',
                padding: '15px',
                border: '1px solid #F3F3F3',
                borderRadius: '5px',
            })
            var txt = '';
            Array.prototype.forEach.call(arguments, function (msg) {
                if (msg instanceof Error) {
                    msg = "错误:" + msg.message;
                } else if (typeof msg !== 'string') {
                    msg = JSON.stringify(msg, null, 2);
                }
                txt += msg + '\r\n';
            });
            $node.text(txt);
        };
        // $("#results").log("测试", "这里是错误的<div>error: 404</div>");
        
        let sso = new SSOHelper();
        $(document).ready(function () {
            var App = {
                init: function () {
                    $(document).ready(function () {
                        sso.checkAuthenticated(function(isAuth) {
                            if (isAuth) {
                                App.home();
                            } else {
                                App.splash();
                            }
                        });
                    });
                }(),
                splash: function () {
                    var contentLogin =
                        '<input id="Username" type="text" value="System"> <input id="Password" type="password" value="dtsjy@2020"> <button id="login">Log in</button>';
                    $('#app').html(contentLogin);
                },
                home: function () {
                    var contentHome = '<h1>Welcome</h1> <a id="logout" href="javascript:void(0);">Log out</a>';
                    $('#app').html(contentHome);
                }
            };
            $(document).on('click', '#login', function (e) {
                e.preventDefault();
                sso.login({
                    username: $('#Username').val(),
                    password: $('#Password').val(),
                    callback: function(isAuth) {
                        if (isAuth) {
                            App.home();
                        }
                        // 测试刷新access_token
                        // sso.refreshToken(sso.getRefreshToken(), function(isAuth) {
                        //     console.info("refreshToken isAuth", isAuth);
                        // });
                    }
                });
            });
            $(document).on('click', '#logout', function (e) {
                e.preventDefault();
                sso.logout(function(isAuth) {
                        App.splash();
                });
            });
        });
    </script>
</html>

  SSOHelper.js

/**
 * 封装用于单点登录操作
 * @param {Object} w window对象
 */
(function(w) {
    // 默认配置
    let default_options = {
        debug: false,
        baseUrl: 'http://localhost:9000',
        clientId: 'platformclient',
        accessTokenKey: '#access_token',
        refreshTokenKey: '#refresh_token',
        expiresKey: '#expires_in',
    };
    let opts = {};
    let access_token;
    let refresh_token;
    
    // 日志打印
    function log() {
        if (opts.debug) {
            let args = arguments;
            console.log(...args);
        }
    }
        
    function SSOHelper(options) {
        // 合并传入参数和默认参数
        opts = Object.assign(opts, default_options, options || {});
        log("opts", opts);
        
        this.getAccessToken();
        this.getRefreshToken();
    }
    
    SSOHelper.prototype = {
        // Check that if user is logged in (has an access token)
        checkAuthenticated: function (callback) {
            if (this.getAccessToken() == null) {
                this.logout();
                if (callback) callback(false);
            } else {
                this.checkTokenValid(access_token, callback);
            }
        },
        // Check the token is still valid on the server for access (also get User info)
        checkTokenValid: function (access_token, callback) {
            var self = this;
            $.ajax({
                type: 'POST',
                url: `${opts.baseUrl}/connect/userinfo`,
                data: {
                    access_token: access_token
                },
                dataType: 'json',
                success: function (data) {
                    log('checkTokenValid success', data);
                    let isAuth = false;
                    if (data.error) {
                        if (self.getRefreshToken() == null) {
                            self.logout();
                        } else {
                            self.refreshToken(refresh_token, callback);
                        }
                    } else {
                        isAuth = true
                    }
                    if (callback) callback(isAuth);
                },
                error: function (a, b, c) {
                    log('checkTokenValid error', a);
                    if (self.getRefreshToken() == null) {
                        self.logout();
                        
                        if (callback) callback(false);
                    } else {
                        self.refreshToken(refresh_token, callback);
                    }
                }
            });
        },
        // Request a new access token using the refresh token
        refreshToken: function (refresh_token, callback) {
            var self = this;
            $.ajax({
                type: 'POST',
                url: `${opts.baseUrl}/connect/token`,
                data: {
                    grant_type: 'refresh_token',
                    refresh_token: refresh_token,
                    client_id: opts.clientId
                },
                dataType: 'json',
                success: function (data) {
                    if (data.error) {
                        log(data.error);
                        
                        if (callback) callback(false);
                    } else {
                        self.setAccessToken(data.access_token);
                        self.setRefreshToken(data.refresh_token);
                        
                        if (callback) callback(true);
                    }
                },
                error: function (a, b, c) {
                    log(a, b, c);
                    self.logout();
                    if (callback) callback(false);
                }
            });
        
        },
        // send login credentials and store tokens in localStorage and in variables
        login: function ({username, password, callback}) {
            var self = this;
            $.ajax({
                type: 'POST',
                url: `${opts.baseUrl}/connect/token`,
                data: {
                    grant_type: 'password',
                    username: username,
                    password: password,
                    client_id: opts.clientId
                },
                dataType: 'json',
                success: function (data) {
                    if (data.error) {
                        log(data.error);
                        if (callback) callback(false);
                    } else {
                        self.setAccessToken(data.access_token);
                        self.setRefreshToken(data.refresh_token);
                        
                        if (callback) callback(true);
                    }
                },
                error: function (a, b, c) {
                    log(a, b, c);
                    if (callback) callback(false);
                }
            });
        },
        // Clear the localStorage and token variables and load the login (splash page)
        logout: function (callback) {
            this.setAccessToken();
            this.setRefreshToken();
            if (callback) callback();
        },
        setAccessToken: function(token) {
            if (token == null || typeof token == 'undefined') {
                localStorage.removeItem(opts.accessTokenKey);
            } else {
                localStorage.setItem(opts.accessTokenKey, token);
            }
            access_token = token;
        },
        getAccessToken: function() {
            return access_token || (access_token = localStorage.getItem(opts.accessTokenKey));
        },
        setRefreshToken: function(token) {
            if (token == null || typeof token == 'undefined') {
                localStorage.removeItem(opts.refreshTokenKey);
            } else {
                localStorage.setItem(opts.refreshTokenKey, token);
            }
            refresh_token = token;
        },
        getRefreshToken: function() {
            return refresh_token || (refresh_token = localStorage.getItem(opts.refreshTokenKey));
        }
    }
    
    w.SSOHelper = SSOHelper;
})(window)

  服务端配置

这里请求存在跨域问题,所以可以启动可跨域的google浏览器。如下是登录请求返回参数:

 

posted @ 2021-03-26 16:23  居无常  阅读(995)  评论(0编辑  收藏  举报