spring security 入门

基本环境搭建

1、创建spring boot项目,导入依赖

<dependencies>
        <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.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2、创建测试controller

@RestController
@RequestMapping("test")
public class TestController {
    @RequestMapping("hello")
    public String hello(){
        return "hello";
    }
}

3、自动创建启动类

@SpringBootApplication
public class SpringSecurityApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringSecurityApplication.class, args);
    }

}

4、application.properties文件设置端口

server.port=8081

5、启动
spring security 入门
6、网页测试http://localhost:8081/test/hello
spring security 入门
输出user和控制台的密码
spring security 入门

通过配置文件为Spring Security设定用户名和密码

spring.security.user.name=zhangsan
spring.security.user.password=123456

这时只有配置文件的账号密码可用

通过内存设置账号密码

@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("lucy").password(password).roles("admin");
        auth.inMemoryAuthentication().withUser("jack").password(password).roles("user");
    }

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

通过数据库进行验证

1、添加依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

2、配置数据库

# 数据源
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://47.94.143.161:3306/SpringSecurity?characterEncoding=utf8&useUnicode=true&useSSL=false
spring.datasource.username=spring_security
spring.datasource.password=@Springsecurity1
#jpa配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

spring security 入门

3、mysql表结构

CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `role` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

4、model,repository,service
这里是使用spring data JPA技术,没有使用mybatis
model

@Entity
@Table(name = "user")
@Setter
@Getter
@ToString
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String username;
    private String password;
    private String role;
}

repository

@Repository
public interface UserRepository extends JpaRepository<User,Long> {
    User findByUsername(String username);
}

sevice

@Service
public class UserService<T extends User> implements UserDetailsService {
    @Resource
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            User user = userRepository.findByUsername(username);
            if(null==user){
                throw new UsernameNotFoundException("用户不存在");
            }
            System.out.println("查找用户"+user);
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            if(!StringUtils.isNullOrEmpty(user.getRole())){
                String[] roles = user.getRole().split(",");
                for (String role : roles) {
                    authorities.add(new SimpleGrantedAuthority(role.trim()));
                }
            }
            //这里可以对密码加密,相应的需要在认证阶段对密码进行解密
            return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

5、config设置

@Configuration
public class SecurityConfig2 extends WebSecurityConfigurerAdapter {
    @Resource
    UserService userService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();// 使用非加密算法保持密码
        //return new BCryptPasswordEncoder();
    }
}

6、controller测试

@RestController
@RequestMapping("test")
@Secured("ROLE_USER")  //只有ROLE_USER角色权限才能访问
public class TestController {
    @RequestMapping("hello")
    public String hello(){
        return "hello";
    }
}

这里使用注解在进行角色权限限定,需要在启动类上开启权限注解功能,

@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SpringSecurityApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringSecurityApplication.class, args);
    }
}

所以登录时,只有user用户拥有ROLE_USER角色,也只有user才能访问test/hello

上一篇:《华为HCIE安全认证》学习笔记 | 虚拟化技术(二)


下一篇:SAP Commerce Cloud portal 的 deployment