sa-token/sa-token-demo/sa-token-demo-sso2-client/src/main/java/com/pj/sso/SsoClientController.java
2021-06-29 23:32:35 +08:00

60 lines
1.9 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.pj.sso;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.sso.SaSsoUtil;
import cn.dev33.satoken.stp.StpUtil;
/**
* Sa-Token-SSO Client端 Controller
* @author kong
*/
@RestController
public class SsoClientController {
// SSO-Client端首页
@RequestMapping("/")
public String index() {
String str = "<h2>Sa-Token SSO-Client 应用端</h2>" +
"<p>当前会话是否登录:" + StpUtil.isLogin() + "</p>" +
"<p><a href=\"javascript:location.href='/ssoLogin?back=' + encodeURIComponent(location.href);\">登录</a></p>";
return str;
}
// SSO-Client端登录地址
@RequestMapping("ssoLogin")
public Object ssoLogin(String back, String ticket) {
// 如果当前Client端已经登录则无需访问SSO认证中心可以直接返回
if(StpUtil.isLogin()) {
return new ModelAndView("redirect:" + back);
}
/*
* 接下来两种情况:
* ticket无值说明此请求是Client端访问需要重定向至SSO认证中心
* ticket有值说明此请求从SSO认证中心重定向而来需要根据ticket进行登录
*/
if(ticket == null) {
String serverAuthUrl = SaSsoUtil.buildServerAuthUrl(SaHolder.getRequest().getUrl(), back);
return new ModelAndView("redirect:" + serverAuthUrl);
} else {
Object loginId = checkTicket(ticket);
if(loginId != null ) {
// loginId有值说明ticket有效
StpUtil.login(loginId);
return new ModelAndView("redirect:" + back);
}
// 此处向客户端提示ticket无效即可不要重定向到SSO认证中心否则容易引起无限重定向
return "ticket无效: " + ticket;
}
}
// SSO-Client端校验ticket获取账号id
private Object checkTicket(String ticket) {
return SaSsoUtil.checkTicket(ticket);
}
}