目录
1、引入shrio依赖
Shiro 官方提供了 Spring Boot 启动器:shiro-spring-boot-starter,在 pom.xml
文件中引入:
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>1.4.0</version>
</dependency>
2、自定义 一个Realm类
Realm 是控制认证和授权的核心部分,也是开发人员必须自己实现的部分。
实现自定义 Realm 最快捷的方式是继承 AuthorizingRealm 类
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Set;
/**
* @author zhz
*/
public class CustomRealm extends AuthorizingRealm {
@Autowired
private ShiroSampleDao shiroSampleDao;
/**
* 认证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String username = token.getUsername();
String password = this.shiroSampleDao.getPasswordByUsername(username);
return new SimpleAuthenticationInfo(username, password, getName());
}
/**
* 授权
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String username = (String) super.getAvailablePrincipal(principalCollection);
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
Set<String> roles = shiroSampleDao.getRolesByUsername(username);
authorizationInfo.setRoles(roles);
roles.forEach(role -> {
Set<String> permissions = this.shir