shiro使用——整合spring
1. 引入相关配置
<dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.9.1</version></dependency>
2. 自定义Realm类 继承AuthorizingRealm 并重写相对应的方法
- 获取用户身份信息
- 调用业务层获取用户信息 (数据库)
- 非空判断,将数据封装返回
@Component
public class MyRealm extends AuthorizingRealm {@Autowiredprivate UserMapper userMapper;@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {return null;}
@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {String name = authenticationToken.getPrincipal().toString();User user = userMapper.selectById(name);if (user != null){SimpleAuthenticationInfo sai = new SimpleAuthenticationInfo(name, user.getPassword(), ByteSource.Util.bytes("salt"), MyRealm.class.getName());return sai;}return null;}
}
3. 编写shiro配置类
配置securityManager
- 创建defaultWebSecurityManager 对象
- 创建加跨对象,设置相关属性
2.1采用md5加密
2.2 迭代加密次数 - 将加对象存储到myRealm中
- 将myRealm存AdefaultWebSecurityManager 对象
- 返回
配置shiro内置过滤器拦截范围
- 需要认证
- 不需要认证
@Configuration
public class shiroConfig {@Autowiredprivate MyRealm myRealm;@Beanpublic DefaultWebSecurityManager defaultWebSecurityManager() {DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();hashedCredentialsMatcher.setHashAlgorithmName("md5");hashedCredentialsMatcher.setHashIterations(3);myRealm.setCredentialsMatcher(hashedCredentialsMatcher);defaultWebSecurityManager.setRealm(myRealm);ThreadContext.bind(defaultWebSecurityManager);return defaultWebSecurityManager;}@Beanpublic DefaultShiroFilterChainDefinition shiroFilterChainDefinition(){DefaultShiroFilterChainDefinition defaultShiroFilterChainDefinition = new DefaultShiroFilterChainDefinition();
defaultShiroFilterChainDefinition.addPathDefinition("/login","anon");defaultShiroFilterChainDefinition.addPathDefinition("/user","anon");
defaultShiroFilterChainDefinition.addPathDefinition("/**","authc");return defaultShiroFilterChainDefinition;}}
4. 回到业务层通过subject.login()方法验证登录
Subject subject = SecurityUtils.getSubject();AuthenticationToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());try {subject.login(token);}catch (Exception e){e.printStackTrace();return ComResult.error("登录失败");}return ComResult.success("登录成功");