pom.xml
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
application.yml:
spring:
datasource:
username: benti
password: 80238023
url: jdbc:mysql://localhost:3306/ssm
driver-class-name: com.mysql.cj.jdbc.Driver
# 切换数据源 使用Druid的数据源
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
# MyBatis
mybatis:
typeAliasesPackage: com.benti.pojo
mapperLocations: classpath:mapper/*.xml
pojo.User:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
private String perms;
}
com.benti.mapper.UserMapper:
@Repository
@Mapper
//这个注解 表示这是一个mybatis的mapper类
public interface UserMapper {
User queryUserByName(String name);
}
mapper.UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.benti.mapper.UserMapper">
<select id="queryUserByName" parameterType="String" resultType="User">
select * from ssm.user where name = #{name}
</select>
</mapper>
com.benti.service.UserService:
public interface UserService {
User queryUserByName(String name);
}
com.benti.service.UserServiceImpl:
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserMapper userMapper;
@Override
public User queryUserByName(String name) {
return userMapper.queryUserByName(name);
}
}
com.benti.config.ShiroConfig:
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean 第三步
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
//添加shiro的内置过滤器
/*
anon:无需认证,就可以访问
authc:必须认证了才能访问
user: 必须拥有了记住我功能才能用
perms:拥有对某个资源的权限才能访问;
role:拥有某个角色权限才能访问
*/
//拦截
Map<String, String> filterMap = new LinkedHashMap<>();
// 配置访问权限 必须是LinkedHashMap,因为它必须保证有序
// 过滤链定义,从上向下顺序执行,一般将 /**放在最为下边 --> : 这是一个坑,一不小心代码就不好使了
//设置权限,未授权 跳转到未授权页面
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
// filterMap.put("/user/add","authc");
// filterMap.put("/user/update","authc");
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
bean.setLoginUrl("/toLogin");
//设置未授权页面
bean.setUnauthorizedUrl("/noauth");
return bean;
}
//DefaultWebSecurityManager 第二步
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联realm
securityManager.setRealm(userRealm());
return securityManager;
}
//创建realm对象 ,需要自定义类 第一步
@Bean
public UserRealm userRealm() {
return new UserRealm();
}
//整合shiroDialect: 用来整合shiro thymeleaf
}
com.benti.config.UserRealm:
//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了授权 doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//拿到当前登录的这个对象:
Subject subject = SecurityUtils.getSubject();
User currentUser = (User) subject.getPrincipal();//拿到user对象
//设置用户权限:
info.addStringPermission(currentUser.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了认证 doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//连接真实数据库
User user = userService.queryUserByName(userToken.getUsername());
if (user==null) {
return null;//抛出异常 UnknownAccountException
}
//密码认证,shiro做
//可以加密:MD5 MD5盐值加密
//SimpleAuthenticationInfo:(参数)
//userInfo, //
// 用户名–此处传的是用户对象 直接通过token.getPrincipal()方法获取—获取当前记录的用户名,从这个用户名获取一系列的对应需求属性。
// 这里传入user 在上面授权中就可以使用
//userInfo.getPassword(), //密码—从数据库中获取的密码
//salt, 盐–用于加密密码对比
//getName() //当前的realm名
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}
com.benti.controller.MyController:
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model) {
model.addAttribute("msg","hello,shiro");
return "index";
}
@RequestMapping("/user/add")
public String add() {
return "user/add";
}
@RequestMapping("/user/update")
public String update() {
return "user/update";
}
@RequestMapping("/toLogin")
public String toLogin() {
return "login";
}
@RequestMapping("/login")
public String login(String username,String password,Model model) {
//获取当前用户
Subject subject = SecurityUtils.getSubject();
//封装用户的登录数据
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);//执行登录方法,如果没有异常就说明OK了
return "index";
}catch (UnknownAccountException e) {//用户名不存在的异常
model.addAttribute("msg","用户名错误");
return "login";
}catch (IncorrectCredentialsException e) {//密码错误的异常
model.addAttribute("msg","密码错误");
return "login";
}
}
@RequestMapping("/noauth")
@ResponseBody
public String unauthorized() {
return "未经授权,无法访问页面";
}
//设置登出
@RequestMapping("/loginOut")
public String loginOut() {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "index";
}
}
login.html:
<body>
<h1>登录</h1>
<p th:text="${msg}" style="color: red";></p>
<form th:action="@{/login}" >
<p>用户名:<input type="text" name="username"></p>
<p>密码:<input type="text" name="password"></p>
<p><input type="submit" value="登录"></p>
<input type="checkbox" name="remember">记住我
</form>
<a th:href="@{/loginOut}"><button>注销</button></a>
</body>