本篇文章主要SpringMVC讲整合shiro
Maven依赖:
Pom.xml
<properties>
<!--SpringMvc 相关配置省去 -->
<!-- 1.3.2可以去掉 JSESSIONID 1.2.2(原始版本) -->
<shiro-version>1.3.2</shiro-version>
</properties>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro-version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${shiro-version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro-version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${shiro-version}</version>
</dependency>
配置shiro过滤器
web.xml配置信息:
<filter>
<!-- 注意: 过滤器名称是固定的-->
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
spring与shiro的配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd"
>
<!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的ShiroDbRealm.java -->
<bean id="myRealm" class="com.xx.realm.MyRealm" />
<bean id="sessionManager"
class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<!-- session的失效时长,单位毫秒 -->
<property name="globalSessionTimeout" value="600000" />
<!-- 删除失效的session -->
<property name="deleteInvalidSessions" value="true" />
<!-- 去掉 JSESSIONID 1.3.2可以去掉-->
<property name="sessionIdUrlRewritingEnabled" value="false"></property>
</bean>
<!-- Shiro默认会使用Servlet容器的Session,可通过sessionMode属性来指定使用Shiro原生Session -->
<!-- 即<property name="sessionMode" value="native"/>,详细说明见官方文档 -->
<!-- 这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替 -->
<bean id="securityManager"
class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm" />
<!-- 会话管理 -->
<property name="sessionManager" ref="sessionManager" />
</bean>
<!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行 -->
<bean id="shiroFilter"
class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager" />
<!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->
<property name="loginUrl" value="/login" />
<property name="filterChainDefinitions">
<value>
/login=anon
/404=anon
/**=authc
</value>
</property>
</bean>
<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor"
class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
<bean
class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager" />
</bean>
</beans>
登录入口:
调用 subject.login()
@ResponseBody
@PostMapping("/login")
public Result login(String username,String password,String validcode,HttpServletRequest request){
Subject subject = SecurityUtils.getSubject();
// 对密码进行二次加密
String pass = CommHelp.String2MD5Token(password);
// 如果传字符串密码,shiro会再判断非空进行toCharxx
UsernamePasswordToken token = new UsernamePasswordToken(username, pass.toCharArray());
token.setRememberMe(Boolean.FALSE);
String message = null;
try {
subject.login(token);
} catch (UnknownAccountException e) {
// 未知账户
logger.error("发生异常: ",e);
} catch (IncorrectCredentialsException e) {
// 错误的凭证
logger.error("发生异常: ",e);
} catch (LockedAccountException e) {
// 账户已锁定
logger.error("发生异常: ",e);
} catch (ExcessiveAttemptsException e) {
// 错误次数过多
logger.error("发生异常: ",e);
} catch(Exception e){
logger.error("发生异常: ",e);
}
// 验证是否登录成功
if (subject.isAuthenticated()) {
// 从subject中获取
SysUser user = (SysUser)subject.getPrincipal();
sysUserService.updateSysUserIpAndCreateTime(user.getId(),CommHelp.getIP(request));
SecurityUtils.getSubject().getSession().setAttribute("userinfo", user);
return Result.success(null);
} else {
token.clear();
}
return Result.error("用户名或密码错误");
}
自定义Realm
public class MyRealm extends AuthorizingRealm{
@Autowired
SysUserService sysUserService;
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 认证
UsernamePasswordToken passwordToken = (UsernamePasswordToken)token;
String username = passwordToken.getUsername();
if (username == null) {
throw new AccountException();
}
SysUser user = sysUserService.getSysUserByUserName(username);
if(user == null) {
// 用户不存在
throw new UnknownAccountException("账号或密码不正确");
}
// 可以判断是否被锁定等
if(user.getStatus() == 2) {
throw new LockedAccountException("账号已被锁定,请联系管理员");
}
return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// 授权
SysUser user = (SysUser)principals.getPrimaryPrincipal();
// 角色列表
Set<String> roles = new HashSet<>();
// 功能列表
Set<String> menus = new HashSet<>();
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
// 判断是否为管理员
roles = sysUserService.selectRoleByUserId(user.getId());
menus = sysUserService.selectPermsByUserId(user.getId());
// 角色加入AuthorizationInfo认证对象
simpleAuthorizationInfo.setRoles(roles);
// 权限加入AuthorizationInfo认证对象
simpleAuthorizationInfo.setStringPermissions(menus);
return simpleAuthorizationInfo;
}
}