欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringSecurity默认数据库模型的认证与授权Demo

程序员文章站 2024-03-19 15:02:34
...
package com.zcw.demospringsecurity.demo3;


import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.JdbcUserDetailsManager;


/**
 * @ClassName : MyJdbcUserDetailsManager
 * @Description : SpringSecurity默认数据库模型的认证与授权Demo
 * @Author : Zhaocunwei
 * @Date: 2020-04-10 17:36
 */
public class MyJdbcUserDetailsManager {
//    <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jdbc -->
//<dependency>
//    <groupId>org.apache.tomcat</groupId>
//    <artifactId>tomcat-jdbc</artifactId>
//    <version>9.0.31</version>
//</dependency>
    @Autowired
    private DataSource dataSource;

    @Bean
    public UserDetailsService userDetailsService(){
        JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager();
        jdbcUserDetailsManager.setDataSource(dataSource);
        if(!jdbcUserDetailsManager.userExists("haha")){
            jdbcUserDetailsManager.createUser(User.withUsername("haha").password("1234567890").roles("USER").build());
        }
        if(!jdbcUserDetailsManager.userExists("admin12312312")){
            jdbcUserDetailsManager.createUser(User.withUsername("admin12312312").password("12000000").roles("USER","ADMIN").build());
        }
        return jdbcUserDetailsManager;
    }
    /***
     * <h1>createUser函数实际上执行了下面的sql语句</h1>
     * insert into users(username,password,enabled) values(?,?,?)
     */
}
相关标签: 安全框架