Commit b9c9690d authored by liqin's avatar liqin 💬

Merge branch 'master' of http://111.203.232.171:8888/licc/shop-mall into master

 Conflicts:
	wisenergy-web-admin/src/main/resources/application-test.yml
parents f070910b c07bae07
...@@ -39,7 +39,7 @@ ...@@ -39,7 +39,7 @@
<module>wisenergy-model</module> <module>wisenergy-model</module>
<module>wisenergy-mapper</module> <module>wisenergy-mapper</module>
<module>wisenergy-service</module> <module>wisenergy-service</module>
<module>wisenergy-shiro</module> <!--<module>wisenergy-shiro</module>-->
<module>wisenergy-web-admin</module> <module>wisenergy-web-admin</module>
</modules> </modules>
......
...@@ -17,13 +17,13 @@ public class FileUploadConfig { ...@@ -17,13 +17,13 @@ public class FileUploadConfig {
* 重新定义文件上传对象【springBoot request转化成MultipartHttpServletRequest】 * 重新定义文件上传对象【springBoot request转化成MultipartHttpServletRequest】
* @return * @return
*/ */
@Bean(name = "multipartResolver") // @Bean(name = "multipartResolver")
public MultipartResolver multipartResolver() { // public MultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver(); // CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("UTF-8"); // resolver.setDefaultEncoding("UTF-8");
resolver.setResolveLazily(true); // resolver.setResolveLazily(true);
resolver.setMaxInMemorySize(40960); // resolver.setMaxInMemorySize(40960);
resolver.setMaxUploadSize(512 * 1024 * 1024); // resolver.setMaxUploadSize(512 * 1024 * 1024);
return resolver; // return resolver;
} // }
} }
package cn.wisenergy.mapper; package cn.wisenergy.mapper;
import cn.wisenergy.model.app.AccountInfo; import cn.wisenergy.model.app.AccountInfo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
......
package cn.wisenergy.model.app; package cn.wisenergy.model.app;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model; import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
...@@ -19,7 +17,6 @@ import java.util.Date; ...@@ -19,7 +17,6 @@ import java.util.Date;
*/ */
@Data @Data
@ApiModel(value = "User") @ApiModel(value = "User")
@TableName("user_info")
public class User extends Model<User> implements Serializable{ public class User extends Model<User> implements Serializable{
private static final long serialVersionUID = 2525339404301884673L; private static final long serialVersionUID = 2525339404301884673L;
...@@ -27,21 +24,18 @@ public class User extends Model<User> implements Serializable{ ...@@ -27,21 +24,18 @@ public class User extends Model<User> implements Serializable{
* 主键id * 主键id
*/ */
@ApiModelProperty(name = "id", value = "用户主键id") @ApiModelProperty(name = "id", value = "用户主键id")
@TableId("id")
private Integer id; private Integer id;
/** /**
* 手机号作为用户账号 * 手机号作为用户账号
*/ */
@ApiModelProperty(name = "user_id", value = "用户主键id") @ApiModelProperty(name = "user_id", value = "用户主键id")
@TableId("user_id")
private String userId; private String userId;
/** /**
* 密码 * 密码
*/ */
@ApiModelProperty(name = "password", value = "用户密码") @ApiModelProperty(name = "password", value = "用户密码")
@TableId("password")
private String password; private String password;
...@@ -49,49 +43,42 @@ public class User extends Model<User> implements Serializable{ ...@@ -49,49 +43,42 @@ public class User extends Model<User> implements Serializable{
* 用户会员等级 * 用户会员等级
*/ */
@ApiModelProperty(name = "user_level", value = "用户会员等级") @ApiModelProperty(name = "user_level", value = "用户会员等级")
@TableId("user_level")
private int userLevel; private int userLevel;
/** /**
* 跨境额度 * 跨境额度
*/ */
@ApiModelProperty(name = "cross_border_line", value = "跨境额度") @ApiModelProperty(name = "cross_border_line", value = "跨境额度")
@TableId("cross_border_line")
private BigDecimal crossBorderLine; private BigDecimal crossBorderLine;
/** /**
* 身份证号码 * 身份证号码
*/ */
@ApiModelProperty(name = "id_card_number", value = "身份证号码") @ApiModelProperty(name = "id_card_number", value = "身份证号码")
@TableId("id_card_number")
private String idCardNumber; private String idCardNumber;
/** /**
* 粉丝昵称 * 粉丝昵称
*/ */
@ApiModelProperty(name = "fans_nickname", value = "粉丝昵称") @ApiModelProperty(name = "fans_nickname", value = "粉丝昵称")
@TableId("fans_nickname")
private String fansNickname; private String fansNickname;
/** /**
* 有赞粉丝id,有赞自动生成 * 有赞粉丝id,有赞自动生成
*/ */
@ApiModelProperty(name = "fans_id", value = "有赞粉丝id,有赞自动生成") @ApiModelProperty(name = "fans_id", value = "有赞粉丝id,有赞自动生成")
@TableId("fans_id")
private String fansId; private String fansId;
/** /**
* 用户本人邀请码 * 用户本人邀请码
*/ */
@ApiModelProperty(name = "invite_code", value = "用户本人邀请码") @ApiModelProperty(name = "invite_code", value = "用户本人邀请码")
@TableId("invite_code")
private String inviteCode; private String inviteCode;
/** /**
* 推荐人邀请码 * 推荐人邀请码
*/ */
@ApiModelProperty(name = "be_invited_code", value = "推荐人邀请码") @ApiModelProperty(name = "be_invited_code", value = "推荐人邀请码")
@TableId("be_invited_code")
private String beInvitedCode; private String beInvitedCode;
/** /**
...@@ -104,100 +91,4 @@ public class User extends Model<User> implements Serializable{ ...@@ -104,100 +91,4 @@ public class User extends Model<User> implements Serializable{
*/ */
@ApiModelProperty(name = "updateTime", value = "修改时间") @ApiModelProperty(name = "updateTime", value = "修改时间")
private Date updateTime; private Date updateTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getUserLevel() {
return userLevel;
}
public void setUserLevel(int userLevel) {
this.userLevel = userLevel;
}
public BigDecimal getCrossBorderLine() {
return crossBorderLine;
}
public void setCrossBorderLine(BigDecimal crossBorderLine) {
this.crossBorderLine = crossBorderLine;
}
public String getIdCardNumber() {
return idCardNumber;
}
public void setIdCardNumber(String idCardNumber) {
this.idCardNumber = idCardNumber;
}
public String getFansNickname() {
return fansNickname;
}
public void setFansNickname(String fansNickname) {
this.fansNickname = fansNickname;
}
public String getFansId() {
return fansId;
}
public void setFansId(String fansId) {
this.fansId = fansId;
}
public String getInviteCode() {
return inviteCode;
}
public void setInviteCode(String inviteCode) {
this.inviteCode = inviteCode;
}
public String getBeInvitedCode() {
return beInvitedCode;
}
public void setBeInvitedCode(String beInvitedCode) {
this.beInvitedCode = beInvitedCode;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
} }
package com.project.shiro.config; //package com.project.shiro.config;
//
import com.project.shiro.util.AuthenticationFilter; //import com.project.shiro.util.AuthenticationFilter;
import com.project.shiro.util.AuthenticationRealm; //import com.project.shiro.util.AuthenticationRealm;
import com.project.shiro.util.AuthorizationFilter; //import com.project.shiro.util.AuthorizationFilter;
import com.project.shiro.util.redis.ShiroRedisCacheManager; //import com.project.shiro.util.redis.ShiroRedisCacheManager;
import com.project.shiro.util.redis.ShiroRedisSessionDAO; //import com.project.shiro.util.redis.ShiroRedisSessionDAO;
import org.apache.shiro.session.mgt.SessionManager; //import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor; //import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; //import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean; //import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager; //import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie; //import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; //import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.slf4j.Logger; //import org.slf4j.Logger;
import org.slf4j.LoggerFactory; //import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; //import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; //import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn; //import org.springframework.context.annotation.DependsOn;
//
import javax.servlet.Filter; //import javax.servlet.Filter;
import java.util.HashMap; //import java.util.HashMap;
import java.util.LinkedHashMap; //import java.util.LinkedHashMap;
import java.util.Map; //import java.util.Map;
//
/** ///**
* Description: shiro配置类 // * Description: shiro配置类
* User: mxy // * User: mxy
* Date: 2019-04-16 // * Date: 2019-04-16
*/ // */
@Configuration //@Configuration
public class ShiroConfig { //public class ShiroConfig {
//
private static final transient Logger logger = LoggerFactory.getLogger(ShiroConfig.class); // private static final transient Logger logger = LoggerFactory.getLogger(ShiroConfig.class);
//
/** // /**
* 配置拦截器 // * 配置拦截器
* <p> // * <p>
* 定义拦截URL权限,优先级从上到下 // * 定义拦截URL权限,优先级从上到下
* 1). anon : 匿名访问,无需登录 // * 1). anon : 匿名访问,无需登录
* 2). authc : 登录后才能访问 // * 2). authc : 登录后才能访问
* 3). logout: 登出 // * 3). logout: 登出
* 4). frameperms : 自定义的过滤器 // * 4). frameperms : 自定义的过滤器
* <p> // * <p>
* URL 匹配风格 // * URL 匹配风格
* 1). ?:匹配一个字符,如 /admin? 将匹配 /admin1,但不匹配 /admin 或 /admin/; // * 1). ?:匹配一个字符,如 /admin? 将匹配 /admin1,但不匹配 /admin 或 /admin/;
* 2). *:匹配零个或多个字符串,如 /admin* 将匹配 /admin 或/admin123,但不匹配 /admin/1; // * 2). *:匹配零个或多个字符串,如 /admin* 将匹配 /admin 或/admin123,但不匹配 /admin/1;
* 3). **:匹配路径中的零个或多个路径,如 /admin/** 将匹配 /admin/a 或 /admin/a/b // * 3). **:匹配路径中的零个或多个路径,如 /admin/** 将匹配 /admin/a 或 /admin/a/b
* <p> // * <p>
* 配置身份验证成功,失败的跳转路径 // * 配置身份验证成功,失败的跳转路径
*/ // */
@Bean
public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
logger.info("进入Shiro拦截工厂");
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 设置securityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 自定义的过滤器
Map<String, Filter> filterMap = new HashMap<>();
// map里面key值要为过滤器的名称,value为过滤器对象
filterMap.put("authc", authenticationFilter());
filterMap.put("frameperms", authorizationFilter());
// 将自定义的过滤器加入到过滤器集合中
shiroFilterFactoryBean.setFilters(filterMap);
// 设置拦截器集合
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
filterChainDefinitionMap.put("/admin/", "anon"); // 后台资源-匿名访问
filterChainDefinitionMap.put("/admin/res/**", "anon"); // 静态资源-匿名访问
filterChainDefinitionMap.put("/admin/anon/**", "anon"); // 后台可匿名访问资源-匿名访问
filterChainDefinitionMap.put("/admin/login", "authc"); // 登录页面-身份认证
filterChainDefinitionMap.put("/admin/logout", "logout"); // 用户退出,只需配置logout即可实现该功能
filterChainDefinitionMap.put("/admin/common/**", "anon"); // 其他路径均需要身份认证,一般位于最下面,优先级最低
filterChainDefinitionMap.put("/admin/**", "authc,frameperms"); // 其他路径均需要身份认证,一般位于最下面,优先级最低
// 设置拦截器
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
shiroFilterFactoryBean.setLoginUrl("/admin/login"); // 登录的路径
// shiroFilterFactoryBean.setUnauthorizedUrl("/admin/common/unauthorized.jhtml"); // 验证失败后跳转的路径
logger.info("Shiro拦截工厂配置完成");
return shiroFilterFactoryBean;
}
/**
* 配置Shiro生命周期处理器
*/
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
/**
* 自动创建代理类,若不添加,Shiro的注解可能不会生效。
*/
@Bean
@DependsOn({"lifecycleBeanPostProcessor"})
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
}
/**
* 开启Shiro的注解
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
return authorizationAttributeSourceAdvisor;
}
/**
* 配置加密匹配,使用MD5的方式,进行1024次加密
*/
// @Bean // @Bean
// public HashedCredentialsMatcher hashedCredentialsMatcher() { // public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
// HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); // logger.info("进入Shiro拦截工厂");
// hashedCredentialsMatcher.setHashAlgorithmName("MD5"); // ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// hashedCredentialsMatcher.setHashIterations(1024); // // 设置securityManager
// return hashedCredentialsMatcher; // shiroFilterFactoryBean.setSecurityManager(securityManager);
//
// // 自定义的过滤器
// Map<String, Filter> filterMap = new HashMap<>();
// // map里面key值要为过滤器的名称,value为过滤器对象
// filterMap.put("authc", authenticationFilter());
// filterMap.put("frameperms", authorizationFilter());
// // 将自定义的过滤器加入到过滤器集合中
// shiroFilterFactoryBean.setFilters(filterMap);
//
// // 设置拦截器集合
// Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
// filterChainDefinitionMap.put("/admin/", "anon"); // 后台资源-匿名访问
// filterChainDefinitionMap.put("/admin/res/**", "anon"); // 静态资源-匿名访问
// filterChainDefinitionMap.put("/admin/anon/**", "anon"); // 后台可匿名访问资源-匿名访问
// filterChainDefinitionMap.put("/admin/login", "authc"); // 登录页面-身份认证
// filterChainDefinitionMap.put("/admin/logout", "logout"); // 用户退出,只需配置logout即可实现该功能
// filterChainDefinitionMap.put("/admin/common/**", "anon"); // 其他路径均需要身份认证,一般位于最下面,优先级最低
// filterChainDefinitionMap.put("/admin/**", "authc,frameperms"); // 其他路径均需要身份认证,一般位于最下面,优先级最低
//
// // 设置拦截器
// shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
// shiroFilterFactoryBean.setLoginUrl("/admin/login"); // 登录的路径
//// shiroFilterFactoryBean.setUnauthorizedUrl("/admin/common/unauthorized.jhtml"); // 验证失败后跳转的路径
// logger.info("Shiro拦截工厂配置完成");
// return shiroFilterFactoryBean;
// } // }
//
/** // /**
* SecurityManager 安全管理器;Shiro的核心 // * 配置Shiro生命周期处理器
*/ // */
@Bean // @Bean
public DefaultWebSecurityManager securityManager() { // public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // return new LifecycleBeanPostProcessor();
// 自定义的Realm // }
securityManager.setRealm(authenticationShiroRealm()); //
// 缓存管理 // /**
securityManager.setCacheManager(shiroRedisCacheManager()); // * 自动创建代理类,若不添加,Shiro的注解可能不会生效。
// 会话管理 // */
securityManager.setSessionManager(sessionManager()); // @Bean
return securityManager; // @DependsOn({"lifecycleBeanPostProcessor"})
} // public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
// DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
/** // advisorAutoProxyCreator.setProxyTargetClass(true);
* 自定义Realm,可以多个 // return advisorAutoProxyCreator;
*/ // }
@Bean //
public AuthenticationRealm authenticationShiroRealm() { // /**
AuthenticationRealm authenticationRealm = new AuthenticationRealm(); // * 开启Shiro的注解
//authenticationRealm.setCredentialsMatcher(hashedCredentialsMatcher()); // */
return authenticationRealm; // @Bean
} // public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
// AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
/** // authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
* redis缓存管理 // return authorizationAttributeSourceAdvisor;
*/ // }
@Bean //
public ShiroRedisCacheManager shiroRedisCacheManager() { // /**
return new ShiroRedisCacheManager(); // * 配置加密匹配,使用MD5的方式,进行1024次加密
} // */
//// @Bean
/** //// public HashedCredentialsMatcher hashedCredentialsMatcher() {
* 设置session会话管理者 //// HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
*/ //// hashedCredentialsMatcher.setHashAlgorithmName("MD5");
@Bean //// hashedCredentialsMatcher.setHashIterations(1024);
public SessionManager sessionManager() { //// return hashedCredentialsMatcher;
DefaultWebSessionManager defaultWebSessionManager = new DefaultWebSessionManager(); //// }
defaultWebSessionManager.setSessionIdCookie(simpleCookie()); //
defaultWebSessionManager.setSessionDAO(shiroRedisSessionDAO()); // /**
return defaultWebSessionManager; // * SecurityManager 安全管理器;Shiro的核心
} // */
// @Bean
/** // public DefaultWebSecurityManager securityManager() {
* session管理 // DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
*/ // // 自定义的Realm
@Bean // securityManager.setRealm(authenticationShiroRealm());
public ShiroRedisSessionDAO shiroRedisSessionDAO() { // // 缓存管理
return new ShiroRedisSessionDAO(); // securityManager.setCacheManager(shiroRedisCacheManager());
} // // 会话管理
// securityManager.setSessionManager(sessionManager());
/** // return securityManager;
* 这里需要设置一个cookie的名称 原因就是会跟原来的session的id值重复的 // }
*/ //
@Bean // /**
public SimpleCookie simpleCookie() { // * 自定义Realm,可以多个
return new SimpleCookie("SHAREJSESSIONID"); // */
} // @Bean
// public AuthenticationRealm authenticationShiroRealm() {
// AuthenticationRealm authenticationRealm = new AuthenticationRealm();
@Bean // //authenticationRealm.setCredentialsMatcher(hashedCredentialsMatcher());
public AuthenticationFilter authenticationFilter() { // return authenticationRealm;
return new AuthenticationFilter(); // }
} //
// /**
@Bean // * redis缓存管理
public AuthorizationFilter authorizationFilter() { // */
return new AuthorizationFilter(); // @Bean
} // public ShiroRedisCacheManager shiroRedisCacheManager() {
// return new ShiroRedisCacheManager();
} // }
//
// /**
// * 设置session会话管理者
// */
// @Bean
// public SessionManager sessionManager() {
// DefaultWebSessionManager defaultWebSessionManager = new DefaultWebSessionManager();
// defaultWebSessionManager.setSessionIdCookie(simpleCookie());
// defaultWebSessionManager.setSessionDAO(shiroRedisSessionDAO());
// return defaultWebSessionManager;
// }
//
// /**
// * session管理
// */
// @Bean
// public ShiroRedisSessionDAO shiroRedisSessionDAO() {
// return new ShiroRedisSessionDAO();
// }
//
// /**
// * 这里需要设置一个cookie的名称 原因就是会跟原来的session的id值重复的
// */
// @Bean
// public SimpleCookie simpleCookie() {
// return new SimpleCookie("SHAREJSESSIONID");
// }
//
//
// @Bean
// public AuthenticationFilter authenticationFilter() {
// return new AuthenticationFilter();
// }
//
// @Bean
// public AuthorizationFilter authorizationFilter() {
// return new AuthorizationFilter();
// }
//
//}
package com.project.shiro.util; //package com.project.shiro.util;
//
import com.alibaba.fastjson.JSONObject; //import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.authc.AuthenticationException; //import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken; //import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject; //import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils; //import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; //import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils; //import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger; //import org.slf4j.Logger;
import org.slf4j.LoggerFactory; //import org.slf4j.LoggerFactory;
//
import javax.servlet.ServletRequest; //import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; //import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; //import javax.servlet.http.HttpServletResponse;
import java.io.IOException; //import java.io.IOException;
import java.io.PrintWriter; //import java.io.PrintWriter;
//
/** ///**
* 自定义表单认证过滤器 // * 自定义表单认证过滤器
* // *
* @author wyy // * @author wyy
* @date 2019/07/26 // * @date 2019/07/26
*/ // */
public class AuthenticationFilter extends FormAuthenticationFilter { //public class AuthenticationFilter extends FormAuthenticationFilter {
private static final Logger log = LoggerFactory.getLogger(AuthenticationFilter.class); // private static final Logger log = LoggerFactory.getLogger(AuthenticationFilter.class);
//
//加密密码参数 // //加密密码参数
private static final String DEFAULT_EN_PASSWORD_PARAM = "enPassword"; // private static final String DEFAULT_EN_PASSWORD_PARAM = "enPassword";
//
//默认的登录名称 // //默认的登录名称
private static final String DEFAULT_USERNAME_PARAM = "loginName"; // private static final String DEFAULT_USERNAME_PARAM = "loginName";
//
//默认验证码ID参数 // //默认验证码ID参数
private static final String DEFAULT_CAPTCHA_ID_PARAM = "captchaId"; // private static final String DEFAULT_CAPTCHA_ID_PARAM = "captchaId";
//
//默认验证码参数 // //默认验证码参数
private static final String DEFAULT_CAPTCHA_PARAM = "captcha"; // private static final String DEFAULT_CAPTCHA_PARAM = "captcha";
//
private String captchaIdParam = DEFAULT_CAPTCHA_ID_PARAM; // private String captchaIdParam = DEFAULT_CAPTCHA_ID_PARAM;
//
private String captchaParam = DEFAULT_CAPTCHA_PARAM; // private String captchaParam = DEFAULT_CAPTCHA_PARAM;
//
private String usernameParam = DEFAULT_USERNAME_PARAM; // private String usernameParam = DEFAULT_USERNAME_PARAM;
//
private String enPasswordParam = DEFAULT_EN_PASSWORD_PARAM; // private String enPasswordParam = DEFAULT_EN_PASSWORD_PARAM;
//
/** // /**
* 创建token // * 创建token
*/ // */
@Override // @Override
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) { // protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
String loginName = getUsername(request); // String loginName = getUsername(request);
String password = getPassword(request); // String password = getPassword(request);
boolean isRemeberMe = isRememberMe(request); // boolean isRemeberMe = isRememberMe(request);
String ip = getHost(request); // String ip = getHost(request);
return new com.project.shiro.util.AuthenticationToken(loginName, password, isRemeberMe, ip, "", ""); // return new com.project.shiro.util.AuthenticationToken(loginName, password, isRemeberMe, ip, "", "");
} // }
//
/** // /**
* 登录拒绝;增加Ajax异步处理 // * 登录拒绝;增加Ajax异步处理
* // *
* @param servletRequest 请求对象 // * @param servletRequest 请求对象
* @param servletResponse 响应对象 // * @param servletResponse 响应对象
* @return // * @return
* @throws Exception // * @throws Exception
*/ // */
@Override // @Override
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception { // protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
// 判断是否为ajax异步请求 // // 判断是否为ajax异步请求
HttpServletRequest request = (HttpServletRequest) servletRequest; // HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse; // HttpServletResponse response = (HttpServletResponse) servletResponse;
//
// 判断是否为登录请求 // // 判断是否为登录请求
if (this.isLoginRequest(servletRequest, response)) { // if (this.isLoginRequest(servletRequest, response)) {
if (this.isLoginSubmission(servletRequest, response)) { // if (this.isLoginSubmission(servletRequest, response)) {
//
if (log.isTraceEnabled()) { // if (log.isTraceEnabled()) {
log.trace("Login submission detected. Attempting to execute login."); // log.trace("Login submission detected. Attempting to execute login.");
} // }
boolean b = executeLogin(servletRequest, response); // boolean b = executeLogin(servletRequest, response);
return b; // return b;
} else { // } else {
if (log.isTraceEnabled()) { // if (log.isTraceEnabled()) {
log.trace("Login page view."); // log.trace("Login page view.");
} // }
return true; // return true;
} // }
} else { // } else {
if (log.isTraceEnabled()) { // if (log.isTraceEnabled()) {
log.trace("Attempting to access a path which requires authentication. Forwarding to the Authentication url [" + this.getLoginUrl() + "]"); // log.trace("Attempting to access a path which requires authentication. Forwarding to the Authentication url [" + this.getLoginUrl() + "]");
} // }
//
// 异步请求报错 // // 异步请求报错
if (isAjaxReq(request, response)) { // if (isAjaxReq(request, response)) {
response.setContentType("application/json"); // response.setContentType("application/json");
response.setCharacterEncoding("UTF-8"); // response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter(); // PrintWriter out = response.getWriter();
JSONObject json = new JSONObject(); // JSONObject json = new JSONObject();
json.put("result", "fail"); // json.put("result", "fail");
json.put("msg", "未登录"); // json.put("msg", "未登录");
out.println(json); // out.println(json);
out.flush(); // out.flush();
out.close(); // out.close();
return false; // return false;
} // }
//
// 如果同步请求继续执行基类方法(当为同步方法的时候,基类会直接跳转登录页面) //// 如果同步请求继续执行基类方法(当为同步方法的时候,基类会直接跳转登录页面)
return super.onAccessDenied(request, response); // return super.onAccessDenied(request, response);
} // }
//
} // }
//
/** // /**
* 重写登录成功的方法;如果为异步请求,直接返回成功响应 // * 重写登录成功的方法;如果为异步请求,直接返回成功响应
* // *
* @param token // * @param token
* @param subject // * @param subject
* @param servletRequest // * @param servletRequest
* @param servletResponse // * @param servletResponse
* @return // * @return
* @throws Exception // * @throws Exception
*/ // */
@Override // @Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest servletRequest, ServletResponse servletResponse) throws Exception { // protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
// 如果为异步请求,登录成功后,直接返回数据,前台跳转登录后的页面处理 // // 如果为异步请求,登录成功后,直接返回数据,前台跳转登录后的页面处理
if (isAjaxReq(servletRequest, servletResponse)) { // if (isAjaxReq(servletRequest, servletResponse)) {
HttpServletResponse response = (HttpServletResponse) servletResponse; // HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setContentType("application/json"); // response.setContentType("application/json");
response.setCharacterEncoding("UTF-8"); // response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter(); // PrintWriter out = response.getWriter();
JSONObject json = new JSONObject(); // JSONObject json = new JSONObject();
json.put("result", "success"); // json.put("result", "success");
json.put("msg", "登录成功"); // json.put("msg", "登录成功");
out.write(json.toJSONString()); // out.write(json.toJSONString());
out.flush(); // out.flush();
out.close(); // out.close();
return true; // return true;
} // }
return super.onLoginSuccess(token, subject, servletRequest, servletResponse); // return super.onLoginSuccess(token, subject, servletRequest, servletResponse);
} // }
//
@Override // @Override
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { // public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
//Always return true if the request's method is OPTIONSif (request instanceof HttpServletRequest) { // //Always return true if the request's method is OPTIONSif (request instanceof HttpServletRequest) {
if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) { // if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
return true; // return true;
} // }
return super.isAccessAllowed(request, response, mappedValue); // return super.isAccessAllowed(request, response, mappedValue);
} // }
//
/** // /**
* 重写登录失败的方法;如果为异步请求,直接返回失败响应 // * 重写登录失败的方法;如果为异步请求,直接返回失败响应
* // *
* @param token // * @param token
* @param e // * @param e
* @param request // * @param request
* @param response // * @param response
* @return // * @return
*/ // */
@Override // @Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { // protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
// 如果为异步登录,直接返回错误结果 // // 如果为异步登录,直接返回错误结果
if (isAjaxReq(request, response)) { // if (isAjaxReq(request, response)) {
PrintWriter out = null; // PrintWriter out = null;
try { // try {
response = (HttpServletResponse) response; // response = (HttpServletResponse) response;
response.setContentType("application/json"); // response.setContentType("application/json");
response.setCharacterEncoding("UTF-8"); // response.setCharacterEncoding("UTF-8");
out = response.getWriter(); // out = response.getWriter();
JSONObject json = new JSONObject(); // JSONObject json = new JSONObject();
if (e.equals("org.apache.shiro.authc.pam.UnsupportedTokenException")) { // if (e.equals("org.apache.shiro.authc.pam.UnsupportedTokenException")) {
String message = "验证码错误!"; // String message = "验证码错误!";
json.put("result", "fail"); // json.put("result", "fail");
json.put("msg", message); // json.put("msg", message);
} else if (e.equals("org.apache.shiro.authc.UnknownAccountException")) { // } else if (e.equals("org.apache.shiro.authc.UnknownAccountException")) {
String message = "此账号不存在!"; // String message = "此账号不存在!";
json.put("result", "fail"); // json.put("result", "fail");
json.put("msg", message); // json.put("msg", message);
} else if (e.equals("org.apache.shiro.authc.DisabledAccountException")) { // } else if (e.equals("org.apache.shiro.authc.DisabledAccountException")) {
String message = "此账号已被禁用!"; // String message = "此账号已被禁用!";
json.put("result", "fail"); // json.put("result", "fail");
json.put("msg", message); // json.put("msg", message);
} else if (e.equals("org.apache.shiro.authc.LockedAccountException")) { // } else if (e.equals("org.apache.shiro.authc.LockedAccountException")) {
String message = "此账号已被锁定"; // String message = "此账号已被锁定";
json.put("result", "fail"); // json.put("result", "fail");
json.put("msg", message); // json.put("msg", message);
} else if (e.equals("org.apache.shiro.authc.IncorrectCredentialsException")) { // } else if (e.equals("org.apache.shiro.authc.IncorrectCredentialsException")) {
String message = "密码错误"; // String message = "密码错误";
json.put("result", "fail"); // json.put("result", "fail");
json.put("msg", message); // json.put("msg", message);
} else if (e.equals("org.apache.shiro.authc.AuthenticationException")) { // } else if (e.equals("org.apache.shiro.authc.AuthenticationException")) {
String message = "账号认证失败!"; // String message = "账号认证失败!";
json.put("result", "fail"); // json.put("result", "fail");
json.put("msg", message); // json.put("msg", message);
} // }
out.write(json.toJSONString()); // out.write(json.toJSONString());
out.flush(); // out.flush();
out.close(); // out.close();
return false; // return false;
} catch (IOException ex) { // } catch (IOException ex) {
ex.printStackTrace(); // ex.printStackTrace();
log.error("shiro认证失败"); // log.error("shiro认证失败");
} // }
//
} // }
//
// 同步请求走基类 // // 同步请求走基类
return super.onLoginFailure(token, e, request, response); // return super.onLoginFailure(token, e, request, response);
} // }
//
//
/** // /**
* 获取密码 // * 获取密码
* // *
* @param servletRequest // * @param servletRequest
* @return // * @return
*/ // */
@Override // @Override
protected String getPassword(ServletRequest servletRequest) { // protected String getPassword(ServletRequest servletRequest) {
String parameter = servletRequest.getParameter(enPasswordParam); // String parameter = servletRequest.getParameter(enPasswordParam);
HttpServletRequest request = (HttpServletRequest) servletRequest; // HttpServletRequest request = (HttpServletRequest) servletRequest;
String enPasswor = request.getParameter(enPasswordParam); // String enPasswor = request.getParameter(enPasswordParam);
String password = enPasswor; // String password = enPasswor;
return password; // return password;
} // }
//
/** // /**
* 判断是否为Ajax请求 // * 判断是否为Ajax请求
* // *
* @param servletRequest // * @param servletRequest
* @param servletResponse // * @param servletResponse
* @return // * @return
*/ // */
public boolean isAjaxReq(ServletRequest servletRequest, ServletResponse servletResponse) { // public boolean isAjaxReq(ServletRequest servletRequest, ServletResponse servletResponse) {
boolean isAjaxReq = false; // boolean isAjaxReq = false;
HttpServletRequest request = (HttpServletRequest) servletRequest; // HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse; // HttpServletResponse response = (HttpServletResponse) servletResponse;
String requestType = request.getHeader("X-Requested-With"); // String requestType = request.getHeader("X-Requested-With");
if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) { // if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
isAjaxReq = true; // isAjaxReq = true;
} // }
return isAjaxReq; // return isAjaxReq;
} // }
//
public String getEnPasswordParam() { // public String getEnPasswordParam() {
return enPasswordParam; // return enPasswordParam;
} // }
//
public void setEnPasswordParam(String enPasswordParam) { // public void setEnPasswordParam(String enPasswordParam) {
this.enPasswordParam = enPasswordParam; // this.enPasswordParam = enPasswordParam;
} // }
//
public String getUsernameParam() { // public String getUsernameParam() {
return usernameParam; // return usernameParam;
} // }
//
public String getCaptchaIdParam() { // public String getCaptchaIdParam() {
return captchaIdParam; // return captchaIdParam;
} // }
//
public void setCaptchaIdParam(String captchaIdParam) { // public void setCaptchaIdParam(String captchaIdParam) {
this.captchaIdParam = captchaIdParam; // this.captchaIdParam = captchaIdParam;
} // }
//
public String getCaptchaParam() { // public String getCaptchaParam() {
return captchaParam; // return captchaParam;
} // }
//
public void setCaptchaParam(String captchaParam) { // public void setCaptchaParam(String captchaParam) {
this.captchaParam = captchaParam; // this.captchaParam = captchaParam;
} // }
//
} //}
package com.project.shiro.util; //package com.project.shiro.util;
//
import com.alibaba.fastjson.JSONObject; //import com.alibaba.fastjson.JSONObject;
import com.project.model.core.Admin; //import com.project.model.core.Admin;
import com.project.model.core.Menu; //import com.project.model.core.Menu;
import com.project.model.core.Role; //import com.project.model.core.Role;
import com.project.service.core.AdminService; //import com.project.service.core.AdminService;
import com.project.service.core.MenuService; //import com.project.service.core.MenuService;
import org.apache.commons.codec.digest.DigestUtils; //import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils; //import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.DateUtils; //import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils; //import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*; //import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo; //import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission; //import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo; //import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm; //import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection; //import org.apache.shiro.subject.PrincipalCollection;
//
import javax.annotation.Resource; //import javax.annotation.Resource;
import java.io.PrintWriter; //import java.io.PrintWriter;
import java.util.*; //import java.util.*;
//
/** ///**
* 认证 // * 认证
*/ // */
public class AuthenticationRealm extends AuthorizingRealm { //public class AuthenticationRealm extends AuthorizingRealm {
//
@Resource(name = "adminServiceImpl") // @Resource(name = "adminServiceImpl")
private AdminService adminService; // private AdminService adminService;
//
@Resource(name = "menuServiceImpl") // @Resource(name = "menuServiceImpl")
private MenuService menuService; // private MenuService menuService;
//
/** // /**
* 获取认证信息 // * 获取认证信息
*/ // */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken token) {
AuthenticationToken authToken = (AuthenticationToken) token;
// 获取登录名、密码
String username = authToken.getUsername();
String password = new String(authToken.getPassword());
if (username != null && password != null) {
Admin admin = adminService.getByLoginName(username);
if (admin == null) {
throw new UnknownAccountException();
}
if (!admin.getStatus().equals(Admin.STATUS_ENUM.ENABLE.getValue())) {
throw new DisabledAccountException();
}
//用户锁定
if (admin.getIsLocked()) {
//账号锁定分钟数
Date lockedDate = admin.getLockedDate();
Date unlockedDate = DateUtils.addMinutes(lockedDate, 10);
//判断锁定时间是否已过
if (new Date().after(unlockedDate)) {
admin.setLoginFailCnt(0);
admin.setIsLocked(false);
admin.setLockedDate(null);
adminService.update(admin);
} else {
throw new LockedAccountException();
}
}
//密码不正确
if (!DigestUtils.md5Hex(password).equals(admin.getLoginPwd())) {
int loginFailCount = admin.getLoginFailCnt() + 1;
if (loginFailCount >= 5) {
admin.setIsLocked(true);
admin.setLockedDate(new Date());
}
admin.setLoginFailCnt(loginFailCount);
adminService.update(admin);
throw new IncorrectCredentialsException();
}
admin.setLoginFailCnt(0);
adminService.update(admin);
return new SimpleAuthenticationInfo(new Principal(admin.getId(), username), password, getName());
}
throw new UnknownAccountException();
}
/**
* 获取授权信息
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Principal principal = (Principal) principals.fromRealm(getName()).iterator().next();
if (principal != null) {
SimpleAuthorizationInfo authInfo = new SimpleAuthorizationInfo();
//获取admin对象
Admin adminTemp = new Admin();
adminTemp.setId(principal.getId());
List<Admin> admins = adminService.getAdminCascadeRole(adminTemp);
Admin admin = admins.get(0);
//获取用户的角色信息
Set<String> roleSet = new HashSet<String>();
for (Role role : admin.getRoles()) {
if (role.getStatus().equals(Role.STATUS_ENUM.ENABLE.getValue())) {
roleSet.add(role.getRoleCode());
}
}
//根据角色ids获取权限信息
List<Menu> menuList = menuService.findOrdinaryMenu(principal.getId());
Set<String> menuSet = new HashSet<String>();
for (Menu menu : menuList) {
if (StringUtils.isNotBlank(menu.getCode())) {
menuSet.add(menu.getCode());
}
}
//将角色和资源放入授权对象中
authInfo.addRoles(roleSet);
authInfo.addStringPermissions(menuSet);
return authInfo;
}
return null;
}
/**
* 超级管理员自动获取所有权限
*/
// @Override // @Override
// public boolean isPermitted(PrincipalCollection principals, String permission) { // protected AuthenticationInfo doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken token) {
//// User user = ((User) principals.getPrimaryPrincipal()); // AuthenticationToken authToken = (AuthenticationToken) token;
//// if (Role.ADMIN_FLAG_SUPER_ADMIN == user.getRole().getAdminFlag()) { // // 获取登录名、密码
//// return true; // String username = authToken.getUsername();
//// } // String password = new String(authToken.getPassword());
//
// if (username != null && password != null) {
// Admin admin = adminService.getByLoginName(username);
// //
// return isPermitted(principals, getPermissionResolver().resolvePermission(permission)); // if (admin == null) {
// throw new UnknownAccountException();
// }
//
// if (!admin.getStatus().equals(Admin.STATUS_ENUM.ENABLE.getValue())) {
// throw new DisabledAccountException();
// }
//
// //用户锁定
// if (admin.getIsLocked()) {
//
// //账号锁定分钟数
// Date lockedDate = admin.getLockedDate();
// Date unlockedDate = DateUtils.addMinutes(lockedDate, 10);
//
// //判断锁定时间是否已过
// if (new Date().after(unlockedDate)) {
// admin.setLoginFailCnt(0);
// admin.setIsLocked(false);
// admin.setLockedDate(null);
// adminService.update(admin);
// } else {
// throw new LockedAccountException();
// }
// }
//
// //密码不正确
// if (!DigestUtils.md5Hex(password).equals(admin.getLoginPwd())) {
// int loginFailCount = admin.getLoginFailCnt() + 1;
// if (loginFailCount >= 5) {
// admin.setIsLocked(true);
// admin.setLockedDate(new Date());
// }
// admin.setLoginFailCnt(loginFailCount);
// adminService.update(admin);
// throw new IncorrectCredentialsException();
// }
// admin.setLoginFailCnt(0);
// adminService.update(admin);
// return new SimpleAuthenticationInfo(new Principal(admin.getId(), username), password, getName());
// }
// throw new UnknownAccountException();
// } // }
//
@Override // /**
public boolean isPermitted(PrincipalCollection principals, Permission permission) { // * 获取授权信息
AuthorizationInfo info = getAuthorizationInfo(principals); // */
Collection<Permission> perms = getPermissions(info); // @Override
if (CollectionUtils.isEmpty(perms)) { // protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return false; //
} // Principal principal = (Principal) principals.fromRealm(getName()).iterator().next();
//
for (Permission perm : perms) { // if (principal != null) {
if (perm.implies(permission)) { // SimpleAuthorizationInfo authInfo = new SimpleAuthorizationInfo();
return true; //
} // //获取admin对象
} // Admin adminTemp = new Admin();
// adminTemp.setId(principal.getId());
return false; // List<Admin> admins = adminService.getAdminCascadeRole(adminTemp);
} // Admin admin = admins.get(0);
//
/** // //获取用户的角色信息
* 踢掉上一个登录的同名用户 // Set<String> roleSet = new HashSet<String>();
* // for (Role role : admin.getRoles()) {
* @param id 主键 // if (role.getStatus().equals(Role.STATUS_ENUM.ENABLE.getValue())) {
*/ // roleSet.add(role.getRoleCode());
// }
// private void stopPreviousSession(Integer id) {
// Collection<Session> sessions = sessionDAO.getActiveSessions();
// Session currSession = SecurityUtils.getSubject().getSession();
// Serializable sId = currSession.getId();
// for (Session session : sessions) {
// SimplePrincipalCollection collection = (SimplePrincipalCollection) session
// .getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
// if (collection == null) {
// continue;
// } // }
// //
// User u = (User) collection.getPrimaryPrincipal(); // //根据角色ids获取权限信息
// if (id.equals(u.getId())) { // List<Menu> menuList = menuService.findOrdinaryMenu(principal.getId());
// if (sId.equals(session.getId())) { // Set<String> menuSet = new HashSet<String>();
// continue; // for (Menu menu : menuList) {
// if (StringUtils.isNotBlank(menu.getCode())) {
// menuSet.add(menu.getCode());
// } // }
// }
//
// //将角色和资源放入授权对象中
// authInfo.addRoles(roleSet);
// authInfo.addStringPermissions(menuSet);
// return authInfo;
// }
//
// return null;
// }
// //
// session.stop(); // /**
// break; // * 超级管理员自动获取所有权限
// */
//// @Override
//// public boolean isPermitted(PrincipalCollection principals, String permission) {
////// User user = ((User) principals.getPrimaryPrincipal());
////// if (Role.ADMIN_FLAG_SUPER_ADMIN == user.getRole().getAdminFlag()) {
////// return true;
////// }
////
//// return isPermitted(principals, getPermissionResolver().resolvePermission(permission));
//// }
//
// @Override
// public boolean isPermitted(PrincipalCollection principals, Permission permission) {
// AuthorizationInfo info = getAuthorizationInfo(principals);
// Collection<Permission> perms = getPermissions(info);
// if (CollectionUtils.isEmpty(perms)) {
// return false;
// }
//
// for (Permission perm : perms) {
// if (perm.implies(permission)) {
// return true;
// } // }
// } // }
//
// return false;
// } // }
//
// /**
} // * 踢掉上一个登录的同名用户
// *
// * @param id 主键
// */
//
//// private void stopPreviousSession(Integer id) {
//// Collection<Session> sessions = sessionDAO.getActiveSessions();
//// Session currSession = SecurityUtils.getSubject().getSession();
//// Serializable sId = currSession.getId();
//// for (Session session : sessions) {
//// SimplePrincipalCollection collection = (SimplePrincipalCollection) session
//// .getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
//// if (collection == null) {
//// continue;
//// }
////
//// User u = (User) collection.getPrimaryPrincipal();
//// if (id.equals(u.getId())) {
//// if (sId.equals(session.getId())) {
//// continue;
//// }
////
//// session.stop();
//// break;
//// }
//// }
//// }
//
//
//}
package com.project.shiro.util; //package com.project.shiro.util;
//
import org.apache.shiro.authc.UsernamePasswordToken; //import org.apache.shiro.authc.UsernamePasswordToken;
//
/** ///**
* 登录令牌 // * 登录令牌
*/ // */
public class AuthenticationToken extends UsernamePasswordToken { //public class AuthenticationToken extends UsernamePasswordToken {
//
private static final long serialVersionUID = 4628652632307774263L; // private static final long serialVersionUID = 4628652632307774263L;
//
//验证码ID // //验证码ID
private String captchaId; // private String captchaId;
//
//验证码 // //验证码
private String captcha; // private String captcha;
//
//ip保留 // //ip保留
public AuthenticationToken(String loginName, String password, boolean remeberMe, String ip, String captchaId, String caprcha) { // public AuthenticationToken(String loginName, String password, boolean remeberMe, String ip, String captchaId, String caprcha) {
super(loginName, password, remeberMe); // super(loginName, password, remeberMe);
this.captchaId = captchaId; // this.captchaId = captchaId;
this.captcha = caprcha; // this.captcha = caprcha;
} // }
//
public String getCaptchaId() { // public String getCaptchaId() {
return captchaId; // return captchaId;
} // }
//
public void setCaptchaId(String captchaId) { // public void setCaptchaId(String captchaId) {
this.captchaId = captchaId; // this.captchaId = captchaId;
} // }
//
public String getCaptcha() { // public String getCaptcha() {
return captcha; // return captcha;
} // }
//
public void setCaptcha(String captcha) { // public void setCaptcha(String captcha) {
this.captcha = captcha; // this.captcha = captcha;
} // }
//
} //}
package com.project.shiro.util; //package com.project.shiro.util;
//
import com.alibaba.fastjson.JSONObject; //import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ResponseHeader; //import io.swagger.annotations.ResponseHeader;
import org.apache.commons.lang3.StringUtils; //import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter; //import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
//
import javax.servlet.ServletRequest; //import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; //import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; //import javax.servlet.http.HttpServletResponse;
import java.io.IOException; //import java.io.IOException;
import java.io.PrintWriter; //import java.io.PrintWriter;
//
/** ///**
* @author wyy // * @author wyy
* @date 2019-09-14 17:57 // * @date 2019-09-14 17:57
*/ // */
public class AuthorizationFilter extends PermissionsAuthorizationFilter { //public class AuthorizationFilter extends PermissionsAuthorizationFilter {
/** // /**
* shiro认证perms资源失败后回调方法 // * shiro认证perms资源失败后回调方法
* @param servletRequest // * @param servletRequest
* @param servletResponse // * @param servletResponse
* @return // * @return
* @throws IOException // * @throws IOException
*/ // */
@Override // @Override
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException { // protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; // HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; // HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
String requestedWith = httpServletRequest.getHeader("X-Requested-With"); // String requestedWith = httpServletRequest.getHeader("X-Requested-With");
if (StringUtils.isNotEmpty(requestedWith) && StringUtils.equals(requestedWith, "XMLHttpRequest")) {//如果是ajax返回指定格式数据 // if (StringUtils.isNotEmpty(requestedWith) && StringUtils.equals(requestedWith, "XMLHttpRequest")) {//如果是ajax返回指定格式数据
httpServletResponse.setContentType("application/json"); // httpServletResponse.setContentType("application/json");
httpServletResponse.setCharacterEncoding("UTF-8"); // httpServletResponse.setCharacterEncoding("UTF-8");
PrintWriter out = httpServletResponse.getWriter(); // PrintWriter out = httpServletResponse.getWriter();
JSONObject json = new JSONObject(); // JSONObject json = new JSONObject();
json.put("result", "success"); // json.put("result", "success");
json.put("msg", "登录成功"); // json.put("msg", "登录成功");
out.write(json.toJSONString()); // out.write(json.toJSONString());
out.flush(); // out.flush();
out.close(); // out.close();
} else {//如果是普通请求进行重定向 // } else {//如果是普通请求进行重定向
httpServletResponse.sendRedirect("/403"); // httpServletResponse.sendRedirect("/403");
} // }
return false; // return false;
} // }
} //}
package com.project.shiro.util; //package com.project.shiro.util;
//
import java.io.Serializable; //import java.io.Serializable;
//
public class Principal implements Serializable { //public class Principal implements Serializable {
//
private static final long serialVersionUID = 598764316789461315L; // private static final long serialVersionUID = 598764316789461315L;
//
public Long id; // public Long id;
//
public String loginName; // public String loginName;
//
public Principal(Long id, String loginName) { // public Principal(Long id, String loginName) {
this.id = id; // this.id = id;
this.loginName = loginName; // this.loginName = loginName;
} // }
//
public Principal() { // public Principal() {
//
} // }
//
public Long getId() { // public Long getId() {
return id; // return id;
} // }
//
public void setId(Long id) { // public void setId(Long id) {
this.id = id; // this.id = id;
} // }
//
public String getLoginName() { // public String getLoginName() {
return loginName; // return loginName;
} // }
//
public void setLoginName(String loginName) { // public void setLoginName(String loginName) {
this.loginName = loginName; // this.loginName = loginName;
} // }
//
} //}
package com.project.shiro.util.redis; //package com.project.shiro.util.redis;
//
import cn.wisenergy.service.common.utils.ByteUtil; //import cn.wisenergy.service.common.utils.ByteUtil;
import cn.wisenergy.service.common.utils.redis.RedisClient; //import cn.wisenergy.service.common.utils.redis.RedisClient;
import cn.wisenergy.service.common.utils.redis.RedisConsts; //import cn.wisenergy.service.common.utils.redis.RedisConsts;
import org.apache.shiro.cache.Cache; //import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException; //import org.apache.shiro.cache.CacheException;
import org.apache.shiro.util.CollectionUtils; //import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger; //import org.slf4j.Logger;
import org.slf4j.LoggerFactory; //import org.slf4j.LoggerFactory;
//
import javax.annotation.Resource; //import javax.annotation.Resource;
import java.io.IOException; //import java.io.IOException;
import java.util.*; //import java.util.*;
//
public class ShiroRedisCache<K, V> implements Cache<K, V> { //public class ShiroRedisCache<K, V> implements Cache<K, V> {
//
//初始化Log日志 // //初始化Log日志
private Logger logger = LoggerFactory.getLogger(this.getClass()); // private Logger logger = LoggerFactory.getLogger(this.getClass());
//
//注入redisClient实例 // //注入redisClient实例
@Resource(name = "redisClient") // @Resource(name = "redisClient")
private RedisClient redisClient; // private RedisClient redisClient;
//
//shiroSession的key值前缀 // //shiroSession的key值前缀
private String keyPrefix; // private String keyPrefix;
//
//通过redisClient实例和prefix参数构造redisCache // //通过redisClient实例和prefix参数构造redisCache
public ShiroRedisCache(RedisClient redisClient, String prefix) { // public ShiroRedisCache(RedisClient redisClient, String prefix) {
if (redisClient == null) { // if (redisClient == null) {
throw new IllegalArgumentException("shiroRedisCahe初始化时,redisClient参数不能为空"); // throw new IllegalArgumentException("shiroRedisCahe初始化时,redisClient参数不能为空");
} // }
this.redisClient = redisClient; // this.redisClient = redisClient;
this.keyPrefix = prefix; // this.keyPrefix = prefix;
} // }
//
/** // /**
* 获得String类型的KEY // * 获得String类型的KEY
* // *
* @param key // * @param key
* @return // * @return
*/ // */
private String getPreStringKey(K key) { // private String getPreStringKey(K key) {
String preKey = null; // String preKey = null;
if (key instanceof String) { // if (key instanceof String) {
preKey = this.keyPrefix + key; // preKey = this.keyPrefix + key;
return preKey; // return preKey;
} else { // } else {
try { // try {
preKey = keyPrefix + ByteUtil.bytesToHexString(ByteUtil.objectToBytes(key)); // preKey = keyPrefix + ByteUtil.bytesToHexString(ByteUtil.objectToBytes(key));
} catch (IOException e) { // } catch (IOException e) {
e.printStackTrace(); // e.printStackTrace();
} // }
return preKey; // return preKey;
} // }
} // }
//
@Override // @Override
public V get(K key) throws CacheException { // public V get(K key) throws CacheException {
logger.debug("根据key从Redis中获取对象 key [" + key + "]"); // logger.debug("根据key从Redis中获取对象 key [" + key + "]");
try { // try {
if (key == null) { // if (key == null) {
return null; // return null;
} else { // } else {
V Vvalue = (V) redisClient.get(getPreStringKey(key)); // V Vvalue = (V) redisClient.get(getPreStringKey(key));
if (Vvalue == null) { // if (Vvalue == null) {
return null; // return null;
} // }
return Vvalue; // return Vvalue;
} // }
} catch (Throwable t) { // } catch (Throwable t) {
throw new CacheException(t); // throw new CacheException(t);
} // }
//
} // }
//
@Override // @Override
public V put(K key, V value) throws CacheException { // public V put(K key, V value) throws CacheException {
logger.debug("根据key从存储 key [" + key + "]"); // logger.debug("根据key从存储 key [" + key + "]");
try { // try {
redisClient.set(getPreStringKey(key), value); // redisClient.set(getPreStringKey(key), value);
redisClient.setAndExpire(getPreStringKey(key), value, RedisConsts.ADMIN_SHIRO_REALM_EXPIRE); // redisClient.setAndExpire(getPreStringKey(key), value, RedisConsts.ADMIN_SHIRO_REALM_EXPIRE);
return value; // return value;
} catch (Throwable t) { // } catch (Throwable t) {
throw new CacheException(t); // throw new CacheException(t);
} // }
} // }
//
@Override // @Override
public V remove(K key) throws CacheException { // public V remove(K key) throws CacheException {
logger.debug("从redis中删除 key [" + key + "]"); // logger.debug("从redis中删除 key [" + key + "]");
try { // try {
V previous = get(key); // V previous = get(key);
redisClient.del(getPreStringKey(key)); // redisClient.del(getPreStringKey(key));
return previous; // return previous;
} catch (Throwable t) { // } catch (Throwable t) {
throw new CacheException(t); // throw new CacheException(t);
} // }
} // }
//
@Override // @Override
public void clear() throws CacheException { // public void clear() throws CacheException {
logger.debug("从redis中删除所有元素"); // logger.debug("从redis中删除所有元素");
try { // try {
// redisClient.flushDB(); //// redisClient.flushDB();
} catch (Throwable t) { // } catch (Throwable t) {
throw new CacheException(t); // throw new CacheException(t);
} // }
} // }
//
@Override // @Override
public int size() { // public int size() {
// try { //// try {
// Long longSize = new Long(redisClient.dbSize()); //// Long longSize = new Long(redisClient.dbSize());
// return longSize.intValue(); //// return longSize.intValue();
//// } catch (Throwable t) {
//// throw new CacheException(t);
//// }
// return 0;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public Set<K> keys() {
// try {
// Set<byte[]> keys = redisClient.keys(ByteUtil.objectToBytes(this.keyPrefix + "*"));
// if (CollectionUtils.isEmpty(keys)) {
// return Collections.emptySet();
// } else {
// Set<K> newKeys = new HashSet<K>();
// for (byte[] key : keys) {
// newKeys.add((K) key);
// }
// return newKeys;
// }
// } catch (Throwable t) {
// throw new CacheException(t);
// }
// }
//
// @Override
// public Collection<V> values() {
// try {
// Set<byte[]> keys = redisClient.keys(ByteUtil.objectToBytes(this.keyPrefix + "*"));
// if (!CollectionUtils.isEmpty(keys)) {
// List<V> values = new ArrayList<V>(keys.size());
// for (byte[] key : keys) {
// @SuppressWarnings("unchecked")
// V value = get((K) key);
// if (value != null) {
// values.add(value);
// }
// }
// return Collections.unmodifiableList(values);
// } else {
// return Collections.emptyList();
// }
// } catch (Throwable t) { // } catch (Throwable t) {
// throw new CacheException(t); // throw new CacheException(t);
// } // }
return 0; // }
} //
// public String getKeyPrefix() {
@SuppressWarnings("unchecked") // return keyPrefix;
@Override // }
public Set<K> keys() { //
try { // public void setKeyPrefix(String keyPrefix) {
Set<byte[]> keys = redisClient.keys(ByteUtil.objectToBytes(this.keyPrefix + "*")); // this.keyPrefix = keyPrefix;
if (CollectionUtils.isEmpty(keys)) { // }
return Collections.emptySet(); //
} else { // public RedisClient getRedisClient() {
Set<K> newKeys = new HashSet<K>(); // return redisClient;
for (byte[] key : keys) { // }
newKeys.add((K) key); //
} // public void setRedisClient(RedisClient redisClient) {
return newKeys; // this.redisClient = redisClient;
} // }
} catch (Throwable t) { //}
throw new CacheException(t);
}
}
@Override
public Collection<V> values() {
try {
Set<byte[]> keys = redisClient.keys(ByteUtil.objectToBytes(this.keyPrefix + "*"));
if (!CollectionUtils.isEmpty(keys)) {
List<V> values = new ArrayList<V>(keys.size());
for (byte[] key : keys) {
@SuppressWarnings("unchecked")
V value = get((K) key);
if (value != null) {
values.add(value);
}
}
return Collections.unmodifiableList(values);
} else {
return Collections.emptyList();
}
} catch (Throwable t) {
throw new CacheException(t);
}
}
public String getKeyPrefix() {
return keyPrefix;
}
public void setKeyPrefix(String keyPrefix) {
this.keyPrefix = keyPrefix;
}
public RedisClient getRedisClient() {
return redisClient;
}
public void setRedisClient(RedisClient redisClient) {
this.redisClient = redisClient;
}
}
package com.project.shiro.util.redis; //package com.project.shiro.util.redis;
//
//
import cn.wisenergy.service.common.utils.redis.RedisClient; //import cn.wisenergy.service.common.utils.redis.RedisClient;
import cn.wisenergy.service.common.utils.redis.RedisConsts; //import cn.wisenergy.service.common.utils.redis.RedisConsts;
import org.apache.shiro.cache.Cache; //import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException; //import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager; //import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger; //import org.slf4j.Logger;
import org.slf4j.LoggerFactory; //import org.slf4j.LoggerFactory;
//
import javax.annotation.Resource; //import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap; //import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; //import java.util.concurrent.ConcurrentMap;
//
public class ShiroRedisCacheManager implements CacheManager { //public class ShiroRedisCacheManager implements CacheManager {
//
private static final Logger logger = LoggerFactory.getLogger(ShiroRedisCacheManager.class); // private static final Logger logger = LoggerFactory.getLogger(ShiroRedisCacheManager.class);
//
private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>(); // private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>();
//
//注入redisClient实例 // //注入redisClient实例
@Resource(name = "redisClient") // @Resource(name = "redisClient")
private RedisClient redisClient; // private RedisClient redisClient;
//
/** // /**
* shiro权限缓存前缀 // * shiro权限缓存前缀
*/ // */
private String keyPrefix = RedisConsts.ADMIN_SHIRO_REALM_KEY; // private String keyPrefix = RedisConsts.ADMIN_SHIRO_REALM_KEY;
//
//
@Override // @Override
public <K, V> Cache<K, V> getCache(String name) throws CacheException { // public <K, V> Cache<K, V> getCache(String name) throws CacheException {
//
logger.debug("获取名称为: " + name + " 的RedisCache实例"); // logger.debug("获取名称为: " + name + " 的RedisCache实例");
Cache c = caches.get(keyPrefix + name); // Cache c = caches.get(keyPrefix + name);
if (c == null) { // if (c == null) {
c = new ShiroRedisCache<K, V>(redisClient, keyPrefix); // c = new ShiroRedisCache<K, V>(redisClient, keyPrefix);
caches.put(keyPrefix + name, c); // caches.put(keyPrefix + name, c);
} // }
return c; // return c;
} // }
//
public RedisClient getRedisClient() { // public RedisClient getRedisClient() {
return redisClient; // return redisClient;
} // }
//
public void setRedisClient(RedisClient redisClient) { // public void setRedisClient(RedisClient redisClient) {
this.redisClient = redisClient; // this.redisClient = redisClient;
} // }
//
public String getKeyPrefix() { // public String getKeyPrefix() {
return keyPrefix; // return keyPrefix;
} // }
//
public void setKeyPrefix(String keyPrefix) { // public void setKeyPrefix(String keyPrefix) {
this.keyPrefix = keyPrefix; // this.keyPrefix = keyPrefix;
} // }
} //}
package com.project.shiro.util.redis; //package com.project.shiro.util.redis;
//
import cn.wisenergy.service.common.utils.ByteUtil; //import cn.wisenergy.service.common.utils.ByteUtil;
import cn.wisenergy.service.common.utils.redis.RedisClient; //import cn.wisenergy.service.common.utils.redis.RedisClient;
import cn.wisenergy.service.common.utils.redis.RedisConsts; //import cn.wisenergy.service.common.utils.redis.RedisConsts;
import org.apache.shiro.session.Session; //import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException; //import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO; //import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger; //import org.slf4j.Logger;
import org.slf4j.LoggerFactory; //import org.slf4j.LoggerFactory;
//
import javax.annotation.Resource; //import javax.annotation.Resource;
import java.io.IOException; //import java.io.IOException;
import java.io.Serializable; //import java.io.Serializable;
import java.util.Collection; //import java.util.Collection;
import java.util.HashSet; //import java.util.HashSet;
import java.util.Set; //import java.util.Set;
//
public class ShiroRedisSessionDAO extends AbstractSessionDAO { //public class ShiroRedisSessionDAO extends AbstractSessionDAO {
//
private static Logger logger = LoggerFactory.getLogger(ShiroRedisSessionDAO.class); // private static Logger logger = LoggerFactory.getLogger(ShiroRedisSessionDAO.class);
//
//注入redisClient实例 // //注入redisClient实例
@Resource(name = "redisClient") // @Resource(name = "redisClient")
private RedisClient redisClient; // private RedisClient redisClient;
//
/** // /**
* shiro-redis的session对象前缀 // * shiro-redis的session对象前缀
*/ // */
//
private String keyPrefix = RedisConsts.ADMIN_SHIRO_SESSION_KEY; // private String keyPrefix = RedisConsts.ADMIN_SHIRO_SESSION_KEY;
//
@Override // @Override
public void update(Session session) throws UnknownSessionException { // public void update(Session session) throws UnknownSessionException {
this.saveSession(session); // this.saveSession(session);
} // }
//
private void saveSession(Session session) throws UnknownSessionException { // private void saveSession(Session session) throws UnknownSessionException {
if (session == null || session.getId() == null) { // if (session == null || session.getId() == null) {
logger.error("session or session id is null"); // logger.error("session or session id is null");
return; // return;
} // }
this.redisClient.setAndExpire(this.getPreStringKey(session.getId()), session, RedisConsts.ADMIN_SHIRO_SESSION_EXPIRE); // this.redisClient.setAndExpire(this.getPreStringKey(session.getId()), session, RedisConsts.ADMIN_SHIRO_SESSION_EXPIRE);
} // }
//
@Override // @Override
public void delete(Session session) { // public void delete(Session session) {
if (session == null || session.getId() == null) { // if (session == null || session.getId() == null) {
logger.error("session or session id is null"); // logger.error("session or session id is null");
return; // return;
} // }
redisClient.del(getPreStringKey(session.getId())); // redisClient.del(getPreStringKey(session.getId()));
//
} // }
//
@Override // @Override
public Collection<Session> getActiveSessions() { // public Collection<Session> getActiveSessions() {
Set<Session> sessions = new HashSet<Session>(); // Set<Session> sessions = new HashSet<Session>();
//
Set<byte[]> keys = null; // Set<byte[]> keys = null;
try { // try {
keys = redisClient.keys(ByteUtil.objectToBytes(this.keyPrefix + "*")); // keys = redisClient.keys(ByteUtil.objectToBytes(this.keyPrefix + "*"));
} catch (IOException e) { // } catch (IOException e) {
e.printStackTrace(); // e.printStackTrace();
} // }
if (keys != null && keys.size() > 0) { // if (keys != null && keys.size() > 0) {
for (byte[] key : keys) { // for (byte[] key : keys) {
Session s = null; // Session s = null;
try { // try {
s = (Session) ByteUtil.bytesToObject(redisClient.get(key)); // s = (Session) ByteUtil.bytesToObject(redisClient.get(key));
} catch (IOException e) { // } catch (IOException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (ClassNotFoundException e) { // } catch (ClassNotFoundException e) {
e.printStackTrace(); // e.printStackTrace();
} // }
sessions.add(s); // sessions.add(s);
} // }
} // }
//
return sessions; // return sessions;
} // }
//
@Override // @Override
protected Serializable doCreate(Session session) { // protected Serializable doCreate(Session session) {
Serializable sessionId = this.generateSessionId(session); // Serializable sessionId = this.generateSessionId(session);
this.assignSessionId(session, sessionId); // this.assignSessionId(session, sessionId);
this.saveSession(session); // this.saveSession(session);
return sessionId; // return sessionId;
} // }
//
@Override // @Override
protected Session doReadSession(Serializable sessionId) { // protected Session doReadSession(Serializable sessionId) {
if (sessionId == null) { // if (sessionId == null) {
logger.error("session id is null"); // logger.error("session id is null");
return null; // return null;
} // }
//
Session s = (Session) redisClient.get(this.getPreStringKey(sessionId)); // Session s = (Session) redisClient.get(this.getPreStringKey(sessionId));
return s; // return s;
} // }
//
/** // /**
* 获得String类型的key // * 获得String类型的key
* // *
* @param // * @param
* @return // * @return
*/ // */
private String getPreStringKey(Serializable sessionId) { // private String getPreStringKey(Serializable sessionId) {
String preKey = this.keyPrefix + sessionId; // String preKey = this.keyPrefix + sessionId;
return preKey; // return preKey;
} // }
//
public String getKeyPrefix() { // public String getKeyPrefix() {
return keyPrefix; // return keyPrefix;
} // }
//
public void setKeyPrefix(String keyPrefix) { // public void setKeyPrefix(String keyPrefix) {
this.keyPrefix = keyPrefix; // this.keyPrefix = keyPrefix;
} // }
//
public void setRedisClient(RedisClient redisClient) { // public void setRedisClient(RedisClient redisClient) {
this.redisClient = redisClient; // this.redisClient = redisClient;
} // }
//
public RedisClient getRedisClient() { // public RedisClient getRedisClient() {
return redisClient; // return redisClient;
} // }
//
} //}
...@@ -51,7 +51,7 @@ public class MvcConfiguration extends WebMvcConfigurationSupport { ...@@ -51,7 +51,7 @@ public class MvcConfiguration extends WebMvcConfigurationSupport {
@Override @Override
public void addCorsMappings(CorsRegistry registry) { public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") registry.addMapping("/**")
.allowedOrigins("*") .allowedOriginPatterns("*")
.allowedHeaders("*") .allowedHeaders("*")
.allowedMethods("*") .allowedMethods("*")
.allowCredentials(true) .allowCredentials(true)
......
package cn.wisenergy.web.sms.interceptor; package cn.wisenergy.web.sms.interceptor;
import cn.wisenergy.common.enums.ResultEnum; import cn.wisenergy.common.enums.ResultEnum;
import cn.wisenergy.common.utils.Constants;
import cn.wisenergy.common.utils.RedisUtils; import cn.wisenergy.common.utils.RedisUtils;
import cn.wisenergy.common.utils.ResponseOutput; import cn.wisenergy.common.utils.ResponseOutput;
import cn.wisenergy.common.utils.StringUtil; import cn.wisenergy.common.utils.StringUtil;
......
...@@ -3,9 +3,9 @@ spring: ...@@ -3,9 +3,9 @@ spring:
type: com.alibaba.druid.pool.DruidDataSource type: com.alibaba.druid.pool.DruidDataSource
druid: druid:
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.110.164:3306/shop_app?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=GMT%2B8 url: jdbc:mysql://39.97.107.31:3306/qunzhihe?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=GMT%2B8
username: root username: qunzhihe
password: adm4HYservice$ password: j2kRn8HjrPez7trw
initial-size: 10 initial-size: 10
max-active: 100 max-active: 100
min-idle: 10 min-idle: 10
...@@ -46,9 +46,9 @@ spring: ...@@ -46,9 +46,9 @@ spring:
# 192.168.110.165 adm4HYservice$ # 192.168.110.165 adm4HYservice$
redis: redis:
database: 0 database: 0
host: 127.0.0.1 host: 39.97.107.31
port: 6379 port: 6379
password: 123456 # 密码(默认为空) password: 1qaz@WSX # 密码(默认为空)
timeout: 6000ms # 连接超时时长(毫秒) timeout: 6000ms # 连接超时时长(毫秒)
jedis: jedis:
pool: pool:
......
...@@ -3,7 +3,7 @@ spring: ...@@ -3,7 +3,7 @@ spring:
type: com.alibaba.druid.pool.DruidDataSource type: com.alibaba.druid.pool.DruidDataSource
druid: druid:
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/qunzhihe?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8 url: jdbc:mysql://39.97.107.31:3306/qunzhihe?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
username: qunzhihe username: qunzhihe
password: j2kRn8HjrPez7trw password: j2kRn8HjrPez7trw
initial-size: 10 initial-size: 10
...@@ -34,15 +34,16 @@ spring: ...@@ -34,15 +34,16 @@ spring:
multi-statement-allow: true multi-statement-allow: true
#/www/server/redis/src/redis-server #/www/server/redis/src/redis-server
redis: redis:
open: false # 是否开启redis缓存 true开启 false关闭
database: 0 database: 0
host: localhost host: 39.97.107.31
port: 6379 port: 6379
password: password: 1qaz@WSX # 密码(默认为空)
timeout: 6000ms timeout: 6000ms # 连接超时时长(毫秒)
jedis: jedis:
pool: pool:
max-active: 1000 # 连接池最大连接数(使用负值表示没有限制) max-active: 1000 # 连接池最大连接数(使用负值表示没有限制)
max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制) max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 10 # 连接池中的最大空闲连接 max-idle: 10 # 连接池中的最大空闲连接
min-idle: 5 # 连接池中的最小空闲连接 min-idle: 5 # 连接池中的最小空闲连接
#jwt: #jwt:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment