Spring boot 单点登录SSO

Spring boot 单点登录SSO,第1张

Spring boot 单点登录SSO 参考:分布式单点登录框架XXL-SSO

测试需要两个项目 8080作为登录duan 8081作为测试端

首先在两个项目中都加入依赖

       
            com.xuxueli
            xxl-sso-core
            1.1.0
        

        
            org.springframework.boot
            spring-boot-starter-freemarker
        

在8080登录端配置

配置application.yml文件

server:
    port: 8080
### redis
redis-user:
    redisAddress: redis://127.0.0.1:6379
    redisExpireMinute: 1440
spring:

    mvc:   #  静态资源访问
        #        servlet.load-on-startup: 0
        static-path-pattern: /static
@Configuration
@ConfigurationProperties(prefix="redis-user")//获取yml中的redis-user配置
@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();
    }

}

8080登录端的后台controller WebController


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

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

    
    @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测试端配置

配置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
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

 

 配置redis  XxlSsoConfig

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

}

写8081测试端的后台controller 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 json(Model model, HttpServletRequest request) {
        XxlSsoUser xxlUser = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
        return new ReturnT(xxlUser);
    }
}

启动redis 和两个项目

访问8081测试端

 登录成功

 刷新8080登录端页面  直接进入系统

 一个系统登录其他系统都可以免登录

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5683372.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存