欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Security基于數(shù)據(jù)庫(kù)實(shí)現(xiàn)認(rèn)證過(guò)程解析

 更新時(shí)間:2020年08月17日 10:01:53   作者:柒丶月  
這篇文章主要介紹了Spring Security基于數(shù)據(jù)庫(kù)實(shí)現(xiàn)認(rèn)證過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

創(chuàng)建數(shù)據(jù)庫(kù)

SET FOREIGN_KEY_CHECKS=0;
	-- ----------------------------
	-- Table structure for role
	-- ----------------------------
	DROP TABLE IF EXISTS `role`;
	CREATE TABLE `role` (
	`id` int(11) NOT NULL AUTO_INCREMENT,
	`name` varchar(32) DEFAULT NULL,
	`nameZh` varchar(32) DEFAULT NULL,
	PRIMARY KEY (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
	-- ----------------------------
	-- Records of role
	-- ----------------------------
	INSERT INTO `role` VALUES ('1', 'dba', '數(shù)據(jù)庫(kù)管理員');
	INSERT INTO `role` VALUES ('2', 'admin', '系統(tǒng)管理員');
	INSERT INTO `role` VALUES ('3', 'user', '用戶');
	-- ----------------------------
	-- Table structure for user
	-- ----------------------------
	DROP TABLE IF EXISTS `user`;
	CREATE TABLE `user` (
	`id` int(11) NOT NULL AUTO_INCREMENT,
	`username` varchar(32) DEFAULT NULL,
	`password` varchar(255) DEFAULT NULL,
	`enabled` tinyint(1) DEFAULT NULL,
	`locked` tinyint(1) DEFAULT NULL,
	PRIMARY KEY (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
	-- ----------------------------
	-- Records of user
	-- ----------------------------
	INSERT INTO `user` VALUES ('1', 'root', '$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq', '1', '0');
	INSERT INTO `user` VALUES ('2', 'admin', '$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq', '1', '0');
	INSERT INTO `user` VALUES ('3', 'sang', '$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq', '1', '0');
	-- ----------------------------
	-- Table structure for user_role
	-- ----------------------------
	DROP TABLE IF EXISTS `user_role`;
	CREATE TABLE `user_role` (
	`id` int(11) NOT NULL AUTO_INCREMENT,
	`uid` int(11) DEFAULT NULL,
	`rid` int(11) DEFAULT NULL,
	PRIMARY KEY (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
	-- ----------------------------
	-- Records of user_role
	-- ----------------------------
	INSERT INTO `user_role` VALUES ('1', '1', '1');
	INSERT INTO `user_role` VALUES ('2', '1', '2');
	INSERT INTO `user_role` VALUES ('3', '2', '2');
	INSERT INTO `user_role` VALUES ('4', '3', '3');
	SET FOREIGN_KEY_CHECKS=1;

導(dǎo)入依賴

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>2.1.3</version>
</dependency>

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
  <version>5.1.46</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid-spring-boot-starter</artifactId>
  <version>1.1.22</version>
</dependency>

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/javaboy?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

讓bean實(shí)現(xiàn)UserDetails接口

public class User implements UserDetails {
  private Integer id;
  private String username;
  private String password;
  private Boolean enabled;
  private Boolean locked;

  private List<Role> roles;

  public List<Role> getRoles() {
    return roles;
  }

  public void setRoles(List<Role> roles) {
    this.roles = roles;
  }

  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 void setEnabled(Boolean enabled) {
    this.enabled = enabled;
  }

  public void setLocked(Boolean locked) {
    this.locked = locked;
  }

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
    List<SimpleGrantedAuthority> authorities = new ArrayList<>();
    for (Role role : roles) {
      authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
    }
    return authorities;
  }

  @Override
  public String getPassword() {
    return password;
  }

  public String getUsername() {
    return username;
  }

  //賬戶是否未過(guò)期
  @Override
  public boolean isAccountNonExpired() {
    return true;
  }

  //賬戶是否未鎖定
  @Override
  public boolean isAccountNonLocked() {
    return !locked;
  }

  @Override
  public boolean isCredentialsNonExpired() {
    return true;
  }

  @Override
  public boolean isEnabled() {
    return enabled;
  }
}

public class Role {
  private Integer id;
  private String name;
  private String nameZh;
...
}

userMapper

在類上直接加@Mapper或者在SpringBoot啟動(dòng)類上配置全局的掃描@MapperScan(basePackages="")

@Mapper
public interface UserMapper {
  User loadUserByUsername(String username);

  List<Role> getUserRolesById(Integer id);
}

<?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.qwl.mysecuritydb.mapper.UserMapper">
  <select id="loadUserByUsername" resultType="com.qwl.mysecuritydb.bean.User">
    select * from user where username = #{username}
  </select>
  <select id="getUserRolesById" resultType="com.qwl.mysecuritydb.bean.Role">
    select * from role where id in(select rid from user_role where uid=#{id})
  </select>
</mapper>

userService 同樣也要繼承UserServiceDetails接口

@Service
public class UserService implements UserDetailsService {
  @Autowired
  UserMapper userMapper;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user =userMapper.loadUserByUsername(username);
    if(user==null){
      throw new UsernameNotFoundException("用戶不存在");
    }
    user.setRoles(userMapper.getUserRolesById(user.getId()));
    return user;
  }
}

HelloController

@RestController
public class HelloController {
  @GetMapping("/hello")
  public String hello(){
    return "hello security";
  }

  @GetMapping("/dba/hello")
  public String dba(){
    return "hello dba";
  }

  @GetMapping("/admin/hello")
  public String admin(){
    return "hello admin";
  }

  @GetMapping("/user/hello")
  public String user(){
    return "hello user";
  }
}

SecurityConfig

  • SercurityConfig需要繼承WebSecurityConfigurerAdapter類,并在類上加@Configuration
  • SpringSecurity5.0之后密碼必須加密
  • 把數(shù)據(jù)庫(kù)查出的用戶信息交給SpringSecurity處理
  • 配置httpSercurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  UserService userService;

		//把數(shù)據(jù)庫(kù)查出的用戶信息交給SpringSecurity處理
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userService);
  }

  @Bean
  PasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder();
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/dba/**").hasRole("dba")
        .antMatchers("/admin/**").hasRole("admin")
        .antMatchers("/user/**").hasRole("user")
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .permitAll()
        .and()
        .csrf().disable();

  }
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • SpringBoot集成P6spy實(shí)現(xiàn)自定義SQL日志打印

    SpringBoot集成P6spy實(shí)現(xiàn)自定義SQL日志打印

    本文主要介紹了SpringBoot集成P6spy實(shí)現(xiàn)自定義SQL日志打印,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07
  • SpringBoot配置logback.xml 多環(huán)境的操作步驟

    SpringBoot配置logback.xml 多環(huán)境的操作步驟

    最近在研究springboot的日志,所以記錄一下,做一下總結(jié),今天重點(diǎn)給大家介紹SpringBoot配置logback.xml 多環(huán)境的操作步驟,要實(shí)現(xiàn)多環(huán)境的配置,主要是依賴于springboot的application.yml文件去實(shí)現(xiàn),感興趣的朋友跟隨小編一起看看吧
    2021-05-05
  • Spring?Boot?多數(shù)據(jù)源處理事務(wù)的思路詳解

    Spring?Boot?多數(shù)據(jù)源處理事務(wù)的思路詳解

    這篇文章主要介紹了Spring?Boot?多數(shù)據(jù)源如何處理事務(wù),本文單純就是技術(shù)探討,要從實(shí)際應(yīng)用中來(lái)說(shuō)的話,我并不建議這樣去玩分布式事務(wù)、也不建議這樣去玩多數(shù)據(jù)源,畢竟分布式事務(wù)主要還是用在微服務(wù)場(chǎng)景下,對(duì)Spring?Boot?多數(shù)據(jù)源事務(wù)相關(guān)知識(shí)感興趣的朋友參考下本文
    2022-06-06
  • 總結(jié)Java對(duì)象被序列化的兩種方法

    總結(jié)Java對(duì)象被序列化的兩種方法

    今天給大家?guī)?lái)的是關(guān)于Java的相關(guān)知識(shí),文章圍繞著Java對(duì)象被序列化的兩種方法展開(kāi),文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06
  • 如何在Java中判斷兩個(gè)Long類型是否相等

    如何在Java中判斷兩個(gè)Long類型是否相等

    這篇文章主要介紹了如何在Java中判斷兩個(gè)Long類型是否相等,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的?參考價(jià)值,需要的小伙伴可以參考一下
    2022-09-09
  • Java RandomAccessFile基本文件操作示例

    Java RandomAccessFile基本文件操作示例

    這篇文章主要介紹了Java RandomAccessFile基本文件操作,結(jié)合實(shí)例形式分析了Java基于RandomAccessFile實(shí)現(xiàn)文件讀寫及文件隨機(jī)訪問(wèn)相關(guān)操作技巧,需要的朋友可以參考下
    2019-09-09
  • Mybatis中通過(guò)generator生成mapper、Dao、mapper.xml的方法

    Mybatis中通過(guò)generator生成mapper、Dao、mapper.xml的方法

    這篇文章主要介紹了Mybatis中通過(guò)generator生成mapper、Dao、mapper.xml的方法,需要的朋友可以參考下
    2017-01-01
  • 解決JD-GUI for mac big sur打不開(kāi)問(wèn)題

    解決JD-GUI for mac big sur打不開(kāi)問(wèn)題

    這篇文章主要介紹了解決JD-GUI for mac big sur打不開(kāi)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • Java與C++分別用遞歸實(shí)現(xiàn)漢諾塔詳解

    Java與C++分別用遞歸實(shí)現(xiàn)漢諾塔詳解

    漢諾塔問(wèn)題是一個(gè)經(jīng)典的問(wèn)題。漢諾塔(Hanoi Tower),又稱河內(nèi)塔,源于印度一個(gè)古老傳說(shuō)。本文將用Java與C++分別實(shí)現(xiàn),感興趣的可以學(xué)習(xí)一下
    2022-05-05
  • Spring Boot 如何使用Liquibase 進(jìn)行數(shù)據(jù)庫(kù)遷移(操作方法)

    Spring Boot 如何使用Liquibase 進(jìn)行數(shù)據(jù)庫(kù)遷移(操作方法)

    在Spring Boot應(yīng)用程序中使用Liquibase進(jìn)行數(shù)據(jù)庫(kù)遷移是一種強(qiáng)大的方式來(lái)管理數(shù)據(jù)庫(kù)模式的變化,本文重點(diǎn)講解如何在Spring Boot應(yīng)用程序中使用Liquibase進(jìn)行數(shù)據(jù)庫(kù)遷移,從而更好地管理數(shù)據(jù)庫(kù)模式的變化,感興趣的朋友跟隨小編一起看看吧
    2023-09-09

最新評(píng)論