第一步 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>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>ERROR</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
第二步 spring shiro配置
<!-- shiro的过滤工厂,相当默认的加载了9个过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 安全管理器-->
<property name="securityManager" ref="securityManager" />
<!-- 用户如果没有登陆,当他在访问资源的时候,就会自动跳转到登陆的页面 -->
<property name="loginUrl" value="/login" />
<!-- 当用户没有访问某项资源权限的时候,跳转到该页面 -->
<property name="unauthorizedUrl" value="/error" />
<!-- 过滤链的定义:定义URL访问的时候对应的认证或授权时处理的过滤器 -->
<property name="filterChainDefinitions">
<value>
/error = anon
/login*=anon
/*.html = authc
/*=authc
</value>
</property>
</bean>
<!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="mstRealm"/>
</bean>
<!--自定义的realm -->
<bean id="mstRealm" class="com.sustly.shiro.realm.MstRealm">
</bean>
第三步 自定义realm
public class MstRealm extends AuthorizingRealm {
@Resource(name = "userService")
private UserService userService;
/**
* 授权
* @param principalCollection principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
/**
* 认证
* @param authenticationToken authenticationToken
* @return AuthenticationInfo
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//通过令牌得到用户名和密码
UsernamePasswordToken upt = (UsernamePasswordToken)authenticationToken;
//得到密码
String pwd = new String(upt.getPassword());
//调用登录查询
User user = userService.login(upt.getUsername(), pwd);
if(null != user){
return new SimpleAuthenticationInfo(user,pwd,getName());
}
return null;
}
}
第四步 登陆
//1. 创建令牌,身份证明
UsernamePasswordToken upt = new UsernamePasswordToken(user.getLoginName(), user.getPassword());
//2. 获取主题 subject: 封装当前用户的一些操作
Subject subject = SecurityUtils.getSubject();
//3. 执行login
subject.login(upt);