Spring Security 基于数据库的认证

介绍

之前使用的全是基于内存的认证,这里使用基于数据库的认证。

设计数据表

这里设计数据表

Spring Security 基于数据库的认证_第1张图片

创建项目

这里使用Mybatis作为项目。

添加如下依赖

Spring Security 基于数据库的认证_第2张图片

Spring Security 基于数据库的认证_第3张图片

Spring Security 基于数据库的认证_第4张图片

添加driud连接池依赖

 
             com.alibaba
             druid
             1.1.9
         

 

完整的pom如下

 
 
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
     4.0.0
     
         org.springframework.boot
         spring-boot-starter-parent
         2.3.1.RELEASE
          
     
     com.example
     demo
     0.0.1-SNAPSHOT
     demo
     Demo project for Spring Boot
         1.8
     
         
             com.alibaba
             druid
             1.1.9
         
         
             org.springframework.boot
             spring-boot-starter-security
         
         
             org.springframework.boot
             spring-boot-starter-web
         
         
             org.mybatis.spring.boot
             mybatis-spring-boot-starter
             2.1.3
         
             mysql
             mysql-connector-java
             runtime
         
         
             org.springframework.boot
             spring-boot-starter-test
             test
             
                 
                     org.junit.vintage
                     junit-vintage-engine
                 
             
         
         
             org.springframework.security
             spring-security-test
             test
         
     
         
             
                 org.springframework.boot
                 spring-boot-maven-plugin
             
         
     

 

配置数据库

 spring:
   datasource:
     type: com.alibaba.druid.pool.DruidDataSource
     username: root
     password: ABCcba20170607
     url: jdbc:mysql://cdb-1yfd1mlm.cd.tencentcdb.com:10056/test

 

创建对应的实体类

 package com.example.demo.domain;
 ​
 import org.springframework.security.core.GrantedAuthority;
 import org.springframework.security.core.authority.SimpleGrantedAuthority;
 import org.springframework.security.core.userdetails.UserDetails;
 ​
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
 ​
 public class User implements UserDetails {
     private Integer id;
     private String username;
     private String password;
     private Boolean enabled;
     private Boolean locked;
     private List roles;
 ​
 ​
     @Override
     // 实体类和SpringSecurity转换
     public Collectionextends GrantedAuthority> getAuthorities() {
         List authorities = new ArrayList<>();
         for (Role role : roles) {
             authorities.add(new SimpleGrantedAuthority(role.getName()));
         }
         return authorities;
     }
 ​
     @Override
     public String getPassword() {
         return null;
     }
 ​
     @Override
     public String getUsername() {
         return null;
     }
 ​
     @Override
     public boolean isAccountNonExpired() {
         return false;
     }
 ​
     @Override
     public boolean isAccountNonLocked() {
         return false;
     }
 ​
     @Override
     public boolean isCredentialsNonExpired() {
         return false;
     }
 ​
     @Override
     public boolean isEnabled() {
         return false;
     }
 ​
     public Integer getId() {
         return id;
     }
 ​
     public void setId(Integer id) {
         this.id = id;
     }
 ​
     public void setUsername(String username) {
         this.username = username;
     }
 ​
     public void setPassword(String password) {
         this.password = password;
     }
 ​
     public Boolean getEnabled() {
         return enabled;
     }
 ​
     public void setEnabled(Boolean enabled) {
         this.enabled = enabled;
     }
 ​
     public Boolean getLocked() {
         return locked;
     }
 ​
     public void setLocked(Boolean locked) {
         this.locked = locked;
     }
 ​
     public List getRoles() {
         return roles;
     }
 ​
     public void setRoles(List roles) {
         this.roles = roles;
     }
 }
 package com.example.demo.domain;
 ​
 public class Role {
     private Integer id;
     private String name;
     private String nameZh;
 ​
     public Integer getId() {
         return id;
     }
 ​
     public void setId(Integer id) {
         this.id = id;
     }
 ​
     public String getName() {
         return name;
     }
 ​
     public void setName(String name) {
         this.name = name;
     }
 ​
     public String getNameZh() {
         return nameZh;
     }
 ​
     public void setNameZh(String nameZh) {
         this.nameZh = nameZh;
     }
 }

 

创建UserService

 package com.example.demo.mapper;
 ​
 import com.example.demo.domain.Role;
 import org.apache.ibatis.annotations.Mapper;
 import org.apache.ibatis.annotations.Select;
 import org.graalvm.compiler.nodeinfo.StructuralInput;
 import org.springframework.security.core.userdetails.User;
 ​
 import java.util.List;
 ​
 @Mapper
 public interface UserMapper {
     @Select("select * from user where username=#{username}")
     public User loadUserByUsername(String username);
 ​
     @Select("select * from role r, user_role ur where r.id = ur.rid and ur.uid = #{id}")
     public List getUserRoleByUid(Integer id);
 }

 

配置Spring Security

 package com.example.demo.config;
 ​
 import com.example.demo.service.UserService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Configurable;
 import org.springframework.context.annotation.Bean;
 import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
 import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
 import org.springframework.security.crypto.password.PasswordEncoder;
 ​
 ​
 @Configurable
 public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
     @Autowired
     private UserService userService;
 ​
     @Bean
     PasswordEncoder passwordEncoder(){
         return new BCryptPasswordEncoder();
     }
 ​
     @Override
     protected void configure(AuthenticationManagerBuilder auth) throws Exception {
         auth.userDetailsService(userService);
     }
 ​
     @Override
     protected void configure(HttpSecurity http) throws Exception {
         http.authorizeRequests()
                 .antMatchers("/admin/**").hasRole("admin")
                 .anyRequest().authenticated()
                 .and()
                 .formLogin()
                 .loginProcessingUrl("/login").permitAll()
                 .and()
                 .csrf().disable();
     }
 }

 

至此完成。

学习java,你掌握这些。二三线也能轻松拿8K以上

你可能感兴趣的:(Spring Security 基于数据库的认证)