学校统一身份验证

master
yangjie 3 years ago
parent 31cd7e79a3
commit fce2214eee
  1. 14
      pom.xml
  2. 2
      src/main/java/com/yipin/liuwanr/PropertiesUtils.java
  3. 9
      src/main/java/com/yipin/liuwanr/Test.java
  4. 123
      src/main/java/com/yipin/liuwanr/config/CasFilterConfig.java
  5. 21
      src/main/java/com/yipin/liuwanr/controller/Response.java
  6. 18
      src/main/java/com/yipin/liuwanr/controller/UserInfoController.java
  7. 18
      src/main/java/com/yipin/liuwanr/filter/AuthInterceptor.java
  8. 18
      src/main/java/com/yipin/liuwanr/filter/CasFilter.java
  9. 49
      src/main/java/com/yipin/liuwanr/filter/LocalUserInfoFilter.java
  10. 34
      src/main/java/com/yipin/liuwanr/util/CASUtil.java
  11. 35
      src/main/java/com/yipin/liuwanr/util/UserIdUtils.java

@ -54,7 +54,7 @@
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId> <artifactId>spring-cloud-dependencies</artifactId>
<version>Edgware.RELEASE</version> <version>Edgware.RELEASE</version>
<scope>import</scope> <!-- <scope>import</scope>-->
<type>pom</type> <type>pom</type>
</dependency> </dependency>
<!-- redis --> <!-- redis -->
@ -277,6 +277,18 @@
<scope>runtime</scope> <scope>runtime</scope>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<version>3.2.1</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies> </dependencies>
<build> <build>
<finalName>root</finalName> <finalName>root</finalName>

@ -33,7 +33,7 @@ public class PropertiesUtils extends PropertyPlaceholderConfigurer {
static { static {
InputStream ins = null; InputStream ins = null;
try { try {
ins = PropertiesUtils.class.getResourceAsStream("/config/application.properties"); ins = PropertiesUtils.class.getResourceAsStream("/config/application-dev.properties");
PRO.load(ins); PRO.load(ins);
} catch (IOException e) { } catch (IOException e) {
System.out.println("加载连连支付配置文件失败!"); System.out.println("加载连连支付配置文件失败!");

@ -8,6 +8,9 @@ import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.yipin.liuwanr.entity.UserIdEnum;
import com.yipin.liuwanr.helper.RandomUtil;
import com.yipin.liuwanr.util.MD5;
import net.sf.json.JSONArray; import net.sf.json.JSONArray;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
@ -18,6 +21,12 @@ public class Test {
// System.out.println((new Test()).getURLContent()); // System.out.println((new Test()).getURLContent());
// String urlStr = "http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=40&sort=symbol&asc=1&node=hs_a&symbol=&_s_r_a=init"; // String urlStr = "http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=40&sort=symbol&asc=1&node=hs_a&symbol=&_s_r_a=init";
// System.out.println((new Test()).getURLContent(urlStr)); // System.out.println((new Test()).getURLContent(urlStr));
/* String zj0001 = RandomUtil.parsePassword("sdsdfhs");
System.out.println(zj0001);*/
// System.out.println(MD5.encrypt("zj0001"));
System.out.println(UserIdEnum.getUserId(Integer.parseInt("1510")));
} }

@ -0,0 +1,123 @@
package com.yipin.liuwanr.config;
import com.yipin.liuwanr.filter.LocalUserInfoFilter;
import org.jasig.cas.client.authentication.AuthenticationFilter;
import org.jasig.cas.client.session.SingleSignOutFilter;
import org.jasig.cas.client.session.SingleSignOutHttpSessionListener;
import org.jasig.cas.client.util.AssertionThreadLocalFilter;
import org.jasig.cas.client.util.HttpServletRequestWrapperFilter;
import org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
/**
* cas过滤器配置
*/
@Configuration
public class CasFilterConfig {
private static final String CAS_URL= "https://idas.uestc.edu.cn/authserver";
private static final String APP_URL= "http://222.197.183.3:8090";
@Bean
public ServletListenerRegistrationBean<SingleSignOutHttpSessionListener> servletListenerRegistrationBean(){
ServletListenerRegistrationBean<SingleSignOutHttpSessionListener> listenerRegistrationBean = new ServletListenerRegistrationBean<>();
listenerRegistrationBean.setListener(new SingleSignOutHttpSessionListener());
listenerRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return listenerRegistrationBean;
}
/**
* 单点登录退出
* @return registrationBean
*/
@Bean
public FilterRegistrationBean<SingleSignOutFilter> singleSignOutFilter(){
FilterRegistrationBean<SingleSignOutFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new SingleSignOutFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.addInitParameter("casServerUrlPrefix", CAS_URL );
registrationBean.setName("CAS Single Sign Out Filter");
registrationBean.setOrder(2);
return registrationBean;
}
/**
* 单点登录认证
* @return registrationBean
*/
@Bean
public FilterRegistrationBean<AuthenticationFilter> authenticationFilter(){
FilterRegistrationBean<AuthenticationFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new AuthenticationFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setName("CAS Filter");
registrationBean.addInitParameter("casServerLoginUrl",CAS_URL);
registrationBean.addInitParameter("serverName", APP_URL );
registrationBean.setOrder(3);
return registrationBean;
}
/**
* 单点登录校验
* @return registrationBean
*/
@Bean
public FilterRegistrationBean<Cas20ProxyReceivingTicketValidationFilter> cas20ProxyReceivingTicketValidationFilter(){
FilterRegistrationBean<Cas20ProxyReceivingTicketValidationFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new Cas20ProxyReceivingTicketValidationFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setName("CAS Validation Filter");
registrationBean.addInitParameter("casServerUrlPrefix", CAS_URL );
registrationBean.addInitParameter("serverName", APP_URL );
registrationBean.setOrder(4);
return registrationBean;
}
/**
* 单点登录请求包装
* @return registrationBean
*/
@Bean
public FilterRegistrationBean<HttpServletRequestWrapperFilter> httpServletRequestWrapperFilter(){
FilterRegistrationBean<HttpServletRequestWrapperFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new HttpServletRequestWrapperFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setName("CAS HttpServletRequest Wrapper Filter");
registrationBean.setOrder(5);
return registrationBean;
}
/**
* 单点登录本地用户信息
* @return registrationBean
*/
@Bean
public FilterRegistrationBean<LocalUserInfoFilter> localUserInfoFilter(){
FilterRegistrationBean<LocalUserInfoFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new LocalUserInfoFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setName("localUserInfoFilter");
registrationBean.setOrder(6);
return registrationBean;
}
@Bean
public FilterRegistrationBean<AssertionThreadLocalFilter> assertionThreadLocalFilter(){
FilterRegistrationBean<AssertionThreadLocalFilter> registrationBean
= new FilterRegistrationBean<>();
registrationBean.setFilter(new AssertionThreadLocalFilter());
return registrationBean;
}
}

@ -31,4 +31,25 @@ public class Response {
public void setErrmessage(String errmessage) { public void setErrmessage(String errmessage) {
this.errmessage = errmessage; this.errmessage = errmessage;
} }
public static Response ok(Object o){
Response response = new Response();
response.errmessage = "成功";
response.message = o;
return response;
}
public static Response ok(){
Response response = new Response();
response.errmessage = "成功";
response.message = "";
return response;
}
public static Response error(){
Response response = new Response();
response.message = "错误";
response.errmessage = "";
return response;
}
} }

@ -5,6 +5,7 @@ import com.yipin.liuwanr.entity.vo.AccountLoginVO;
import com.yipin.liuwanr.entity.vo.AdminLoginVO; import com.yipin.liuwanr.entity.vo.AdminLoginVO;
import com.yipin.liuwanr.helper.RedisHelper; import com.yipin.liuwanr.helper.RedisHelper;
import com.yipin.liuwanr.service.*; import com.yipin.liuwanr.service.*;
import com.yipin.liuwanr.util.UserIdUtils;
import com.yipin.liuwanr.vo.UserInfoVO; import com.yipin.liuwanr.vo.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -39,6 +40,9 @@ public class UserInfoController {
@Autowired @Autowired
private ISysPermissionService permissionService; private ISysPermissionService permissionService;
@Autowired
private UserIdUtils userIdUtils;
/** /**
* 添加用户 * 添加用户
@ -333,6 +337,11 @@ public class UserInfoController {
} }
@PostMapping("/schoolLogins")
public Response schoolLogins(){
return Response.ok();
}
/** /**
* 科大教师端登陆 * 科大教师端登陆
@ -485,7 +494,8 @@ public class UserInfoController {
resp.setStatus(300); resp.setStatus(300);
resp.setErrmessage("平台id为空!查询失败!"); resp.setErrmessage("平台id为空!查询失败!");
} else { } else {
HashMap<String, Object> ret = userInfoService.queryUserOR(userId,platformId); Integer token = userIdUtils.getUserIdByToken();
HashMap<String, Object> ret = userInfoService.queryUserOR(token,platformId);
int status = (int) ret.get("retcode"); int status = (int) ret.get("retcode");
if (200 == status) { if (200 == status) {
resp.setStatus(status); resp.setStatus(status);
@ -508,7 +518,8 @@ public class UserInfoController {
resp.setStatus(300); resp.setStatus(300);
resp.setErrmessage("用户id为空!查询失败!"); resp.setErrmessage("用户id为空!查询失败!");
}else { }else {
HashMap<String, Object> ret = userInfoService.queryUserProfiles(userId); Integer token = userIdUtils.getUserIdByToken();
HashMap<String, Object> ret = userInfoService.queryUserProfiles(token);
int status = (int) ret.get("retcode"); int status = (int) ret.get("retcode");
if (200 == status) { if (200 == status) {
resp.setStatus(status); resp.setStatus(status);
@ -727,7 +738,8 @@ public class UserInfoController {
resp.setStatus(300); resp.setStatus(300);
resp.setErrmessage("平台id为空!"); resp.setErrmessage("平台id为空!");
}else{ }else{
HashMap<String, Object> ret = userInfoService.queryStuAndSta(platformId,userId); Integer token = userIdUtils.getUserIdByToken();
HashMap<String, Object> ret = userInfoService.queryStuAndSta(platformId,token);
int status = (int) ret.get("retcode"); int status = (int) ret.get("retcode");
if (200 == status) { if (200 == status) {
resp.setStatus(status); resp.setStatus(status);

@ -1,6 +1,7 @@
package com.yipin.liuwanr.filter; package com.yipin.liuwanr.filter;
import org.jasig.cas.client.validation.AssertionImpl;
import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations; import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -10,6 +11,8 @@ import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
/** /**
@ -28,6 +31,21 @@ public class AuthInterceptor implements HandlerInterceptor {
response.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8"); response.setContentType("text/html;charset=utf-8");
Object attribute = request.getSession().getAttribute("_const_cas_assertion_");
if (!StringUtils.isEmpty(attribute)){
AssertionImpl assertion = (AssertionImpl) attribute;
Field[] fields = assertion.getClass().getDeclaredFields();
/*for (Field field : fields) {
System.out.println(field);
}*/
//获取用户信息中的公开属性
Map<String,Object> map = assertion.getPrincipal().getAttributes();
//获取用户信息中公开的Attributes部分
map.get("user_name"); //获取登录用户姓名,默认可获取
map.get("uid"); //获取登录用户id,需接入应用配置方可获取
}
String token = request.getHeader("token"); String token = request.getHeader("token");
if (StringUtils.isEmpty(token)) { if (StringUtils.isEmpty(token)) {

@ -0,0 +1,18 @@
package com.yipin.liuwanr.filter;
import org.jasig.cas.client.authentication.AuthenticationFilter;
import org.springframework.core.annotation.Order;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
@Order(value = 0)
@WebFilter(filterName = "CAS Authentication Filter", urlPatterns = "/*", initParams = {
@WebInitParam(name = "casServerLoginUrl", value = "https://idas.uestc.edu.cn"),
@WebInitParam(name = "serverName", value = "http://222.197.183.3:8090")
})
//自定义一个继承CAS过滤器的过滤器,不用具体实现也可以生效
public class CasFilter extends AuthenticationFilter {
}

@ -0,0 +1,49 @@
package com.yipin.liuwanr.filter;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.yipin.liuwanr.util.CASUtil;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
/**
* 本地用户信息过滤器
*
* @author weiller 2018年1月23日10:27:30
*/
public class LocalUserInfoFilter implements Filter {
Logger logger = LoggerFactory.getLogger(LocalUserInfoFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest)request;
Map<String,Object> loginName = CASUtil.getAccountNameFromCas(httpServletRequest);
assert loginName != null;
if(!loginName.isEmpty()){
logger.info("访问者 :" +loginName.get("user_name"));
logger.info("访问者 :" +loginName.get("uid"));
httpServletRequest.getSession().setAttribute("loginName", loginName.get("user_name"));
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}

@ -0,0 +1,34 @@
package com.yipin.liuwanr.util;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* cas client常用工具类
*
* @author weiller
*/
public class CASUtil {
/**
* 从cas中获取用户名
*
* @param request
* @return
*/
public static Map<String, Object> getAccountNameFromCas(HttpServletRequest request) {
Assertion assertion = (Assertion) request.getSession()
.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
if(assertion!= null){
AttributePrincipal principal = assertion.getPrincipal();
return assertion.getAttributes();
}else return null;
}
}

@ -0,0 +1,35 @@
package com.yipin.liuwanr.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
@Component
public class UserIdUtils {
@Autowired
StringRedisTemplate redisTemplate;
@Autowired
HttpServletRequest request;
public Integer getUserIdByToken(){
String token = request.getHeader("token");
if (StringUtils.isEmpty(token)){
return 0;
}
ValueOperations<String, String> ops = redisTemplate.opsForValue();
Object loginStatus = ops.get(token);
if (StringUtils.isEmpty(loginStatus)){
return 0;
}else {
String userId = request.getHeader("userId");
if (!StringUtils.isEmpty(userId)){
return Integer.parseInt(userId);
}else {
return Integer.parseInt(loginStatus.toString());
}
}
}
}
Loading…
Cancel
Save