org.apache.shiro
shiro-spring-boot-web-starter
1.9.1
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-devtools
runtime
true
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.apache.logging.log4j
log4j-core
2.17.2
org.springframework.boot
spring-boot-starter-data-jdbc
2.7.2
org.springframework.boot
spring-boot-starter-jdbc
2.7.2
mysql
mysql-connector-java
8.0.29
com.alibaba
druid
1.2.11
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.2.2
注意:父工程是普通maven项目中导入的依赖,在子项目springboot中无法沿用
@SpringBootTest
class ShiroSpringbootApplicationTests {
@Autowired
UserMapper userMapper;
@Test
void contextLoads() {
Map map = new HashMap(15);
map.put("id","20");
User user = userMapper.getUser(map);
System.out.println(user.toString());
}
}
//User(id=20, name=李云, password=123456, email=123456@qq.com, birthday=Wed Aug 03 00:00:00 CST 2022)
package com.example.config;
import com.example.mapper.UserMapper;
import com.example.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* @author CNCLUKZK
* @create 2022/8/5-19:45
*/
//自定义UserRealm extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
UserMapper userMapper;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了授权doGetAuthorizationInfo方法!");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了认证doGetAuthenticationInfo方法!");
//连接真实数据库
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
Map map = new HashMap(15);
/*(String)userToken.getPrincipal() == userToken.getUsername()*/
map.put("name",userToken.getUsername());
User user = userMapper.getUser(map);
if (user==null) {
return null; //抛出UnknownAccountException异常
}
/*可以加密:
MD5加密:e10adc3949ba59abbe56e057f20f883e
MD5盐值加密(密码混合账户): e10adc3949ba59abbe56e057f20f883eusername*/
//密码认证,shiro做,加密了,默认是简单验证new SimpleCredentialsMatcher()明文验证
return new SimpleAuthenticationInfo("",user.getPassword(),"");
}
}
连接真实数据库后登陆时,如果账号是重名,那么生成token失败登陆失败
密码认证,shiro做,加密了,默认是简单验证new SimpleCredentialsMatcher()的明文验证
//第一步:创建Realm对象,需要自定义类
@Bean
public UserRealm userRealm(){
UserRealm userRealm = new UserRealm();
userRealm.setCredentialsMatcher(new Md5CredentialsMatcher());
return userRealm;
}