SpringSecurity_連線mysql(初出茅廬)

yma16發表於2020-12-15

SpringSecurity

在這裡插入圖片描述

安裝依賴

mybatis-plus、lombok、springweb、Thymeleaf、springsecurity、

        <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>
<!--mybatis-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>
<!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
<!--lomok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

執行,預設使用者名稱user,檢視預設的密碼
在這裡插入圖片描述

建立成功
檢視localhost
在這裡插入圖片描述

Config

繼承 WebSecurityConfigurerAdapter

package com.yma16.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(password());//加密
    }
    @Bean
    PasswordEncoder password()
    {
        return new BCryptPasswordEncoder();//註解
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.formLogin().and().authorizeRequests().anyRequest().authenticated();//身份驗證
    }
}

配置檔案

  • 基於記憶體的使用者配置
  • 基於JDBC的使用者儲存
  • 以LDAP作為後端的使用者儲存
  • 自定義使用者詳情服務
properties檔案配置
server.port=2234
spring.security.user.name=yma16
spring.security.user.password=123456

在這裡插入圖片描述

繼承WebSecurityConfigureAdapter配置

重寫configure方法

package com.yma16.springsecurity;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);//繼承重寫
        //新增使用者
        auth.inMemoryAuthentication().withUser("yma16").password("123456").authorities("ROLE_USER").
                and().withUser("sxy").password("12345").authorities("ROLE_USER");
    }
}

基於jdbc的使用者儲存

在這裡插入圖片描述

連線mysql

properties配置檔案

server.port=1998
#spring.security.user.name=yma16
#spring.security.user.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springsecurity?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
entity(對應資料庫表)

在這裡插入圖片描述
users類

package com.yma16.entity;
import lombok.Data;//簡便生成get、set方法 lombok

@Data
public class Users {
    private Integer id;
    private String username,password;
}

mapper介面(增刪改查)

UsersMapper介面繼承BaseMapper

package com.yma16.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yma16.entity.Users;
import org.springframework.stereotype.Repository;

@Repository
public interface UsersMapper extends BaseMapper<Users> {//增刪改查

}

service(UserDetailsService)
package com.yma16.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yma16.entity.Users;
import com.yma16.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UsersMapper usersMapper;//  Reposotory
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
        //根據使用者名稱查詢
        QueryWrapper<Users> wrapper=new QueryWrapper();
        //where 語句 where usename=?
        wrapper.eq("username",username);
        Users users=usersMapper.selectOne(wrapper);
        if(users==null)
        {//沒有該使用者
            throw new UsernameNotFoundException("沒有該使用者!");//丟擲錯誤
        }

        List<GrantedAuthority> auths= AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPassword()),auths);//
//        return new User("yma16",new BCryptPasswordEncoder().encode("123456"),auths);
    }
}

執行

在這裡插入圖片描述
登入
在這裡插入圖片描述
ok,沒問題,下一步開始配置前端介面。

相關文章