一、描述
用户登录后,后端服务会将用户信息放到heard里
二、代码
@Slf4j
@Component
public class RequestContextComponent {
/**
* 获取会员ID
*/
public Long getMemberId() {
//从Header中获取用户信息
try {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
request.setCharacterEncoding("utf-8");
String uid = request.getHeader("uid");
if(StringUtil.isNotEmpty(uid)){
return Long.valueOf(uid);
}
} catch (Exception exception) {
throw new Exception(I18nUtils.message("auth.relogin"));
}
return null;
}
/**
* 获取当前登录用户信息
* @return
*/
public SecurityUserDTO getSecurity() {
//从Header中获取用户信息
try {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
request.setCharacterEncoding("utf-8");
String user = request.getHeader("user");;
if (user == null) {
throw new Exception(I18nUtils.message("auth.relogin"));
}
JSONObject userJsonObject = new JSONObject(URLDecoder.decode(user, Charset.defaultCharset()) );
SecurityUserDTO securityDTO = new SecurityUserDTO();
securityDTO.setId(Convert.toLong(userJsonObject.get("id")));
securityDTO.setUserName(userJsonObject.getStr("username"));
securityDTO.setUserType(SecurityUserTypeEnum.valueOf(userJsonObject.getStr("userType")));
securityDTO.setGrantType(SecurityLoginTypeEnum.parse(userJsonObject.getStr("grantType")));
if(StringUtil.isNotNullOrEmpty(userJsonObject.get("authorities"))){
securityDTO.setRoles(Convert.toList(String.class,userJsonObject.get("authorities")));
}
return securityDTO;
} catch (Exception exception) {
throw new Exception(I18nUtils.message("auth.relogin"));
}
}
}
网友评论