1 、Shiro 三大核心对象
- Subject:其实是当前正在执行的用户对象
- SecurityManager:管理所有对象
- Realms:连接数据
2 依赖
Shiro的依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.1</version>
</dependency>
Shrio和Spring的整合依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
3 配置过滤器
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultSecurityManager defaultSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
// 设置安全管理器
bean.setSecurityManager(defaultSecurityManager);
/*
添加Shiro内置过滤器,常用的有如下过滤器:
anon:无需认证就可以访问
authc:必须认证了才能访问
user:必须拥有rememberMe才能用
perms:拥有对某个资源的权限才能用
role:拥有某个角色权限
*/
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/user/add", "authc");
filterChainDefinitionMap.put("/user/update", "authc");
// 支持通配符的方式
// filterChainDefinitionMap.put("/user/*", "authc");
bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
// 设置登录请求
bean.setLoginUrl("/toLogin");
return bean;
}
4 自定义UserRealm
public class UserRealm extends AuthorizingRealm {
// 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("============执行授权============");
return null;
}
// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("============执行认证============");
// 用户名,密码 实际应该是从数据库中取
String username = "root";
String password = "root";
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
if (!usernamePasswordToken.getUsername().equals(username)) {
return null; // 抛出异常 UnknownAccountException
}
// 密码认证
return new SimpleAuthenticationInfo("", password, "");
}
}