1、添加Shiro依赖
org.apache.shiro
shiro-spring
1.4.1
2、创建ShiroConfig
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
//添加shiro的内置过滤器
/*
anon:无需认证可以访问
authc:必须认证才能访问
user:必须拥有 记住我 功能才能用
perms:拥有对某个资源的权限才能访问
role:拥有某个角色权限才能访问
*/
//拦截
Map filterMap = new LinkedHashMap<>();
// filterMap.put("/user/add","authc");
// filterMap.put("/user/update","authc");
filterMap.put("/login/*","anon");
bean.setFilterChainDefinitionMap(filterMap);
//验证失败跳转页面
bean.setLoginUrl("/Text");
return bean;
}
@Bean
public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(userRealm);
return securityManager;
}
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
}
3、Realm授权、认证
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权执行");
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("认证执行");
// UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//
// //连接真实的数据库
// User user = userService.queryUserByName(token.getUsername());
//
// if (user == null){//没有此用户
// return null;
// }
//密码认证 shiro做
return new SimpleAuthenticationInfo("",token.getPassword(),"");
}
}