1、导入依赖
spring-boot-starter-web
mybatis-plus-boot-starter
shiro-spring-boot-web-starter
mysql-connector-java
lombok
2、配置类
@Configuration
public class ShiroConfig {
//注册realm
@Bean
public Realm ShiroRealm(){
return new ShiroRealm();
}
//对shiro过滤器进行设置
@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition(){
DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
definition.addPathDefinition("/","anon");
definition.addPathDefinition("/account/login","anon");
definition.addPathDefinition("/logout","logout");
definition.addPathDefinition("/**","user");
return definition;
}
}
3、shiro认证过程
用户及密码在controller接收到
@PostMapping("login")
public String login(String accountName,String password){
//提交请求的subject,而主体subject可以通过shiro提供的一个工具类SecurityUtils来获取
Subject subject = SecurityUtils.getSubject();
//主体Subject提交请求给Security Manager,---->subject.login(token),提交请求时需要一个token,所以要先创建token
subject.login(new UsernamePasswordToken(accountName,password));
return "success";
}
4、自定义 realm
public class ShiroRealm extends AuthorizingRealm {
@Autowired
private AccountMapper accountMapper;
@Autowired
private RoleMapper roleMapper;
@Autowired
private PermissionMapper permissionMapper;
@Override
//用来做授权(就是检验当前用户是否拥有权限时使用的)
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//1.先获取到用户名信息
Account account = (Account) principals.getPrimaryPrincipal();
//通过id信息查询相关权限
List<Role> roleList = roleMapper.searchRoleByAccountId(account.getAccountId());
Set<String> accountRoles = roleList.stream()
.map(r -> r.getRoleName())
.collect(Collectors.toSet());
List<String> permissions = new ArrayList<>();
if (roleList.size()>0){
permissions=permissionMapper.searchPermissionInIds(roleList);
}
//返回用户权限信息
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.setStringPermissions(new HashSet<>(permissions));
authorizationInfo.setRoles(accountRoles);
return authorizationInfo;
}
@Override
//用来做认证(login时用到的),Security Manager调用认证器器Authorizer授权
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 1.先通过主体传过来的验证信息获取用户名
Object username = token.getPrincipal();
//去数据库查询用户名
QueryWrapper<Account> wrapper = new QueryWrapper<>();
wrapper.eq("account_name",username);
List<Account> list = accountMapper.selectList(wrapper);
if (list.size()==0){
throw new UnknownAccountException(username+"用户不存在");
}
if (list.size()>1){
throw new AccountException("系统异常,出现多个"+username+"用户");
}
//查询到用户,则返回AuthenticationInfo对象
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(list.get(0),
list.get(0).getPassword(),
ShiroRealm.class.getName());
return authenticationInfo;
}
}
shiro工作图解