基于SpringBoot的SSO单点的登录配置

可以先参考:

XXL-SSO官方使用手册

实在不会的再参考本篇文章

源码地址:第二个集中项目: 老王的项目

视频讲解

SSO单点登录介绍_哔哩哔哩_bilibili

首先我们在所需要的两个(及以上)的项目pom.xml文件中引入依赖

        <!--SSO核心-->
        <!-- https://mvnrepository.com/artifact/com.xuxueli/xxl-sso-core -->
        <dependency>
            <groupId>com.xuxueli</groupId>
            <artifactId>xxl-sso-core</artifactId>
            <version>1.1.0</version>
        </dependency>

        <!-- freemarker前端模板 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

我们所引入的xxl-sso-core核心依赖的工具包如下,这里的工具我们后续都会用到

我们引入的freemaker模板,因为我还没找到直接通过地址栏访问前端页面的方式,所以我们用后端controller进行访问

===============================================

我们首先配置端口号,页面路径,静态页面路径以及freemaker的模板路径,还有redis

(这里有两种配置方式,一种是yml,一种是properties,这里为了全面一点我选择了每个子项目各用一种配置)

(登录页面为8080,测试页面为8081)

在8080端口的application.yml中如下配置

server:
  port: 8080
#  servlet:
#    context-path: /wangyi  


mvc: #  静态资源访问
    servlet.load-on-startup: 0
    static-path-pattern: /static/**
  resources:
    static-locations: classpath:/static/
  freemarker:
    templateLoaderPath: classpath:/templates/
    suffix: .ftl
    charset: UTF-8
    request-context-attribute: request
    settings.number_format: 0.##########


### redis
redis-wangyi:
  redisAddress: redis://127.0.0.1:6379
  redisExpireMinute: 1440

在8081端口的application.properties如下配置

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

### 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
### server后面跟你的服务器端口
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

======================================

配置8080端口

复制我项目源码中的前端模板到8080端口项目中,后续测试登录会用到

 8080端口的登录后台WebController,(doLogin的登录逻辑自己重写就行)


@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";
        }
    }



    /**
     * Login page
     *
     * @param model
     * @param request
     * @return
     */
    @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) {

        //mysql数据库的一个查询
        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());

            //产生session和storeKey
            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";
    }



}

配置XxlSsoConfig(@ConfigurationProperties(prefix="redis-wangyi")这个注解括号里面的prefix的值对应着yml里面的词头名)


/**
 * @author xuxueli 2018-04-03 20:41:07
 */
@Configuration
@ConfigurationProperties(prefix="redis-wangyi")
@Data
public class XxlSsoConfig implements InitializingBean, DisposableBean {

    private String redisAddress;

    private int redisExpireMinute;

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

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

}

======================================

配置8081端口

 复制我项目源码中的前端模板到8081端口项目中,后续测试登录会用到

配置IndexController,用于返回前端页面


@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<XxlSsoUser> json(Model model, HttpServletRequest request) {
        XxlSsoUser xxlUser = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
        return new ReturnT(xxlUser);
    }

    @RequestMapping("/wangyi")
    public String wangyi() {
        return "fff";
    }

}

 配置XxlSsoConfig,我们不仅要对jedis初始化,还要进行页面的拦截filter


@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();
    }

}

================================================

启动redis;   测试,分别运行两个项目,登录(因为我这里连接了我的数据库,所以我输入用户名输入gg123,密码输入gg123)

最后出现的两个端口的页面的都可以访问,cookies都一样, 即成功,如下.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值