Spring Security 入门

本文详细介绍了如何在Spring Boot应用中启用和配置Spring Security,包括添加依赖、基于配置文件和内存的用户存储、自定义用户认证,以及权限控制如自定义登录页面、请求路径权限、403错误页面和注解授权。此外,还涵盖了登录保持、退出登录和CSRF防护等关键点。
摘要由CSDN通过智能技术生成

https://top234.top/blog/21041107.html

1 启用Spring Security

1.1 添加spring-boot-starter-security依赖

<!-- spring security 依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2 配置Spring Security

2.1 基于配置文件的用户存储

# 在配置文件中设置用户名密码
spring: 
  security:
    user:
      name: lisi
      password: lisi

2.2 基于内存的用户存储

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   

        // 设置用户名密码到内存中
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zs").password(new BCryptPasswordEncoder()
                .encode("ls"))
                .roles("admin");
    }
}

2.3 自定义用户认证

  1. 创建配置类,指定UserDetailsService接口实现类实例,并注入用户密码的转码方式
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   
    @Autowired
    private UserDetailsService myUserDetailsService;
    /**
     * 配置用户密码转码器
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
   
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   
    	//配置自定义UserDetailsService接口实现类对象并将用户密码转码器注入到用户详情服务中
   		auth.userDetailsService(myUserDetailsService)
            .passwordEncoder(passwordEncoder());
    }
}
  1. 编写UserDetailsService接口实现类,实现loadUserByUsername(String username)方法,自定义用户数据查询方式
package top.top234.springsecurity.service;

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
public class MyUserDetailsService implements UserDetailsService {
   

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
   

        List<GrantedAuthority> role = AuthorityUtils.
            commaSeparatedStringToAuthorityList("role");

        return new User("lisi", new BCryptPasswordEncoder().encode("lisi"), role);
    }
}

2.4 自定义用户认证并结合数据库

  1. 实体类及数据表
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
   
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String username;
    private String password;
    private String role;
}
  1. dao
package top.top234.springsecurity.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import top.top234.springsecurity.entity.User;

public interface UserRepository extends JpaRepository<User,Integer> {
   
    User findByUsername(String username);
}
  1. 创建配置类,设置使用哪个UserDetailsService实现类及密码的加密方式
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   
    @Autowired
    private UserDetailsService myUserDetailsService;
    /**
     * 配置用户密码转码器
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
   
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   
   		auth
            .userDetailsService(myUserDetailsService)//配置自定义UserDetailsService接口实现类实例
            .passwordEncoder(passwordEncoder());//将用户密码转码器注入到用户详情服务中
    }
}
  1. 编写UserDetailsService接口实现类,实现loadUserByUsername(String username)方法,自定义用户数据查询方式
@Service
public class MyUserDetailsService implements UserDetailsService {
   
    @Autowired
    private UserRepository userRepository;
    
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
   
		//自定义用户数据查询规则
        User user = userRepository.findByUsername(s);
        
        //用户名不存在时抛出org.springframework.security.core.userdetails.UsernameNotFoundException异常
        if (user==null){
   
            throw new UsernameNotFoundException("用户名不存在");
        }

        //将用户role字段转为集合,commaSeparatedStringToAuthorityList()方法参数为字符串,会将字符串参数按照逗号分割为权限集合
        List<GrantedAuthority> role = AuthorityUtils
            .commaSeparatedStringToAuthorityList(user.getRole());
        
        //方法返回UserDetails接口的实现类对象,UserDetails对象包括有用户名 密码 及 操作权限集合
        return new org.springframework.security.core.userdetails.User(
            user.getUsername(), user.getPassword(), role);
    }
}

3 权限控制 - 保护web请求

3.1 使用自定义登录页面

  1. 修改SecurityConfig配置类,配置自定义登录页面的路径
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   
    @Autowired
    private UserDetailsService myUserDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   
        auth.userDetailsService(myUserDetailsService)
            .passwordEncoder(new BCryptPasswordEncoder());
    }

    /**
     * 自定义登录页面配置及设置请求权限
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
   
        http.formLogin()
                .loginPage("/login")//自定义的登录页面
                .loginProcessingUrl("/user/login")//登录访问路径(登录页表单的提交路径),随便填写,由springboot实现
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值