SpringSecurity-ユーザー認証

2つの重要なインターフェース

  1. UserDetailsS​​erviceインターフェース
    1. データベースのユーザー名とパスワードを照会する
    2. UsernamePasswordAuthenticationFilterを継承するクラスを作成し、3つのメソッドを書き直します
    3. UserDetailsS​​erviceを実装するクラスを作成し、データベースクエリプロセスを記述して、セキュリティフレームワークによって提供されるオブジェクトであるUserオブジェクトを返します。
  2. PasswordEncodeインターフェース
    1. Userオブジェクトでパスワード暗号化を返すために使用されるデータ暗号化インターフェース

ログインユーザー名とパスワードを設定する

  1. 構成ファイル経由
spring.security.user.name=fy
spring.security.user.password=fy123
  1. 構成クラスを介して
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode("123");
        auth.inMemoryAuthentication().withUser("fyun").password(password).roles("admin");
    }
    @Bean
    PasswordEncoder passwordEncoder(){
    
    
        return new BCryptPasswordEncoder();
    }
}
  1. カスタム書き込み実装クラス
    1. 構成クラスを作成し、使用するUserDetailsS​​ervice実装クラスを設定します
    @Configuration
     public class MySecurityConfig extends WebSecurityConfigurerAdapter {
          
          
    
         @Autowired
         private UserDetailsService userDetailsService;
         @Override
         protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          
          
             auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
         }
         @Bean
         PasswordEncoder passwordEncoder(){
          
          
             return new BCryptPasswordEncoder();
         }
     }
    
    1. 実装クラスを記述し、Userオブジェクトを返します。Userオブジェクトには、ユーザー名、パスワード、および操作権限があります。
    @Service("userDetailsService")
    public class MyUserDetailsService implements UserDetailsService {
          
          
        @Override
        public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
          
          
            List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
            return new User("may",new BCryptPasswordEncoder().encode("my123"),role);
        }
    }
    

データベースにクエリを実行して、ユーザー認証を完了します

MybatisPlusを統合してデータベース操作を完了します

  1. 関連する依存関係を導入する
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.4.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
  1. データベースとデータテーブルを作成する
CREATE TABLE USER(
id INTEGER AUTO_INCREMENT,
username VARCHAR(225) ,
PASSWORD VARCHAR(225),
PRIMARY KEY (id)
);
  1. ユーザーエンティティクラスの作成
@Data
public class User {
    
    
    private Integer id;
    private String username;
    private String password;
}
  1. MybatisPlusを統合する
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
  1. UserMapperインターフェースを作成する
@Repository
public interface UserMapper extends BaseMapper<User> {
    
    
}
  1. 書く
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    
    

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    
    
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = userMapper.selectOne(wrapper);
        if (user == null){
    
    
            throw new UsernameNotFoundException("用户名不存在!");
        }
        List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        return new org.springframework.security.core.userdetails.User(user.getUsername(),new BCryptPasswordEncoder().encode(user.getPassword()),role);
    }
}
  1. データソースを構成する
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://10.138.236.45/security?serverTimezone=GMT%2B8

カスタムログインページ

  1. 構成クラスのconfigureメソッドをオーバーライドします
@Override
protected void configure(HttpSecurity http) throws Exception {
    
    
    http.formLogin()    //自定义自己编写的登录页面
            .loginPage("/login.html")   //登录页面设置
            .loginProcessingUrl("/user/login")  //登录访问路径
            .defaultSuccessUrl("/test/index").permitAll()   //登录成功之后的跳转路径
            .and().authorizeRequests()
            .antMatchers("/","/test/hello","/user/login").permitAll()   //设置哪些路径可以直接访问
            .anyRequest().authenticated()
            .and().csrf().disable();    //关闭csrf防护
}
  1. ログインページを編集します
    。ユーザー名とパスワードのname属性は、「username」と「password」である必要があります。
<form action="/user/login" method="post">
    用户名:<input type="text" name="username">
    <br>
    密码:<input type="text" name="password">
    <br>
    <input type="submit" value="login">
</form>

おすすめ

転載: blog.csdn.net/qq_40857365/article/details/112857254