Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in / Register
Toggle navigation
S
shop-Mall
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
licc
shop-Mall
Commits
34ad5d18
Commit
34ad5d18
authored
Mar 04, 2021
by
m1991
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
解决启动报错
parent
4272103d
Show whitespace changes
Inline
Side-by-side
Showing
13 changed files
with
1156 additions
and
1183 deletions
+1156
-1183
pom.xml
pom.xml
+1
-1
FileUploadConfig.java
...ava/cn/wisenergy/common/config/file/FileUploadConfig.java
+0
-29
User.java
...ergy-model/src/main/java/cn/wisenergy/model/app/User.java
+10
-9
ShiroConfig.java
...o/src/main/java/com/project/shiro/config/ShiroConfig.java
+195
-195
AuthenticationFilter.java
...ain/java/com/project/shiro/util/AuthenticationFilter.java
+275
-275
AuthenticationRealm.java
...main/java/com/project/shiro/util/AuthenticationRealm.java
+185
-185
AuthenticationToken.java
...main/java/com/project/shiro/util/AuthenticationToken.java
+41
-41
AuthorizationFilter.java
...main/java/com/project/shiro/util/AuthorizationFilter.java
+47
-47
Principal.java
...shiro/src/main/java/com/project/shiro/util/Principal.java
+38
-38
ShiroRedisCache.java
...in/java/com/project/shiro/util/redis/ShiroRedisCache.java
+175
-175
ShiroRedisCacheManager.java
.../com/project/shiro/util/redis/ShiroRedisCacheManager.java
+59
-59
ShiroRedisSessionDAO.java
...va/com/project/shiro/util/redis/ShiroRedisSessionDAO.java
+129
-129
LoginInterceptor.java
...va/cn/wisenergy/web/sms/interceptor/LoginInterceptor.java
+1
-0
No files found.
pom.xml
View file @
34ad5d18
...
...
@@ -39,7 +39,7 @@
<module>
wisenergy-model
</module>
<module>
wisenergy-mapper
</module>
<module>
wisenergy-service
</module>
<
module>
wisenergy-shiro
</module
>
<
!--<module>wisenergy-shiro</module>--
>
<module>
wisenergy-web-admin
</module>
</modules>
...
...
wisenergy-common/src/main/java/cn/wisenergy/common/config/file/FileUploadConfig.java
deleted
100644 → 0
View file @
4272103d
package
cn
.
wisenergy
.
common
.
config
.
file
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.web.multipart.MultipartResolver
;
import
org.springframework.web.multipart.commons.CommonsMultipartResolver
;
/**
* 文件上传配置
* @author wyy
* @date 2019-08-22 19:20
*/
@Configuration
public
class
FileUploadConfig
{
/**
* 重新定义文件上传对象【springBoot request转化成MultipartHttpServletRequest】
* @return
*/
@Bean
(
name
=
"multipartResolver"
)
public
MultipartResolver
multipartResolver
()
{
CommonsMultipartResolver
resolver
=
new
CommonsMultipartResolver
();
resolver
.
setDefaultEncoding
(
"UTF-8"
);
resolver
.
setResolveLazily
(
true
);
resolver
.
setMaxInMemorySize
(
40960
);
resolver
.
setMaxUploadSize
(
512
*
1024
*
1024
);
return
resolver
;
}
}
wisenergy-model/src/main/java/cn/wisenergy/model/app/User.java
View file @
34ad5d18
package
cn
.
wisenergy
.
model
.
app
;
import
com.baomidou.mybatisplus.annotation.TableField
;
import
com.baomidou.mybatisplus.annotation.TableId
;
import
com.baomidou.mybatisplus.annotation.TableName
;
import
com.baomidou.mybatisplus.extension.activerecord.Model
;
...
...
@@ -34,14 +35,14 @@ public class User extends Model<User> implements Serializable{
* 手机号作为用户账号
*/
@ApiModelProperty
(
name
=
"user_id"
,
value
=
"用户主键id"
)
@Table
I
d
(
"user_id"
)
@Table
Fiel
d
(
"user_id"
)
private
String
userId
;
/**
* 密码
*/
@ApiModelProperty
(
name
=
"password"
,
value
=
"用户密码"
)
@Table
I
d
(
"password"
)
@Table
Fiel
d
(
"password"
)
private
String
password
;
...
...
@@ -49,49 +50,49 @@ public class User extends Model<User> implements Serializable{
* 用户会员等级
*/
@ApiModelProperty
(
name
=
"user_level"
,
value
=
"用户会员等级"
)
@Table
I
d
(
"user_level"
)
@Table
Fiel
d
(
"user_level"
)
private
int
userLevel
;
/**
* 跨境额度
*/
@ApiModelProperty
(
name
=
"cross_border_line"
,
value
=
"跨境额度"
)
@Table
I
d
(
"cross_border_line"
)
@Table
Fiel
d
(
"cross_border_line"
)
private
BigDecimal
crossBorderLine
;
/**
* 身份证号码
*/
@ApiModelProperty
(
name
=
"id_card_number"
,
value
=
"身份证号码"
)
@Table
I
d
(
"id_card_number"
)
@Table
Fiel
d
(
"id_card_number"
)
private
String
idCardNumber
;
/**
* 粉丝昵称
*/
@ApiModelProperty
(
name
=
"fans_nickname"
,
value
=
"粉丝昵称"
)
@Table
I
d
(
"fans_nickname"
)
@Table
Fiel
d
(
"fans_nickname"
)
private
String
fansNickname
;
/**
* 有赞粉丝id,有赞自动生成
*/
@ApiModelProperty
(
name
=
"fans_id"
,
value
=
"有赞粉丝id,有赞自动生成"
)
@Table
I
d
(
"fans_id"
)
@Table
Fiel
d
(
"fans_id"
)
private
String
fansId
;
/**
* 用户本人邀请码
*/
@ApiModelProperty
(
name
=
"invite_code"
,
value
=
"用户本人邀请码"
)
@Table
I
d
(
"invite_code"
)
@Table
Fiel
d
(
"invite_code"
)
private
String
inviteCode
;
/**
* 推荐人邀请码
*/
@ApiModelProperty
(
name
=
"be_invited_code"
,
value
=
"推荐人邀请码"
)
@Table
I
d
(
"be_invited_code"
)
@Table
Fiel
d
(
"be_invited_code"
)
private
String
beInvitedCode
;
/**
...
...
wisenergy-shiro/src/main/java/com/project/shiro/config/ShiroConfig.java
View file @
34ad5d18
package
com
.
project
.
shiro
.
config
;
import
com.project.shiro.util.AuthenticationFilter
;
import
com.project.shiro.util.AuthenticationRealm
;
import
com.project.shiro.util.AuthorizationFilter
;
import
com.project.shiro.util.redis.ShiroRedisCacheManager
;
import
com.project.shiro.util.redis.ShiroRedisSessionDAO
;
import
org.apache.shiro.session.mgt.SessionManager
;
import
org.apache.shiro.spring.LifecycleBeanPostProcessor
;
import
org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor
;
import
org.apache.shiro.spring.web.ShiroFilterFactoryBean
;
import
org.apache.shiro.web.mgt.DefaultWebSecurityManager
;
import
org.apache.shiro.web.servlet.SimpleCookie
;
import
org.apache.shiro.web.session.mgt.DefaultWebSessionManager
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.context.annotation.DependsOn
;
import
javax.servlet.Filter
;
import
java.util.HashMap
;
import
java.util.LinkedHashMap
;
import
java.util.Map
;
/**
* Description: shiro配置类
* User: mxy
* Date: 2019-04-16
*/
@Configuration
public
class
ShiroConfig
{
private
static
final
transient
Logger
logger
=
LoggerFactory
.
getLogger
(
ShiroConfig
.
class
);
/**
* 配置拦截器
* <p>
* 定义拦截URL权限,优先级从上到下
* 1). anon : 匿名访问,无需登录
* 2). authc : 登录后才能访问
* 3). logout: 登出
* 4). frameperms : 自定义的过滤器
* <p>
* URL 匹配风格
* 1). ?:匹配一个字符,如 /admin? 将匹配 /admin1,但不匹配 /admin 或 /admin/;
* 2). *:匹配零个或多个字符串,如 /admin* 将匹配 /admin 或/admin123,但不匹配 /admin/1;
* 3). **:匹配路径中的零个或多个路径,如 /admin/** 将匹配 /admin/a 或 /admin/a/b
* <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次加密
*/
//package com.project.shiro.config;
//
//import com.project.shiro.util.AuthenticationFilter;
//import com.project.shiro.util.AuthenticationRealm;
//import com.project.shiro.util.AuthorizationFilter;
//import com.project.shiro.util.redis.ShiroRedisCacheManager;
//import com.project.shiro.util.redis.ShiroRedisSessionDAO;
//import org.apache.shiro.session.mgt.SessionManager;
//import org.apache.shiro.spring.LifecycleBeanPostProcessor;
//import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
//import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
//import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
//import org.apache.shiro.web.servlet.SimpleCookie;
//import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.context.annotation.DependsOn;
//
//import javax.servlet.Filter;
//import java.util.HashMap;
//import java.util.LinkedHashMap;
//import java.util.Map;
//
///**
// * Description: shiro配置类
// * User: mxy
// * Date: 2019-04-16
// */
//@Configuration
//public class ShiroConfig {
//
// private static final transient Logger logger = LoggerFactory.getLogger(ShiroConfig.class);
//
// /**
// * 配置拦截器
// * <p>
// * 定义拦截URL权限,优先级从上到下
// * 1). anon : 匿名访问,无需登录
// * 2). authc : 登录后才能访问
// * 3). logout: 登出
// * 4). frameperms : 自定义的过滤器
// * <p>
// * URL 匹配风格
// * 1). ?:匹配一个字符,如 /admin? 将匹配 /admin1,但不匹配 /admin 或 /admin/;
// * 2). *:匹配零个或多个字符串,如 /admin* 将匹配 /admin 或/admin123,但不匹配 /admin/1;
// * 3). **:匹配路径中的零个或多个路径,如 /admin/** 将匹配 /admin/a 或 /admin/a/b
// * <p>
// * 配置身份验证成功,失败的跳转路径
// */
// @Bean
// public HashedCredentialsMatcher hashedCredentialsMatcher() {
// HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
// hashedCredentialsMatcher.setHashAlgorithmName("MD5");
// hashedCredentialsMatcher.setHashIterations(1024);
// return hashedCredentialsMatcher;
// 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;
// }
/**
* SecurityManager 安全管理器;Shiro的核心
*/
@Bean
public
DefaultWebSecurityManager
securityManager
()
{
DefaultWebSecurityManager
securityManager
=
new
DefaultWebSecurityManager
();
// 自定义的Realm
securityManager
.
setRealm
(
authenticationShiroRealm
());
// 缓存管理
securityManager
.
setCacheManager
(
shiroRedisCacheManager
());
// 会话管理
securityManager
.
setSessionManager
(
sessionManager
());
return
securityManager
;
}
/**
* 自定义Realm,可以多个
*/
@Bean
public
AuthenticationRealm
authenticationShiroRealm
()
{
AuthenticationRealm
authenticationRealm
=
new
AuthenticationRealm
();
//authenticationRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return
authenticationRealm
;
}
/**
* redis缓存管理
*/
@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
();
}
}
//
// /**
// * 配置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
//// public HashedCredentialsMatcher hashedCredentialsMatcher() {
//// HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
//// hashedCredentialsMatcher.setHashAlgorithmName("MD5");
//// hashedCredentialsMatcher.setHashIterations(1024);
//// return hashedCredentialsMatcher;
//// }
//
// /**
// * SecurityManager 安全管理器;Shiro的核心
// */
// @Bean
// public DefaultWebSecurityManager securityManager() {
// DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// // 自定义的Realm
// securityManager.setRealm(authenticationShiroRealm());
// // 缓存管理
// securityManager.setCacheManager(shiroRedisCacheManager());
// // 会话管理
// securityManager.setSessionManager(sessionManager());
// return securityManager;
// }
//
// /**
// * 自定义Realm,可以多个
// */
// @Bean
// public AuthenticationRealm authenticationShiroRealm() {
// AuthenticationRealm authenticationRealm = new AuthenticationRealm();
// //authenticationRealm.setCredentialsMatcher(hashedCredentialsMatcher());
// return authenticationRealm;
// }
//
// /**
// * redis缓存管理
// */
// @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();
// }
//
//}
wisenergy-shiro/src/main/java/com/project/shiro/util/AuthenticationFilter.java
View file @
34ad5d18
package
com
.
project
.
shiro
.
util
;
import
com.alibaba.fastjson.JSONObject
;
import
org.apache.shiro.authc.AuthenticationException
;
import
org.apache.shiro.authc.AuthenticationToken
;
import
org.apache.shiro.subject.Subject
;
import
org.apache.shiro.util.StringUtils
;
import
org.apache.shiro.web.filter.authc.FormAuthenticationFilter
;
import
org.apache.shiro.web.util.WebUtils
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
javax.servlet.ServletRequest
;
import
javax.servlet.ServletResponse
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
java.io.IOException
;
import
java.io.PrintWriter
;
/**
* 自定义表单认证过滤器
*
* @author wyy
* @date 2019/07/26
*/
public
class
AuthenticationFilter
extends
FormAuthenticationFilter
{
private
static
final
Logger
log
=
LoggerFactory
.
getLogger
(
AuthenticationFilter
.
class
);
//加密密码参数
private
static
final
String
DEFAULT_EN_PASSWORD_PARAM
=
"enPassword"
;
//默认的登录名称
private
static
final
String
DEFAULT_USERNAME_PARAM
=
"loginName"
;
//默认验证码ID参数
private
static
final
String
DEFAULT_CAPTCHA_ID_PARAM
=
"captchaId"
;
//默认验证码参数
private
static
final
String
DEFAULT_CAPTCHA_PARAM
=
"captcha"
;
private
String
captchaIdParam
=
DEFAULT_CAPTCHA_ID_PARAM
;
private
String
captchaParam
=
DEFAULT_CAPTCHA_PARAM
;
private
String
usernameParam
=
DEFAULT_USERNAME_PARAM
;
private
String
enPasswordParam
=
DEFAULT_EN_PASSWORD_PARAM
;
/**
* 创建token
*/
@Override
protected
AuthenticationToken
createToken
(
ServletRequest
request
,
ServletResponse
response
)
{
String
loginName
=
getUsername
(
request
);
String
password
=
getPassword
(
request
);
boolean
isRemeberMe
=
isRememberMe
(
request
);
String
ip
=
getHost
(
request
);
return
new
com
.
project
.
shiro
.
util
.
AuthenticationToken
(
loginName
,
password
,
isRemeberMe
,
ip
,
""
,
""
);
}
/**
* 登录拒绝;增加Ajax异步处理
*
* @param servletRequest 请求对象
* @param servletResponse 响应对象
* @return
* @throws Exception
*/
@Override
protected
boolean
onAccessDenied
(
ServletRequest
servletRequest
,
ServletResponse
servletResponse
)
throws
Exception
{
// 判断是否为ajax异步请求
HttpServletRequest
request
=
(
HttpServletRequest
)
servletRequest
;
HttpServletResponse
response
=
(
HttpServletResponse
)
servletResponse
;
// 判断是否为登录请求
if
(
this
.
isLoginRequest
(
servletRequest
,
response
))
{
if
(
this
.
isLoginSubmission
(
servletRequest
,
response
))
{
if
(
log
.
isTraceEnabled
())
{
log
.
trace
(
"Login submission detected. Attempting to execute login."
);
}
boolean
b
=
executeLogin
(
servletRequest
,
response
);
return
b
;
}
else
{
if
(
log
.
isTraceEnabled
())
{
log
.
trace
(
"Login page view."
);
}
return
true
;
}
}
else
{
if
(
log
.
isTraceEnabled
())
{
log
.
trace
(
"Attempting to access a path which requires authentication. Forwarding to the Authentication url ["
+
this
.
getLoginUrl
()
+
"]"
);
}
// 异步请求报错
if
(
isAjaxReq
(
request
,
response
))
{
response
.
setContentType
(
"application/json"
);
response
.
setCharacterEncoding
(
"UTF-8"
);
PrintWriter
out
=
response
.
getWriter
();
JSONObject
json
=
new
JSONObject
();
json
.
put
(
"result"
,
"fail"
);
json
.
put
(
"msg"
,
"未登录"
);
out
.
println
(
json
);
out
.
flush
();
out
.
close
();
return
false
;
}
// 如果同步请求继续执行基类方法(当为同步方法的时候,基类会直接跳转登录页面)
return
super
.
onAccessDenied
(
request
,
response
);
}
}
/**
* 重写登录成功的方法;如果为异步请求,直接返回成功响应
*
* @param token
* @param subject
* @param servletRequest
* @param servletResponse
* @return
* @throws Exception
*/
@Override
protected
boolean
onLoginSuccess
(
AuthenticationToken
token
,
Subject
subject
,
ServletRequest
servletRequest
,
ServletResponse
servletResponse
)
throws
Exception
{
// 如果为异步请求,登录成功后,直接返回数据,前台跳转登录后的页面处理
if
(
isAjaxReq
(
servletRequest
,
servletResponse
))
{
HttpServletResponse
response
=
(
HttpServletResponse
)
servletResponse
;
response
.
setContentType
(
"application/json"
);
response
.
setCharacterEncoding
(
"UTF-8"
);
PrintWriter
out
=
response
.
getWriter
();
JSONObject
json
=
new
JSONObject
();
json
.
put
(
"result"
,
"success"
);
json
.
put
(
"msg"
,
"登录成功"
);
out
.
write
(
json
.
toJSONString
());
out
.
flush
();
out
.
close
();
return
true
;
}
return
super
.
onLoginSuccess
(
token
,
subject
,
servletRequest
,
servletResponse
);
}
@Override
public
boolean
isAccessAllowed
(
ServletRequest
request
,
ServletResponse
response
,
Object
mappedValue
)
{
//Always return true if the request's method is OPTIONSif (request instanceof HttpServletRequest) {
if
(((
HttpServletRequest
)
request
).
getMethod
().
toUpperCase
().
equals
(
"OPTIONS"
))
{
return
true
;
}
return
super
.
isAccessAllowed
(
request
,
response
,
mappedValue
);
}
/**
* 重写登录失败的方法;如果为异步请求,直接返回失败响应
*
* @param token
* @param e
* @param request
* @param response
* @return
*/
@Override
protected
boolean
onLoginFailure
(
AuthenticationToken
token
,
AuthenticationException
e
,
ServletRequest
request
,
ServletResponse
response
)
{
// 如果为异步登录,直接返回错误结果
if
(
isAjaxReq
(
request
,
response
))
{
PrintWriter
out
=
null
;
try
{
response
=
(
HttpServletResponse
)
response
;
response
.
setContentType
(
"application/json"
);
response
.
setCharacterEncoding
(
"UTF-8"
);
out
=
response
.
getWriter
();
JSONObject
json
=
new
JSONObject
();
if
(
e
.
equals
(
"org.apache.shiro.authc.pam.UnsupportedTokenException"
))
{
String
message
=
"验证码错误!"
;
json
.
put
(
"result"
,
"fail"
);
json
.
put
(
"msg"
,
message
);
}
else
if
(
e
.
equals
(
"org.apache.shiro.authc.UnknownAccountException"
))
{
String
message
=
"此账号不存在!"
;
json
.
put
(
"result"
,
"fail"
);
json
.
put
(
"msg"
,
message
);
}
else
if
(
e
.
equals
(
"org.apache.shiro.authc.DisabledAccountException"
))
{
String
message
=
"此账号已被禁用!"
;
json
.
put
(
"result"
,
"fail"
);
json
.
put
(
"msg"
,
message
);
}
else
if
(
e
.
equals
(
"org.apache.shiro.authc.LockedAccountException"
))
{
String
message
=
"此账号已被锁定"
;
json
.
put
(
"result"
,
"fail"
);
json
.
put
(
"msg"
,
message
);
}
else
if
(
e
.
equals
(
"org.apache.shiro.authc.IncorrectCredentialsException"
))
{
String
message
=
"密码错误"
;
json
.
put
(
"result"
,
"fail"
);
json
.
put
(
"msg"
,
message
);
}
else
if
(
e
.
equals
(
"org.apache.shiro.authc.AuthenticationException"
))
{
String
message
=
"账号认证失败!"
;
json
.
put
(
"result"
,
"fail"
);
json
.
put
(
"msg"
,
message
);
}
out
.
write
(
json
.
toJSONString
());
out
.
flush
();
out
.
close
();
return
false
;
}
catch
(
IOException
ex
)
{
ex
.
printStackTrace
();
log
.
error
(
"shiro认证失败"
);
}
}
// 同步请求走基类
return
super
.
onLoginFailure
(
token
,
e
,
request
,
response
);
}
/**
* 获取密码
*
* @param servletRequest
* @return
*/
@Override
protected
String
getPassword
(
ServletRequest
servletRequest
)
{
String
parameter
=
servletRequest
.
getParameter
(
enPasswordParam
);
HttpServletRequest
request
=
(
HttpServletRequest
)
servletRequest
;
String
enPasswor
=
request
.
getParameter
(
enPasswordParam
);
String
password
=
enPasswor
;
return
password
;
}
/**
* 判断是否为Ajax请求
*
* @param servletRequest
* @param servletResponse
* @return
*/
public
boolean
isAjaxReq
(
ServletRequest
servletRequest
,
ServletResponse
servletResponse
)
{
boolean
isAjaxReq
=
false
;
HttpServletRequest
request
=
(
HttpServletRequest
)
servletRequest
;
HttpServletResponse
response
=
(
HttpServletResponse
)
servletResponse
;
String
requestType
=
request
.
getHeader
(
"X-Requested-With"
);
if
(
requestType
!=
null
&&
requestType
.
equalsIgnoreCase
(
"XMLHttpRequest"
))
{
isAjaxReq
=
true
;
}
return
isAjaxReq
;
}
public
String
getEnPasswordParam
()
{
return
enPasswordParam
;
}
public
void
setEnPasswordParam
(
String
enPasswordParam
)
{
this
.
enPasswordParam
=
enPasswordParam
;
}
public
String
getUsernameParam
()
{
return
usernameParam
;
}
public
String
getCaptchaIdParam
()
{
return
captchaIdParam
;
}
public
void
setCaptchaIdParam
(
String
captchaIdParam
)
{
this
.
captchaIdParam
=
captchaIdParam
;
}
public
String
getCaptchaParam
()
{
return
captchaParam
;
}
public
void
setCaptchaParam
(
String
captchaParam
)
{
this
.
captchaParam
=
captchaParam
;
}
}
//
package com.project.shiro.util;
//
//
import com.alibaba.fastjson.JSONObject;
//
import org.apache.shiro.authc.AuthenticationException;
//
import org.apache.shiro.authc.AuthenticationToken;
//
import org.apache.shiro.subject.Subject;
//
import org.apache.shiro.util.StringUtils;
//
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
//
import org.apache.shiro.web.util.WebUtils;
//
import org.slf4j.Logger;
//
import org.slf4j.LoggerFactory;
//
//
import javax.servlet.ServletRequest;
//
import javax.servlet.ServletResponse;
//
import javax.servlet.http.HttpServletRequest;
//
import javax.servlet.http.HttpServletResponse;
//
import java.io.IOException;
//
import java.io.PrintWriter;
//
/
//
**
//
* 自定义表单认证过滤器
//
*
//
* @author wyy
//
* @date 2019/07/26
//
*/
//
public class AuthenticationFilter extends FormAuthenticationFilter {
//
private static final Logger log = LoggerFactory.getLogger(AuthenticationFilter.class);
//
//
//加密密码参数
//
private static final String DEFAULT_EN_PASSWORD_PARAM = "enPassword";
//
//
//默认的登录名称
//
private static final String DEFAULT_USERNAME_PARAM = "loginName";
//
//
//默认验证码ID参数
//
private static final String DEFAULT_CAPTCHA_ID_PARAM = "captchaId";
//
//
//默认验证码参数
//
private static final String DEFAULT_CAPTCHA_PARAM = "captcha";
//
//
private String captchaIdParam = DEFAULT_CAPTCHA_ID_PARAM;
//
//
private String captchaParam = DEFAULT_CAPTCHA_PARAM;
//
//
private String usernameParam = DEFAULT_USERNAME_PARAM;
//
//
private String enPasswordParam = DEFAULT_EN_PASSWORD_PARAM;
//
//
/**
//
* 创建token
//
*/
//
@Override
//
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
//
String loginName = getUsername(request);
//
String password = getPassword(request);
//
boolean isRemeberMe = isRememberMe(request);
//
String ip = getHost(request);
//
return new com.project.shiro.util.AuthenticationToken(loginName, password, isRemeberMe, ip, "", "");
//
}
//
//
/**
//
* 登录拒绝;增加Ajax异步处理
//
*
//
* @param servletRequest 请求对象
//
* @param servletResponse 响应对象
//
* @return
//
* @throws Exception
//
*/
//
@Override
//
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
//
// 判断是否为ajax异步请求
//
HttpServletRequest request = (HttpServletRequest) servletRequest;
//
HttpServletResponse response = (HttpServletResponse) servletResponse;
//
//
// 判断是否为登录请求
//
if (this.isLoginRequest(servletRequest, response)) {
//
if (this.isLoginSubmission(servletRequest, response)) {
//
//
if (log.isTraceEnabled()) {
//
log.trace("Login submission detected. Attempting to execute login.");
//
}
//
boolean b = executeLogin(servletRequest, response);
//
return b;
//
} else {
//
if (log.isTraceEnabled()) {
//
log.trace("Login page view.");
//
}
//
return true;
//
}
//
} else {
//
if (log.isTraceEnabled()) {
//
log.trace("Attempting to access a path which requires authentication. Forwarding to the Authentication url [" + this.getLoginUrl() + "]");
//
}
//
//
// 异步请求报错
//
if (isAjaxReq(request, response)) {
//
response.setContentType("application/json");
//
response.setCharacterEncoding("UTF-8");
//
PrintWriter out = response.getWriter();
//
JSONObject json = new JSONObject();
//
json.put("result", "fail");
//
json.put("msg", "未登录");
//
out.println(json);
//
out.flush();
//
out.close();
//
return false;
//
}
//
//
//
如果同步请求继续执行基类方法(当为同步方法的时候,基类会直接跳转登录页面)
//
return super.onAccessDenied(request, response);
//
}
//
//
}
//
//
/**
//
* 重写登录成功的方法;如果为异步请求,直接返回成功响应
//
*
//
* @param token
//
* @param subject
//
* @param servletRequest
//
* @param servletResponse
//
* @return
//
* @throws Exception
//
*/
//
@Override
//
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
//
// 如果为异步请求,登录成功后,直接返回数据,前台跳转登录后的页面处理
//
if (isAjaxReq(servletRequest, servletResponse)) {
//
HttpServletResponse response = (HttpServletResponse) servletResponse;
//
response.setContentType("application/json");
//
response.setCharacterEncoding("UTF-8");
//
PrintWriter out = response.getWriter();
//
JSONObject json = new JSONObject();
//
json.put("result", "success");
//
json.put("msg", "登录成功");
//
out.write(json.toJSONString());
//
out.flush();
//
out.close();
//
return true;
//
}
//
return super.onLoginSuccess(token, subject, servletRequest, servletResponse);
//
}
//
//
@Override
//
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
//
//Always return true if the request's method is OPTIONSif (request instanceof HttpServletRequest) {
//
if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
//
return true;
//
}
//
return super.isAccessAllowed(request, response, mappedValue);
//
}
//
//
/**
//
* 重写登录失败的方法;如果为异步请求,直接返回失败响应
//
*
//
* @param token
//
* @param e
//
* @param request
//
* @param response
//
* @return
//
*/
//
@Override
//
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
//
// 如果为异步登录,直接返回错误结果
//
if (isAjaxReq(request, response)) {
//
PrintWriter out = null;
//
try {
//
response = (HttpServletResponse) response;
//
response.setContentType("application/json");
//
response.setCharacterEncoding("UTF-8");
//
out = response.getWriter();
//
JSONObject json = new JSONObject();
//
if (e.equals("org.apache.shiro.authc.pam.UnsupportedTokenException")) {
//
String message = "验证码错误!";
//
json.put("result", "fail");
//
json.put("msg", message);
//
} else if (e.equals("org.apache.shiro.authc.UnknownAccountException")) {
//
String message = "此账号不存在!";
//
json.put("result", "fail");
//
json.put("msg", message);
//
} else if (e.equals("org.apache.shiro.authc.DisabledAccountException")) {
//
String message = "此账号已被禁用!";
//
json.put("result", "fail");
//
json.put("msg", message);
//
} else if (e.equals("org.apache.shiro.authc.LockedAccountException")) {
//
String message = "此账号已被锁定";
//
json.put("result", "fail");
//
json.put("msg", message);
//
} else if (e.equals("org.apache.shiro.authc.IncorrectCredentialsException")) {
//
String message = "密码错误";
//
json.put("result", "fail");
//
json.put("msg", message);
//
} else if (e.equals("org.apache.shiro.authc.AuthenticationException")) {
//
String message = "账号认证失败!";
//
json.put("result", "fail");
//
json.put("msg", message);
//
}
//
out.write(json.toJSONString());
//
out.flush();
//
out.close();
//
return false;
//
} catch (IOException ex) {
//
ex.printStackTrace();
//
log.error("shiro认证失败");
//
}
//
//
}
//
//
// 同步请求走基类
//
return super.onLoginFailure(token, e, request, response);
//
}
//
//
//
/**
//
* 获取密码
//
*
//
* @param servletRequest
//
* @return
//
*/
//
@Override
//
protected String getPassword(ServletRequest servletRequest) {
//
String parameter = servletRequest.getParameter(enPasswordParam);
//
HttpServletRequest request = (HttpServletRequest) servletRequest;
//
String enPasswor = request.getParameter(enPasswordParam);
//
String password = enPasswor;
//
return password;
//
}
//
//
/**
//
* 判断是否为Ajax请求
//
*
//
* @param servletRequest
//
* @param servletResponse
//
* @return
//
*/
//
public boolean isAjaxReq(ServletRequest servletRequest, ServletResponse servletResponse) {
//
boolean isAjaxReq = false;
//
HttpServletRequest request = (HttpServletRequest) servletRequest;
//
HttpServletResponse response = (HttpServletResponse) servletResponse;
//
String requestType = request.getHeader("X-Requested-With");
//
if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
//
isAjaxReq = true;
//
}
//
return isAjaxReq;
//
}
//
//
public String getEnPasswordParam() {
//
return enPasswordParam;
//
}
//
//
public void setEnPasswordParam(String enPasswordParam) {
//
this.enPasswordParam = enPasswordParam;
//
}
//
//
public String getUsernameParam() {
//
return usernameParam;
//
}
//
//
public String getCaptchaIdParam() {
//
return captchaIdParam;
//
}
//
//
public void setCaptchaIdParam(String captchaIdParam) {
//
this.captchaIdParam = captchaIdParam;
//
}
//
//
public String getCaptchaParam() {
//
return captchaParam;
//
}
//
//
public void setCaptchaParam(String captchaParam) {
//
this.captchaParam = captchaParam;
//
}
//
//
}
wisenergy-shiro/src/main/java/com/project/shiro/util/AuthenticationRealm.java
View file @
34ad5d18
package
com
.
project
.
shiro
.
util
;
import
com.alibaba.fastjson.JSONObject
;
import
com.project.model.core.Admin
;
import
com.project.model.core.Menu
;
import
com.project.model.core.Role
;
import
com.project.service.core.AdminService
;
import
com.project.service.core.MenuService
;
import
org.apache.commons.codec.digest.DigestUtils
;
import
org.apache.commons.collections.CollectionUtils
;
import
org.apache.commons.lang.time.DateUtils
;
import
org.apache.commons.lang3.StringUtils
;
import
org.apache.shiro.authc.*
;
import
org.apache.shiro.authz.AuthorizationInfo
;
import
org.apache.shiro.authz.Permission
;
import
org.apache.shiro.authz.SimpleAuthorizationInfo
;
import
org.apache.shiro.realm.AuthorizingRealm
;
import
org.apache.shiro.subject.PrincipalCollection
;
import
javax.annotation.Resource
;
import
java.io.PrintWriter
;
import
java.util.*
;
/**
* 认证
*/
public
class
AuthenticationRealm
extends
AuthorizingRealm
{
@Resource
(
name
=
"adminServiceImpl"
)
private
AdminService
adminService
;
@Resource
(
name
=
"menuServiceImpl"
)
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
;
}
/**
* 超级管理员自动获取所有权限
*/
//package com.project.shiro.util;
//
//import com.alibaba.fastjson.JSONObject;
//import com.project.model.core.Admin;
//import com.project.model.core.Menu;
//import com.project.model.core.Role;
//import com.project.service.core.AdminService;
//import com.project.service.core.MenuService;
//import org.apache.commons.codec.digest.DigestUtils;
//import org.apache.commons.collections.CollectionUtils;
//import org.apache.commons.lang.time.DateUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.apache.shiro.authc.*;
//import org.apache.shiro.authz.AuthorizationInfo;
//import org.apache.shiro.authz.Permission;
//import org.apache.shiro.authz.SimpleAuthorizationInfo;
//import org.apache.shiro.realm.AuthorizingRealm;
//import org.apache.shiro.subject.PrincipalCollection;
//
//import javax.annotation.Resource;
//import java.io.PrintWriter;
//import java.util.*;
//
///**
// * 认证
// */
//public class AuthenticationRealm extends AuthorizingRealm {
//
// @Resource(name = "adminServiceImpl")
// private AdminService adminService;
//
// @Resource(name = "menuServiceImpl")
// private MenuService menuService;
//
// /**
// * 获取认证信息
// */
// @Override
// public boolean isPermitted(PrincipalCollection principals, String permission) {
//// User user = ((User) principals.getPrimaryPrincipal());
//// if (Role.ADMIN_FLAG_SUPER_ADMIN == user.getRole().getAdminFlag()) {
//// return true;
// 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
//// 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;
//// }
//// }
//// }
//
//
// 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;
// }
// }
// }
}
//}
wisenergy-shiro/src/main/java/com/project/shiro/util/AuthenticationToken.java
View file @
34ad5d18
package
com
.
project
.
shiro
.
util
;
import
org.apache.shiro.authc.UsernamePasswordToken
;
/**
* 登录令牌
*/
public
class
AuthenticationToken
extends
UsernamePasswordToken
{
private
static
final
long
serialVersionUID
=
4628652632307774263L
;
//验证码ID
private
String
captchaId
;
//验证码
private
String
captcha
;
//ip保留
public
AuthenticationToken
(
String
loginName
,
String
password
,
boolean
remeberMe
,
String
ip
,
String
captchaId
,
String
caprcha
)
{
super
(
loginName
,
password
,
remeberMe
);
this
.
captchaId
=
captchaId
;
this
.
captcha
=
caprcha
;
}
public
String
getCaptchaId
()
{
return
captchaId
;
}
public
void
setCaptchaId
(
String
captchaId
)
{
this
.
captchaId
=
captchaId
;
}
public
String
getCaptcha
()
{
return
captcha
;
}
public
void
setCaptcha
(
String
captcha
)
{
this
.
captcha
=
captcha
;
}
}
//
package com.project.shiro.util;
//
//
import org.apache.shiro.authc.UsernamePasswordToken;
//
/
//
**
//
* 登录令牌
//
*/
//
public class AuthenticationToken extends UsernamePasswordToken {
//
//
private static final long serialVersionUID = 4628652632307774263L;
//
//
//验证码ID
//
private String captchaId;
//
//
//验证码
//
private String captcha;
//
//
//ip保留
//
public AuthenticationToken(String loginName, String password, boolean remeberMe, String ip, String captchaId, String caprcha) {
//
super(loginName, password, remeberMe);
//
this.captchaId = captchaId;
//
this.captcha = caprcha;
//
}
//
//
public String getCaptchaId() {
//
return captchaId;
//
}
//
//
public void setCaptchaId(String captchaId) {
//
this.captchaId = captchaId;
//
}
//
//
public String getCaptcha() {
//
return captcha;
//
}
//
//
public void setCaptcha(String captcha) {
//
this.captcha = captcha;
//
}
//
//
}
wisenergy-shiro/src/main/java/com/project/shiro/util/AuthorizationFilter.java
View file @
34ad5d18
package
com
.
project
.
shiro
.
util
;
import
com.alibaba.fastjson.JSONObject
;
import
io.swagger.annotations.ResponseHeader
;
import
org.apache.commons.lang3.StringUtils
;
import
org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter
;
import
javax.servlet.ServletRequest
;
import
javax.servlet.ServletResponse
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
java.io.IOException
;
import
java.io.PrintWriter
;
/**
* @author wyy
* @date 2019-09-14 17:57
*/
public
class
AuthorizationFilter
extends
PermissionsAuthorizationFilter
{
/**
* shiro认证perms资源失败后回调方法
* @param servletRequest
* @param servletResponse
* @return
* @throws IOException
*/
@Override
protected
boolean
onAccessDenied
(
ServletRequest
servletRequest
,
ServletResponse
servletResponse
)
throws
IOException
{
HttpServletRequest
httpServletRequest
=
(
HttpServletRequest
)
servletRequest
;
HttpServletResponse
httpServletResponse
=
(
HttpServletResponse
)
servletResponse
;
String
requestedWith
=
httpServletRequest
.
getHeader
(
"X-Requested-With"
);
if
(
StringUtils
.
isNotEmpty
(
requestedWith
)
&&
StringUtils
.
equals
(
requestedWith
,
"XMLHttpRequest"
))
{
//如果是ajax返回指定格式数据
httpServletResponse
.
setContentType
(
"application/json"
);
httpServletResponse
.
setCharacterEncoding
(
"UTF-8"
);
PrintWriter
out
=
httpServletResponse
.
getWriter
();
JSONObject
json
=
new
JSONObject
();
json
.
put
(
"result"
,
"success"
);
json
.
put
(
"msg"
,
"登录成功"
);
out
.
write
(
json
.
toJSONString
());
out
.
flush
();
out
.
close
();
}
else
{
//如果是普通请求进行重定向
httpServletResponse
.
sendRedirect
(
"/403"
);
}
return
false
;
}
}
//
package com.project.shiro.util;
//
//
import com.alibaba.fastjson.JSONObject;
//
import io.swagger.annotations.ResponseHeader;
//
import org.apache.commons.lang3.StringUtils;
//
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
//
//
import javax.servlet.ServletRequest;
//
import javax.servlet.ServletResponse;
//
import javax.servlet.http.HttpServletRequest;
//
import javax.servlet.http.HttpServletResponse;
//
import java.io.IOException;
//
import java.io.PrintWriter;
//
/
//
**
//
* @author wyy
//
* @date 2019-09-14 17:57
//
*/
//
public class AuthorizationFilter extends PermissionsAuthorizationFilter {
//
/**
//
* shiro认证perms资源失败后回调方法
//
* @param servletRequest
//
* @param servletResponse
//
* @return
//
* @throws IOException
//
*/
//
@Override
//
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
//
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
//
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
//
String requestedWith = httpServletRequest.getHeader("X-Requested-With");
//
if (StringUtils.isNotEmpty(requestedWith) && StringUtils.equals(requestedWith, "XMLHttpRequest")) {//如果是ajax返回指定格式数据
//
httpServletResponse.setContentType("application/json");
//
httpServletResponse.setCharacterEncoding("UTF-8");
//
PrintWriter out = httpServletResponse.getWriter();
//
JSONObject json = new JSONObject();
//
json.put("result", "success");
//
json.put("msg", "登录成功");
//
out.write(json.toJSONString());
//
out.flush();
//
out.close();
//
} else {//如果是普通请求进行重定向
//
httpServletResponse.sendRedirect("/403");
//
}
//
return false;
//
}
//
}
wisenergy-shiro/src/main/java/com/project/shiro/util/Principal.java
View file @
34ad5d18
package
com
.
project
.
shiro
.
util
;
import
java.io.Serializable
;
public
class
Principal
implements
Serializable
{
private
static
final
long
serialVersionUID
=
598764316789461315L
;
public
Long
id
;
public
String
loginName
;
public
Principal
(
Long
id
,
String
loginName
)
{
this
.
id
=
id
;
this
.
loginName
=
loginName
;
}
public
Principal
()
{
}
public
Long
getId
()
{
return
id
;
}
public
void
setId
(
Long
id
)
{
this
.
id
=
id
;
}
public
String
getLoginName
()
{
return
loginName
;
}
public
void
setLoginName
(
String
loginName
)
{
this
.
loginName
=
loginName
;
}
}
//
package com.project.shiro.util;
//
//
import java.io.Serializable;
//
//
public class Principal implements Serializable {
//
//
private static final long serialVersionUID = 598764316789461315L;
//
//
public Long id;
//
//
public String loginName;
//
//
public Principal(Long id, String loginName) {
//
this.id = id;
//
this.loginName = loginName;
//
}
//
//
public Principal() {
//
//
}
//
//
public Long getId() {
//
return id;
//
}
//
//
public void setId(Long id) {
//
this.id = id;
//
}
//
//
public String getLoginName() {
//
return loginName;
//
}
//
//
public void setLoginName(String loginName) {
//
this.loginName = loginName;
//
}
//
//
}
wisenergy-shiro/src/main/java/com/project/shiro/util/redis/ShiroRedisCache.java
View file @
34ad5d18
package
com
.
project
.
shiro
.
util
.
redis
;
import
cn.wisenergy.service.common.utils.ByteUtil
;
import
cn.wisenergy.service.common.utils.redis.RedisClient
;
import
cn.wisenergy.service.common.utils.redis.RedisConsts
;
import
org.apache.shiro.cache.Cache
;
import
org.apache.shiro.cache.CacheException
;
import
org.apache.shiro.util.CollectionUtils
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
javax.annotation.Resource
;
import
java.io.IOException
;
import
java.util.*
;
public
class
ShiroRedisCache
<
K
,
V
>
implements
Cache
<
K
,
V
>
{
//初始化Log日志
private
Logger
logger
=
LoggerFactory
.
getLogger
(
this
.
getClass
());
//注入redisClient实例
@Resource
(
name
=
"redisClient"
)
private
RedisClient
redisClient
;
//shiroSession的key值前缀
private
String
keyPrefix
;
//通过redisClient实例和prefix参数构造redisCache
public
ShiroRedisCache
(
RedisClient
redisClient
,
String
prefix
)
{
if
(
redisClient
==
null
)
{
throw
new
IllegalArgumentException
(
"shiroRedisCahe初始化时,redisClient参数不能为空"
);
}
this
.
redisClient
=
redisClient
;
this
.
keyPrefix
=
prefix
;
}
/**
* 获得String类型的KEY
*
* @param key
* @return
*/
private
String
getPreStringKey
(
K
key
)
{
String
preKey
=
null
;
if
(
key
instanceof
String
)
{
preKey
=
this
.
keyPrefix
+
key
;
return
preKey
;
}
else
{
try
{
preKey
=
keyPrefix
+
ByteUtil
.
bytesToHexString
(
ByteUtil
.
objectToBytes
(
key
));
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
return
preKey
;
}
}
@Override
public
V
get
(
K
key
)
throws
CacheException
{
logger
.
debug
(
"根据key从Redis中获取对象 key ["
+
key
+
"]"
);
try
{
if
(
key
==
null
)
{
return
null
;
}
else
{
V
Vvalue
=
(
V
)
redisClient
.
get
(
getPreStringKey
(
key
));
if
(
Vvalue
==
null
)
{
return
null
;
}
return
Vvalue
;
}
}
catch
(
Throwable
t
)
{
throw
new
CacheException
(
t
);
}
}
@Override
public
V
put
(
K
key
,
V
value
)
throws
CacheException
{
logger
.
debug
(
"根据key从存储 key ["
+
key
+
"]"
);
try
{
redisClient
.
set
(
getPreStringKey
(
key
),
value
);
redisClient
.
setAndExpire
(
getPreStringKey
(
key
),
value
,
RedisConsts
.
ADMIN_SHIRO_REALM_EXPIRE
);
return
value
;
}
catch
(
Throwable
t
)
{
throw
new
CacheException
(
t
);
}
}
@Override
public
V
remove
(
K
key
)
throws
CacheException
{
logger
.
debug
(
"从redis中删除 key ["
+
key
+
"]"
);
try
{
V
previous
=
get
(
key
);
redisClient
.
del
(
getPreStringKey
(
key
));
return
previous
;
}
catch
(
Throwable
t
)
{
throw
new
CacheException
(
t
);
}
}
@Override
public
void
clear
()
throws
CacheException
{
logger
.
debug
(
"从redis中删除所有元素"
);
try
{
// redisClient.flushDB();
}
catch
(
Throwable
t
)
{
throw
new
CacheException
(
t
);
}
}
@Override
public
int
size
()
{
//package com.project.shiro.util.redis;
//
//import cn.wisenergy.service.common.utils.ByteUtil;
//import cn.wisenergy.service.common.utils.redis.RedisClient;
//import cn.wisenergy.service.common.utils.redis.RedisConsts;
//import org.apache.shiro.cache.Cache;
//import org.apache.shiro.cache.CacheException;
//import org.apache.shiro.util.CollectionUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import javax.annotation.Resource;
//import java.io.IOException;
//import java.util.*;
//
//public class ShiroRedisCache<K, V> implements Cache<K, V> {
//
// //初始化Log日志
// private Logger logger = LoggerFactory.getLogger(this.getClass());
//
// //注入redisClient实例
// @Resource(name = "redisClient")
// private RedisClient redisClient;
//
// //shiroSession的key值前缀
// private String keyPrefix;
//
// //通过redisClient实例和prefix参数构造redisCache
// public ShiroRedisCache(RedisClient redisClient, String prefix) {
// if (redisClient == null) {
// throw new IllegalArgumentException("shiroRedisCahe初始化时,redisClient参数不能为空");
// }
// this.redisClient = redisClient;
// this.keyPrefix = prefix;
// }
//
// /**
// * 获得String类型的KEY
// *
// * @param key
// * @return
// */
// private String getPreStringKey(K key) {
// String preKey = null;
// if (key instanceof String) {
// preKey = this.keyPrefix + key;
// return preKey;
// } else {
// try {
// preKey = keyPrefix + ByteUtil.bytesToHexString(ByteUtil.objectToBytes(key));
// } catch (IOException e) {
// e.printStackTrace();
// }
// return preKey;
// }
// }
//
// @Override
// public V get(K key) throws CacheException {
// logger.debug("根据key从Redis中获取对象 key [" + key + "]");
// try {
// if (key == null) {
// return null;
// } else {
// V Vvalue = (V) redisClient.get(getPreStringKey(key));
// if (Vvalue == null) {
// return null;
// }
// return Vvalue;
// }
// } catch (Throwable t) {
// throw new CacheException(t);
// }
//
// }
//
// @Override
// public V put(K key, V value) throws CacheException {
// logger.debug("根据key从存储 key [" + key + "]");
// try {
// redisClient.set(getPreStringKey(key), value);
// redisClient.setAndExpire(getPreStringKey(key), value, RedisConsts.ADMIN_SHIRO_REALM_EXPIRE);
// return value;
// } catch (Throwable t) {
// throw new CacheException(t);
// }
// }
//
// @Override
// public V remove(K key) throws CacheException {
// logger.debug("从redis中删除 key [" + key + "]");
// try {
// V previous = get(key);
// redisClient.del(getPreStringKey(key));
// return previous;
// } catch (Throwable t) {
// throw new CacheException(t);
// }
// }
//
// @Override
// public void clear() throws CacheException {
// logger.debug("从redis中删除所有元素");
// try {
//// redisClient.flushDB();
// } catch (Throwable t) {
// throw new CacheException(t);
// }
// }
//
// @Override
// public int size() {
//// try {
//// Long longSize = new Long(redisClient.dbSize());
//// 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 {
// Long longSize = new Long(redisClient.dbSize());
// return longSize.intValue();
// 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);
// }
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
)
{
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
;
}
}
// }
//
// 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;
// }
//}
wisenergy-shiro/src/main/java/com/project/shiro/util/redis/ShiroRedisCacheManager.java
View file @
34ad5d18
package
com
.
project
.
shiro
.
util
.
redis
;
import
cn.wisenergy.service.common.utils.redis.RedisClient
;
import
cn.wisenergy.service.common.utils.redis.RedisConsts
;
import
org.apache.shiro.cache.Cache
;
import
org.apache.shiro.cache.CacheException
;
import
org.apache.shiro.cache.CacheManager
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
javax.annotation.Resource
;
import
java.util.concurrent.ConcurrentHashMap
;
import
java.util.concurrent.ConcurrentMap
;
public
class
ShiroRedisCacheManager
implements
CacheManager
{
private
static
final
Logger
logger
=
LoggerFactory
.
getLogger
(
ShiroRedisCacheManager
.
class
);
private
final
ConcurrentMap
<
String
,
Cache
>
caches
=
new
ConcurrentHashMap
<
String
,
Cache
>();
//注入redisClient实例
@Resource
(
name
=
"redisClient"
)
private
RedisClient
redisClient
;
/**
* shiro权限缓存前缀
*/
private
String
keyPrefix
=
RedisConsts
.
ADMIN_SHIRO_REALM_KEY
;
@Override
public
<
K
,
V
>
Cache
<
K
,
V
>
getCache
(
String
name
)
throws
CacheException
{
logger
.
debug
(
"获取名称为: "
+
name
+
" 的RedisCache实例"
);
Cache
c
=
caches
.
get
(
keyPrefix
+
name
);
if
(
c
==
null
)
{
c
=
new
ShiroRedisCache
<
K
,
V
>(
redisClient
,
keyPrefix
);
caches
.
put
(
keyPrefix
+
name
,
c
);
}
return
c
;
}
public
RedisClient
getRedisClient
()
{
return
redisClient
;
}
public
void
setRedisClient
(
RedisClient
redisClient
)
{
this
.
redisClient
=
redisClient
;
}
public
String
getKeyPrefix
()
{
return
keyPrefix
;
}
public
void
setKeyPrefix
(
String
keyPrefix
)
{
this
.
keyPrefix
=
keyPrefix
;
}
}
//
package com.project.shiro.util.redis;
//
//
//
import cn.wisenergy.service.common.utils.redis.RedisClient;
//
import cn.wisenergy.service.common.utils.redis.RedisConsts;
//
import org.apache.shiro.cache.Cache;
//
import org.apache.shiro.cache.CacheException;
//
import org.apache.shiro.cache.CacheManager;
//
import org.slf4j.Logger;
//
import org.slf4j.LoggerFactory;
//
//
import javax.annotation.Resource;
//
import java.util.concurrent.ConcurrentHashMap;
//
import java.util.concurrent.ConcurrentMap;
//
//
public class ShiroRedisCacheManager implements CacheManager {
//
//
private static final Logger logger = LoggerFactory.getLogger(ShiroRedisCacheManager.class);
//
//
private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>();
//
//
//注入redisClient实例
//
@Resource(name = "redisClient")
//
private RedisClient redisClient;
//
//
/**
//
* shiro权限缓存前缀
//
*/
//
private String keyPrefix = RedisConsts.ADMIN_SHIRO_REALM_KEY;
//
//
//
@Override
//
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
//
//
logger.debug("获取名称为: " + name + " 的RedisCache实例");
//
Cache c = caches.get(keyPrefix + name);
//
if (c == null) {
//
c = new ShiroRedisCache<K, V>(redisClient, keyPrefix);
//
caches.put(keyPrefix + name, c);
//
}
//
return c;
//
}
//
//
public RedisClient getRedisClient() {
//
return redisClient;
//
}
//
//
public void setRedisClient(RedisClient redisClient) {
//
this.redisClient = redisClient;
//
}
//
//
public String getKeyPrefix() {
//
return keyPrefix;
//
}
//
//
public void setKeyPrefix(String keyPrefix) {
//
this.keyPrefix = keyPrefix;
//
}
//
}
wisenergy-shiro/src/main/java/com/project/shiro/util/redis/ShiroRedisSessionDAO.java
View file @
34ad5d18
package
com
.
project
.
shiro
.
util
.
redis
;
import
cn.wisenergy.service.common.utils.ByteUtil
;
import
cn.wisenergy.service.common.utils.redis.RedisClient
;
import
cn.wisenergy.service.common.utils.redis.RedisConsts
;
import
org.apache.shiro.session.Session
;
import
org.apache.shiro.session.UnknownSessionException
;
import
org.apache.shiro.session.mgt.eis.AbstractSessionDAO
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
javax.annotation.Resource
;
import
java.io.IOException
;
import
java.io.Serializable
;
import
java.util.Collection
;
import
java.util.HashSet
;
import
java.util.Set
;
public
class
ShiroRedisSessionDAO
extends
AbstractSessionDAO
{
private
static
Logger
logger
=
LoggerFactory
.
getLogger
(
ShiroRedisSessionDAO
.
class
);
//注入redisClient实例
@Resource
(
name
=
"redisClient"
)
private
RedisClient
redisClient
;
/**
* shiro-redis的session对象前缀
*/
private
String
keyPrefix
=
RedisConsts
.
ADMIN_SHIRO_SESSION_KEY
;
@Override
public
void
update
(
Session
session
)
throws
UnknownSessionException
{
this
.
saveSession
(
session
);
}
private
void
saveSession
(
Session
session
)
throws
UnknownSessionException
{
if
(
session
==
null
||
session
.
getId
()
==
null
)
{
logger
.
error
(
"session or session id is null"
);
return
;
}
this
.
redisClient
.
setAndExpire
(
this
.
getPreStringKey
(
session
.
getId
()),
session
,
RedisConsts
.
ADMIN_SHIRO_SESSION_EXPIRE
);
}
@Override
public
void
delete
(
Session
session
)
{
if
(
session
==
null
||
session
.
getId
()
==
null
)
{
logger
.
error
(
"session or session id is null"
);
return
;
}
redisClient
.
del
(
getPreStringKey
(
session
.
getId
()));
}
@Override
public
Collection
<
Session
>
getActiveSessions
()
{
Set
<
Session
>
sessions
=
new
HashSet
<
Session
>();
Set
<
byte
[]>
keys
=
null
;
try
{
keys
=
redisClient
.
keys
(
ByteUtil
.
objectToBytes
(
this
.
keyPrefix
+
"*"
));
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
if
(
keys
!=
null
&&
keys
.
size
()
>
0
)
{
for
(
byte
[]
key
:
keys
)
{
Session
s
=
null
;
try
{
s
=
(
Session
)
ByteUtil
.
bytesToObject
(
redisClient
.
get
(
key
));
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
catch
(
ClassNotFoundException
e
)
{
e
.
printStackTrace
();
}
sessions
.
add
(
s
);
}
}
return
sessions
;
}
@Override
protected
Serializable
doCreate
(
Session
session
)
{
Serializable
sessionId
=
this
.
generateSessionId
(
session
);
this
.
assignSessionId
(
session
,
sessionId
);
this
.
saveSession
(
session
);
return
sessionId
;
}
@Override
protected
Session
doReadSession
(
Serializable
sessionId
)
{
if
(
sessionId
==
null
)
{
logger
.
error
(
"session id is null"
);
return
null
;
}
Session
s
=
(
Session
)
redisClient
.
get
(
this
.
getPreStringKey
(
sessionId
));
return
s
;
}
/**
* 获得String类型的key
*
* @param
* @return
*/
private
String
getPreStringKey
(
Serializable
sessionId
)
{
String
preKey
=
this
.
keyPrefix
+
sessionId
;
return
preKey
;
}
public
String
getKeyPrefix
()
{
return
keyPrefix
;
}
public
void
setKeyPrefix
(
String
keyPrefix
)
{
this
.
keyPrefix
=
keyPrefix
;
}
public
void
setRedisClient
(
RedisClient
redisClient
)
{
this
.
redisClient
=
redisClient
;
}
public
RedisClient
getRedisClient
()
{
return
redisClient
;
}
}
//
package com.project.shiro.util.redis;
//
//
import cn.wisenergy.service.common.utils.ByteUtil;
//
import cn.wisenergy.service.common.utils.redis.RedisClient;
//
import cn.wisenergy.service.common.utils.redis.RedisConsts;
//
import org.apache.shiro.session.Session;
//
import org.apache.shiro.session.UnknownSessionException;
//
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
//
import org.slf4j.Logger;
//
import org.slf4j.LoggerFactory;
//
//
import javax.annotation.Resource;
//
import java.io.IOException;
//
import java.io.Serializable;
//
import java.util.Collection;
//
import java.util.HashSet;
//
import java.util.Set;
//
//
public class ShiroRedisSessionDAO extends AbstractSessionDAO {
//
//
private static Logger logger = LoggerFactory.getLogger(ShiroRedisSessionDAO.class);
//
//
//注入redisClient实例
//
@Resource(name = "redisClient")
//
private RedisClient redisClient;
//
//
/**
//
* shiro-redis的session对象前缀
//
*/
//
//
private String keyPrefix = RedisConsts.ADMIN_SHIRO_SESSION_KEY;
//
//
@Override
//
public void update(Session session) throws UnknownSessionException {
//
this.saveSession(session);
//
}
//
//
private void saveSession(Session session) throws UnknownSessionException {
//
if (session == null || session.getId() == null) {
//
logger.error("session or session id is null");
//
return;
//
}
//
this.redisClient.setAndExpire(this.getPreStringKey(session.getId()), session, RedisConsts.ADMIN_SHIRO_SESSION_EXPIRE);
//
}
//
//
@Override
//
public void delete(Session session) {
//
if (session == null || session.getId() == null) {
//
logger.error("session or session id is null");
//
return;
//
}
//
redisClient.del(getPreStringKey(session.getId()));
//
//
}
//
//
@Override
//
public Collection<Session> getActiveSessions() {
//
Set<Session> sessions = new HashSet<Session>();
//
//
Set<byte[]> keys = null;
//
try {
//
keys = redisClient.keys(ByteUtil.objectToBytes(this.keyPrefix + "*"));
//
} catch (IOException e) {
//
e.printStackTrace();
//
}
//
if (keys != null && keys.size() > 0) {
//
for (byte[] key : keys) {
//
Session s = null;
//
try {
//
s = (Session) ByteUtil.bytesToObject(redisClient.get(key));
//
} catch (IOException e) {
//
e.printStackTrace();
//
} catch (ClassNotFoundException e) {
//
e.printStackTrace();
//
}
//
sessions.add(s);
//
}
//
}
//
//
return sessions;
//
}
//
//
@Override
//
protected Serializable doCreate(Session session) {
//
Serializable sessionId = this.generateSessionId(session);
//
this.assignSessionId(session, sessionId);
//
this.saveSession(session);
//
return sessionId;
//
}
//
//
@Override
//
protected Session doReadSession(Serializable sessionId) {
//
if (sessionId == null) {
//
logger.error("session id is null");
//
return null;
//
}
//
//
Session s = (Session) redisClient.get(this.getPreStringKey(sessionId));
//
return s;
//
}
//
//
/**
//
* 获得String类型的key
//
*
//
* @param
//
* @return
//
*/
//
private String getPreStringKey(Serializable sessionId) {
//
String preKey = this.keyPrefix + sessionId;
//
return preKey;
//
}
//
//
public String getKeyPrefix() {
//
return keyPrefix;
//
}
//
//
public void setKeyPrefix(String keyPrefix) {
//
this.keyPrefix = keyPrefix;
//
}
//
//
public void setRedisClient(RedisClient redisClient) {
//
this.redisClient = redisClient;
//
}
//
//
public RedisClient getRedisClient() {
//
return redisClient;
//
}
//
//
}
wisenergy-web-admin/src/main/java/cn/wisenergy/web/sms/interceptor/LoginInterceptor.java
View file @
34ad5d18
package
cn
.
wisenergy
.
web
.
sms
.
interceptor
;
import
cn.wisenergy.common.enums.ResultEnum
;
import
cn.wisenergy.common.utils.Constants
;
import
cn.wisenergy.common.utils.RedisUtils
;
import
cn.wisenergy.common.utils.ResponseOutput
;
import
cn.wisenergy.common.utils.StringUtil
;
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment