spring boot 单点登录sso移植项目,以及一些小细节

首先你的项目是多模块的。我这里是用的gitee 里 xuxueli的sso

一,以我的项目展开。我有两个模块。首先在两个模块里都加入两个依赖。

        
            com.xuxueli
            xxl-sso-core
            1.1.0
        
 
        
            org.springframework.boot
            spring-boot-starter-freemarker
        

第一个是sso所需要的,第二个是一个模板引擎。就是写html所需要的。

二,在改写配置文件时先来一个小插曲。

有的项目可能有application.properties和application.yml

这两个配置文件在编译时yml会覆盖properties,当然只是会覆盖变量相同,内容不同的。比如写相同的端口也是可以的。给一个yml,与properties的相互转换的链接

http://www.toyaml.com

三,在8080端口配置yml,我下面是properties里的。

### 
server.port=8080

## resources
spring.mvc.servlet.load-on-startup=0
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static/

### freemarker
spring.freemarker.templateLoaderPath=classpath:/templates/
spring.freemarker.suffix=.ftl
spring.freemarker.charset=UTF-8
spring.freemarker.request-context-attribute=request
spring.freemarker.settings.number_format=0.##########

### xxl-sso
xxl.sso.redis.address=redis://127.0.0.1:6379
xxl.sso.redis.expire.minute=1440

当然也可以经过转换放入yml里。上面配置了静态资源,模板引擎,和redis。

spring boot 单点登录sso移植项目,以及一些小细节_第1张图片

加入templates模板,另外千万别忘了将ftl里的静态资源路径修改一下再使用。资源都在static中。

配置XxlSsoconfig,我把引入的包也拿过来防止引入错。



import com.xxl.sso.core.store.SsoLoginStore;
import com.xxl.sso.core.util.JedisUtil;
import lombok.Data;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @author xuxueli 2018-04-03 20:41:07
 */
@Configuration
@Data
public class XxlSsoConfig implements InitializingBean, DisposableBean {

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

    @Value("${xxl.sso.redis.expire.minute}")
    private int redisExpireMinute;

    @Override
    public void afterPropertiesSet() throws Exception {
        SsoLoginStore.setRedisExpireMinite(redisExpireMinute);
        JedisUtil.init(redisAddress);
    }

    @Override
    public void destroy() throws Exception {
        JedisUtil.close();
    }

}

 webController,和徐雪丽不同,需要自己改动。结合自己项目。

package com.clusterProject.unifiedVerificationPlatform.controller;
import com.clusterProject.unifiedVerificationPlatform.entity.User;

import com.clusterProject.unifiedVerificationPlatform.service.LoginService;
import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.login.SsoWebLoginHelper;
import com.xxl.sso.core.store.SsoLoginStore;
import com.xxl.sso.core.store.SsoSessionIdHelper;
import com.xxl.sso.core.user.XxlSsoUser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * sso server (for web)
 *
 * @author xuxueli 2017-08-01 21:39:47
 */
@Controller
public class WebController {
    @Resource
    private LoginService loginService;

    /**
     *访问首页时 查看是否登录
     */
    @RequestMapping("/")
    public String index(Model model, HttpServletRequest request, HttpServletResponse response) {
        // login check
        XxlSsoUser xxlUser = SsoWebLoginHelper.loginCheck(request, response);
        if (xxlUser == null) {
            return "redirect:/login";
        } else {
            model.addAttribute("xxlUser", xxlUser);
            return "index";
        }
    }

    /**     * 访问登录页面 查看是否登录
     */
    @RequestMapping(Conf.SSO_LOGIN)
    public String login(Model model, HttpServletRequest request, HttpServletResponse response) {

        // login check
        XxlSsoUser xxlUser = SsoWebLoginHelper.loginCheck(request, response);
        if (xxlUser != null) {
            // success redirect
            String redirectUrl = request.getParameter(Conf.REDIRECT_URL);
            if (redirectUrl != null && redirectUrl.trim().length() > 0) {
                String sessionId = SsoWebLoginHelper.getSessionIdByCookie(request);
                String redirectUrlFinal = redirectUrl + "?" + Conf.SSO_SESSIONID + "=" + sessionId;
                return "redirect:" + redirectUrlFinal;
            } else {
                return "redirect:/";
            }
        }

        model.addAttribute("errorMsg", request.getParameter("errorMsg"));
        model.addAttribute(Conf.REDIRECT_URL, request.getParameter(Conf.REDIRECT_URL));
        return "login";
    }

    /**
     *  doLogin 登录请求
     *  前台login表单传送
     * @param request
     * @param response
     * @param redirectAttributes
     * @param username
     * @param password
     * @param ifRemember
     * @return
     */
    @RequestMapping("doLogin")
    public String doLogin(HttpServletRequest request,
                          HttpServletResponse response,
                          RedirectAttributes redirectAttributes,
                          String username,
                          String password,
                          String ifRemember) {
        User user = User.builder().username(username).password(password).build();
        //查询数据库 以确定用户是否存在
        User user1 = loginService.usernameLogin(user);
        if (user1 != null) {
            //是否记住密码
            boolean ifRem = (ifRemember != null && "on".equals(ifRemember)) ? true : false;

            XxlSsoUser xxlUser = new XxlSsoUser();
            xxlUser.setUserid(String.valueOf(user1.getId()));
            xxlUser.setUsername(user1.getUsername());
            xxlUser.setVersion(UUID.randomUUID().toString().replaceAll("-", ""));
            xxlUser.setExpireMinite(SsoLoginStore.getRedisExpireMinite());
            xxlUser.setExpireFreshTime(System.currentTimeMillis());
            String sessionId = SsoSessionIdHelper.makeSessionId(xxlUser);

            //登录,存储storeKey
            SsoWebLoginHelper.login(response, sessionId, xxlUser, ifRem);

            //返回重定向sessionId
            String redirectUrl = request.getParameter(Conf.REDIRECT_URL);
            if (redirectUrl!=null && redirectUrl.trim().length()>0) {
                String redirectUrlFinal = redirectUrl + "?" + Conf.SSO_SESSIONID + "=" + sessionId;
                return "redirect:" + redirectUrlFinal;
            }
        }
        return "redirect:/";
    }

    /**
     * Logout
     *
     * @param request
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(Conf.SSO_LOGOUT)
    public String logout(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {

        // logout
        SsoWebLoginHelper.logout(request, response);

        redirectAttributes.addAttribute(Conf.REDIRECT_URL, request.getParameter(Conf.REDIRECT_URL));
        return "redirect:/login";
    }
}

配置8081端口,即第二模块开始

### web
server.port=8081
server.servlet.context-path=/

### resources
spring.mvc.servlet.load-on-startup=0
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static/

### freemarker
spring.freemarker.templateLoaderPath=classpath:/templates/
spring.freemarker.suffix=.ftl
spring.freemarker.charset=UTF-8
spring.freemarker.request-context-attribute=request
spring.freemarker.settings.number_format=0.##########

### xxl-sso
xxl.sso.server=http://127.0.0.1:8080/
xxl.sso.logout.path=/logout
xxl-sso.excluded.paths=
xxl.sso.redis.address=redis://127.0.0.1:6379

注意上面的最后四行。

XxlSsoConfig

package com.clusterProject.chatPlatform;

import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.filter.XxlSsoWebFilter;
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.excluded.paths}")
    private String xxlSsoExcludedPaths;

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


    @Bean
    public FilterRegistrationBean xxlSsoFilterRegistration() {

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

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

        registration.setName("XxlSsoWebFilter");
        registration.setOrder(1);
        registration.addUrlPatterns("/*");
        registration.setFilter(new XxlSsoWebFilter());
        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();
    }

}

IndexController

import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.entity.ReturnT;
import com.xxl.sso.core.user.XxlSsoUser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author xuxueli 2017-08-01 21:39:47
 */
@Controller
public class IndexController {

    @RequestMapping("/")
    public String index(Model model, HttpServletRequest request) {

        XxlSsoUser xxlUser = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
        model.addAttribute("xxlUser", xxlUser);
        return "index";
    }

    @RequestMapping("/json")
    @ResponseBody
    public ReturnT json(Model model, HttpServletRequest request) {
        XxlSsoUser xxlUser = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
        return new ReturnT(xxlUser);
    }

}

先启动redis,然后启动两个项目。 service快捷键 alt + 8,当然也可以分别进入各个模块运行启动类。

spring boot 单点登录sso移植项目,以及一些小细节_第2张图片spring boot 单点登录sso移植项目,以及一些小细节_第3张图片

 spring boot 单点登录sso移植项目,以及一些小细节_第4张图片

你可能感兴趣的:(java,intellij,idea,spring,boot)