使用idea创建SpringBoot工程,必须有网
1、添加依赖pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.qfedu</groupId>
<artifactId>day48_springboot_shiro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>day48_springboot_shiro</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.28</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
在此处,不需要添加端口依赖,因为springboot有热部署,有默认的8080端口
2、配置文件,在resources目录下
application.yml
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://localhost:3306/rbac?useSSL=true&serverTimezone=UTC&characterEncoding=UTF-8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
thymeleaf:
cache: false
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.qfedu.entity
3、前端文件,在resources目录下templates目录保存页面文件
login.html`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<h1>this is index page.</h1>
<form action="login" method="post">
username:<input type="text" name="username" /><p />
password:<input type="text" name="password" /><p />
<input type="submit" value="submit" /><p />
</form>
</body>
</html>
main.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<h1>this is main page.</h1>
</body>
</html>
4、配置类
ShiroConfig.java
package com.qfedu.config;
import com.qfedu.shiro.MyRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
Map<String, String> map = new HashMap<>();
map.put("/login", "anon");
map.put("/main", "roles[manager]");
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setUnauthorizedUrl("/unauth");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
@Bean(name = "defaultWebSecurityManager")
public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("myRealm")MyRealm realm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
/**
* 开启shiro的注解
* 需要借助SpringAOP扫描Shiro注解的类,来进行安全校验
* @return
*/
@Bean
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
}
/**
* 开启aop的注解支持
* @param defaultWebSecurityManager
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager defaultWebSecurityManager){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(defaultWebSecurityManager);
return authorizationAttributeSourceAdvisor;
}
}
5、Realm类
package com.qfedu.shiro;
import com.qfedu.entity.Permission;
import com.qfedu.entity.Role;
import com.qfedu.entity.User;
import com.qfedu.service.IUserService;
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.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
@Component("myRealm")
public class MyRealm extends AuthorizingRealm {
@Resource
private IUserService iUserService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
String username = getAvailablePrincipal(principals).toString();
List<Role> rlist = iUserService.getRolesByUsername(username);
for (Role r:rlist) {
info.addRole(r.getRname());
}
List<Permission> plist = iUserService.getPermissionByUsername(username);
for (Permission p:plist ) {
info.addStringPermission(p.getPname());
}
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info=null;
UsernamePasswordToken tk=(UsernamePasswordToken) token;
String username = tk.getUsername();
char[] passwords = tk.getPassword();
String password = new String(passwords);
User u = iUserService.Login(username, password);
if(u!=null&&u.getUid()!=0){
String name=getName();
info=new SimpleAuthenticationInfo(username,password,name);
}
return info;
}
}
6、实体类
User,java
package com.qfedu.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.Set;
/**
* (User)实体类
*
* @author makejava
* @since 2020-04-14 11:06:42
*/
@Data
public class User implements Serializable {
private static final long serialVersionUID = 617289138502785533L;
private Integer uid;
private String username;
private String password;
private String tel;
private String addr;
private Set<Role> rs;
}
Role.java
package com.qfedu.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.Set;
/**
* (Role)实体类
*
* @author makejava
* @since 2020-04-14 11:06:42
*/
@Data
public class Role implements Serializable {
private static final long serialVersionUID = -74163700661732397L;
private Integer rid;
private String rname;
private String rdesc;
private Set<Permission> ps;
}
Permission.java
package com.qfedu.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.Set;
/**
* (Permission)实体类
*
* @author makejava
* @since 2020-04-14 11:06:42
*/
@Data
public class Permission implements Serializable {
private static final long serialVersionUID = 581645870054218482L;
private Integer pid;
private String pname;
private String pdesc;
}
7、业务类
IUserDao.java
package com.qfedu.dao;
import com.qfedu.entity.Permission;
import com.qfedu.entity.Role;
import com.qfedu.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface IUserDao {
User getUserByNameAndPass(@Param("username")String username,@Param("password")String password);
List<Role> getRolesByUsername(String username);
List<Permission> getPermissionByUsername(String username);
}
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属性 -->
<mapper namespace="com.qfedu.dao.IUserDao">
<select id="getUserByNameAndPass" resultType="user">
select * from user where username = #{
username} and password = #{
password}
</select>
<select id="getRolesByUsername" resultType="role">
SELECT r.* FROM user u
INNER JOIN user_role ur on u.uid = ur.uid
INNER JOIN Role r on r.rid = ur.rid
WHERE u.username =#{
username};
</select>
<select id="getPermissionByUsername" resultType="permission">
SELECT p.* FROM user u
INNER JOIN user_role ur on u.uid = ur.uid
INNER JOIN Role r on r.rid = ur.rid
INNER JOIN role_perms rp on r.rid = rp.rid
INNER JOIN permission p on p.pid = rp.pid
WHERE u.username = #{
username}
</select>
</mapper>
8、服务类
IUserService.java
package com.qfedu.service;
import com.qfedu.entity.Permission;
import com.qfedu.entity.Role;
import com.qfedu.entity.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface IUserService {
User Login(@Param("username")String username, @Param("password")String password);
List<Role> getRolesByUsername(String username);
List<Permission> getPermissionByUsername(String username);
}
IUserServiceImpl.java
package com.qfedu.service.impl;
import com.qfedu.dao.IUserDao;
import com.qfedu.entity.Permission;
import com.qfedu.entity.Role;
import com.qfedu.entity.User;
import com.qfedu.service.IUserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class IUserServiceImpl implements IUserService {
@Resource
private IUserDao iUserDao;
@Override
public User Login(String username, String password) {
return iUserDao.getUserByNameAndPass(username,password);
}
@Override
public List<Role> getRolesByUsername(String username) {
return iUserDao.getRolesByUsername(username);
}
@Override
public List<Permission> getPermissionByUsername(String username) {
return iUserDao.getPermissionByUsername(username);
}
}
9、控制器
UserController.java
package com.qfedu.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class UserController {
@GetMapping("/")
public String PreLog(){
return "login";
}
@PostMapping("/login")
public String login(String username,String password){
System.out.println(username+"----------"+password);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);
return "main";
} catch (AuthenticationException e) {
e.printStackTrace();
return "login";
}
}
}
完成!!!