1、增加 Shiro 依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
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<String, String> 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(),"");
}
}