For some reason, we need to learn about the security framework spring. (Research for a long time, if the user authentication and authorization only say this child, I still feel shiro easy to use.)
spring security description can refer to the following documents:
(Full of envy ah) I'm not here to pull up.
http://www.tianshouzhi.com/api/tutorials/spring_security_4/252
First, first posted the code
Below is my project structure
Of course, I used springboot + thymeleaf + mybatis + mysql
1. The use of pom.xml
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-web</artifactId> 4 </dependency> 5 6 <dependency> 7 <groupId>org.springframework.boot</groupId> 8 <artifactId>spring-boot-starter-test</artifactId> 9 <scope>test</scope> 10 </dependency> 11 12 <dependency> 13 <groupId>org.mybatis.spring.boot</groupId> 14 <artifactId>mybatis-spring-boot-starter</artifactId> 15 <version>2.0.1</version> 16 </dependency> 17 18 <!-- mysql --> 19 <dependency> 20 <groupId>mysql</groupId> 21 <artifactId>mysql-connector-java</artifactId> 22 <version>5.1.32</version> 23 </dependency> 24 25 <!-- lombok --> 26 <dependency> 27 <groupId>org.projectlombok</groupId> 28 <artifactId>lombok</artifactId> 29 <version>1.18.8</version> 30 <scope>provided</scope> 31 </dependency> 32 33 <!-- security+thymeleaf --> 34 <dependency> 35 <groupId>org.springframework.boot</groupId> 36 <artifactId>spring-boot-starter-security</artifactId> 37 <version>2.1.5.RELEASE</version> 38 </dependency> 39 40 <dependency> 41 <groupId>org.springframework.boot</groupId> 42 <artifactId>spring-boot-starter-thymeleaf</artifactId> 43 <!-- <version>2.1.3.RELEASE</version>--> 44 </dependency> 45 <dependency> 46 <groupId>org.thymeleaf.extras</groupId> 47 <artifactId>thymeleaf-extras-springsecurity4</artifactId> 48 <version>3.0.2.RELEASE</version> 49 </dependency>
2. Core configuration class
1 import org.springframework.context.annotation.Bean; 2 import org.springframework.context.annotation.Configuration; 3 import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 4 import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 6 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 7 import org.springframework.security.core.userdetails.UserDetailsService; 8 import org.springframework.security.crypto.password.MessageDigestPasswordEncoder; 9 10 @Configuration 11 @EnableWebSecurity 12 public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 13 @Bean 14 UserDetailsService customUserService(){ //注册UserDetailsService 的bean 15 return new UserDetailsServiceImpl(); 16 } 17 18 @Override 19 protected void configure(AuthenticationManagerBuilder auth) throws Exception { 20 auth.userDetailsService(customUserService()).passwordEncoder(new MessageDigestPasswordEncoder("MD5")); //user Details Service验证 21 } 22 @Override 23 protected void configure(HttpSecurity http) throws Exception { 24 http.authorizeRequests() 25 .anyRequest().authenticated() //authenticated任何请求,登录后可以访问 26 .and() 27 .csrf().disable() 28 .formLogin() 29 .loginPage ( "/ the User / the Login") // 30 .defaultSuccessUrl ( "/ the User / index" ) 31 .failureUrl ( "/ the User / the Login? error = to true" ) 32 .permitAll () // login page to access any user 33 is .AND () 34 is .logout () permitAll ();. // logout behavior discretionary access 35 } 36 }
3.UserDetailsServiceImpl
1 import com.qx.demo.entity.RolePo; 2 import com.qx.demo.entity.UserPo; 3 import com.qx.demo.service.UserService; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.security.core.authority.SimpleGrantedAuthority; 6 import org.springframework.security.core.userdetails.User; 7 import org.springframework.security.core.userdetails.UserDetails; 8 import org.springframework.security.core.userdetails.UserDetailsService; 9 import org.springframework.security.core.userdetails.UsernameNotFoundException; 10 11 import java.util.HashSet; 12 import java.util.Set; 13 14 public class UserDetailsServiceImpl implements UserDetailsService { 15 @Autowired 16 UserService service; 17 @Override 18 public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { 19 UserPo user = service.getUserById(s); 20 if (user==null){ 21 throw new UsernameNotFoundException("用户名不存在"); 22 } 23 Set<SimpleGrantedAuthority> authorities = new HashSet<>(); 24 for (RolePo item:user.getRoles()){ 25 authorities.add(new SimpleGrantedAuthority(item.getRName())); 26 System.out.println(item.getRName()); 27 } 28 return new User(user.getUsername(),user.getPassword(),authorities); 29 } 30 }
4. Control Layer Controller
1 import com.qx.demo.service.UserService; 2 import org.springframework.beans.factory.annotation.Autowired; 3 import org.springframework.security.core.Authentication; 4 import org.springframework.security.core.userdetails.User; 5 import org.springframework.stereotype.Controller; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 import org.springframework.web.servlet.ModelAndView; 8 9 import javax.servlet.http.HttpServletRequest; 10 11 @Controller 12 @RequestMapping("user") 13 public class UserController { 14 @Autowired 15 private UserService service; 16 @RequestMapping("login") 17 public ModelAndView toLogin(HttpServletRequest request){ 18 ModelAndView mv= new ModelAndView("login"); 19 String error = request.getParameter("error"); 20 if (error!=null && error.equals("true")){ 21 System.out.println("登录失败"); 22 } 23 return mv; 24 } 25 @RequestMapping("index") 26 public String getUserById( Authentication authentication){ 27 User principal = (User)authentication.getPrincipal(); 28 if (authentication!=null) 29 System.out.println(authentication.getCredentials()+",\n"+authentication.getDetails()+",\n"+authentication.getPrincipal()+",\n"+authentication.getName()); 30 return "index"; 31 } 32 }
The entity class
1 import lombok.Data; 2 import lombok.ToString; 3 4 import java.util.List; 5 6 @Data 7 @ToString 8 public class UserPo { 9 private int uid; 10 private String username; 11 private String password; 12 private List<RolePo> roles; 13 }
1 import lombok.Data; 2 import lombok.ToString; 3 4 import java.util.List; 5 6 @Data 7 @ToString 8 public class RolePo { 9 private int rid; 10 private String rName; 11 private List<PermissionPo> pers; 12 }
1 import lombok.Data; 2 import lombok.ToString; 3 4 @Data 5 @ToString 6 public class PermissionPo { 7 private int pid; 8 private String pName; 9 private String pPer; 10 }
6.Dao layer
1 import com.qx.demo.entity.UserPo; 2 3 public interface UserMapper { 4 UserPo getUserByUsername(String username); 5 }
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 4 <mapper namespace="com.qx.demo.dao.UserMapper"> 5 6 <resultMap id="getRoleAndPer" type="com.qx.demo.entity.UserPo"> 7 <id column="uid" property="uid"></id> 8 <result column="username" property="username"></result> 9 <result column="password" property="password"></result> 10 <collection property="roles" ofType="com.qx.demo.entity.RolePo"> 11 <id column="rid" property="rid"></id> 12 <result column="r_name" property="rName"></result> 13 <collection property="pers" ofType="com.qx.demo.entity.PermissionPo"> 14 <id column="pid" property="pid"></id> 15 <result column="p_name" property="pName"></result> 16 <result column="p_per" property="pPer"></result> 17 </collection> 18 </collection> 19 </resultMap> 20 <select id="getUserByUsername" parameterType="String" resultMap="getRoleAndPer"> 21 SELECT * FROM qx_user qu 22 INNER JOIN `qx_user_role` qur ON qu.`uid`=qur.`u_id` 23 INNER JOIN qx_role qr ON qur.`r_id` = qr.`rid` 24 INNER JOIN qx_role_per qrp ON qr.`rid`=qrp.`pid` 25 INNER JOIN qx_permission qp ON qrp.`pid`=qp.`pid` 26 WHERE username=#{_parameter} 27 </select> 28 </mapper>
7.service layer
1 import com.qx.demo.entity.UserPo; 2 3 public interface UserService { 4 UserPo getUserById(String id); 5 }
1 import com.qx.demo.dao.UserMapper; 2 import com.qx.demo.entity.UserPo; 3 import com.qx.demo.service.UserService; 4 import org.springframework.stereotype.Service; 5 6 import javax.annotation.Resource; 7 8 @Service 9 public class UserServiceImpl implements UserService { 10 @Resource 11 private UserMapper mapper; 12 @Override 13 public UserPo getUserById(String username) { 14 return mapper.getUserByUsername(username); 15 } 16 }
8.application.properties
1 mybatis.mapper-locations=/mapper/*.xml 2 mybatis.type-aliases-package=com.qx.demo.entity 3 4 spring.datasource.driver-class-name=com.mysql.jdbc.Driver 5 spring.datasource.url=jdbc:mysql:///qx 6 spring.datasource.username=root 7 spring.datasource.data-password=root 8 9 spring.thymeleaf.mode=HTML5 10 spring.thymeleaf.cache=false 11 12 logging.level.com.qx.demo.dao=debug