SSO 基于token vue + element ui spring boot前后端分离

一、项目启动

根据sql语句生成server库和客户端库

1.后端启动

配置修改:

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: username
    password: password
    url: jdbc:mysql://ip:port/spike_sso?autoReconnect=true&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF8&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai

xxl:
  sso:
    redis:
      address: redis://:password@ip:port/0
      expire:
        minute: 1440

server启动运行 SpikeSsoApplication.java 默认端口9090

client  启动运行 SpikeApplication.java 默认端口9091

2.前端nginx配置

upstream sso-api{
        server 127.0.0.1:6060 weight=1;
    }

    server {
        listen 8086;
        location / {
             root   /usr/share/nginx/spike-sso-ui/dist;
             index  index.html index.htm;
    	     try_files  $uri $uri/ /index.html;

        }
        location /sso {
            proxy_pass http://sso-api;
        }
         #location /api {
          #  proxy_pass http://127.0.0.1:9080;
        #}
    }
    server {
       listen 8087;
        location / {
             root   /usr/share/nginx/spike-ui/dist;
             index  index.html index.htm;
             try_files  $uri $uri/ /index.html;
        }

        location /api {
            proxy_pass http://127.0.0.1:9080;
        }
    }

二、项目详解

1.后端代码

XxlSsoConfig.java

import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.filter.XxlSsoTokenFilter;
import com.xxl.sso.core.util.JedisUtil;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author xuxueli 2018-11-15
 */
@Configuration
public class XxlSsoConfig implements DisposableBean {


    @Value("${xxl.sso.server}")
    private String xxlSsoServer;

    @Value("${xxl.sso.logout.path}")
    private String xxlSsoLogoutPath;

    @Value("${xxl.sso.redis.address}")
    private String xxlSsoRedisAddress;

    @Value("${xxl-sso.excluded.paths}")
    private String xxlSsoExcludedPaths;


    @Bean
    public FilterRegistrationBean xxlSsoFilterRegistration() {

        // xxl-sso, redis init
        JedisUtil.init(xxlSsoRedisAddress);

        // xxl-sso, filter init
        FilterRegistrationBean registration = new FilterRegistrationBean();

        registration.setName("XxlSsoTokenFilter");
        registration.setOrder(1);
        registration.addUrlPatterns("/*");
        registration.setFilter(new XxlSsoTokenFilter());
        registration.addInitParameter(Conf.SSO_SERVER, xxlSsoServer);
        registration.addInitParameter(Conf.SSO_LOGOUT_PATH, xxlSsoLogoutPath);
        registration.addInitParameter(Conf.SSO_EXCLUDED_PATHS, xxlSsoExcludedPaths);

        return registration;
    }

    @Override
    public void destroy() throws Exception {

        // xxl-sso, redis close
        JedisUtil.close();
    }

}

2.前端代码

axios 拦截器配置

配置 返回501跳转

import axios from "axios";
import { Message } from 'element-ui';
// 创建 axios 实例

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    let token = localStorage.getItem("token");
    if (token != null && token != 'null') {
        config.headers["xxl_sso_sessionid"] = token;
    }
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    if (response.data.code == 501) {
        window.location.href="/login";
    }
    return response;
}, function (error) {
    let status = error.response.status;
    if (403 == status) {
        Message.error("未登录");
        let returnUrl = localStorage.getItem("returnUrl");
        // if (returnUrl != 'null') {
        //     window.location.href="/login?returnUrl="+returnUrl;
        // }else {
            window.location.href="/login";
        // }
        //this.$router.push("/");
    }
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
});

export {axios as axios };

preLogin.vue处理跳转

let returnUrl = this.$route.query.returnUrl;
      localStorage.removeItem("returnUrl");
      if (returnUrl != undefined && returnUrl !=null && returnUrl != 'null') {
        localStorage.setItem("returnUrl",returnUrl);
      }
      // 查看sso server是否登录,如果登录带着token返回
      let token = localStorage.getItem("token");
      if (token != 'null') {
        // 校验登录
        logincheck(token).then(res=>{
          if (res.data.data != null) {
              window.location.href=returnUrl+"?token="+token;
          }else {
              window.location.href="/login?returnUrl="+returnUrl;
          }
        }).catch((err) => {
        })
        .finally(() => {

        });
      } else {
          window.location.href="/login?returnUrl="+returnUrl;
      }

三、代码地址

注意事项: 

客户端需要修改SSO 登录地址

SSO 基于token vue + element ui spring boot前后端分离_第1张图片

SSO 基于token vue + element ui spring boot前后端分离_第2张图片

在线demo 用户名/密码 admin/123456 

server: SSO SERVER

client: SPIKE SERVICE

github: https://github.com/katriina-tavi/spike

gitee: spike: 前端分离实现单点登录 vue element springboot xxl-sso实现

你可能感兴趣的:(vue.js,前端,javascript)