SpringSecurity入门

本文介绍了如何在Spring Boot项目中集成Spring Security,包括添加依赖、配置用户验证流程,以及通过MyUserDetailsService从数据库查询用户信息进行登录验证。适合初学者了解Spring Security的基础用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringSecurity入门

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
        <relativePath/>
    </parent>

引入依赖:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

写一个测试:

DemoController:

@RestController
@RequestMapping("/demo")
public class DemoController {

    @GetMapping("demo")
    public String demo(){
        return "demo";
    }

启动项目并访问。

image-20221022153830695

默认:user

密码:控制台随机生成

image-20221022153919241

登录后

image-20221022154045767

基本原理:SpringSecurity本质是一个过滤器链

简单使用:

SecurityConfig:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

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

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

MyUserDetailsService:

public class MyUserDetailsService implements UserDetailsService {

    @Resource
    private MyUserService myUserService;

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

        MyUser one = myUserService.lambdaQuery().eq(MyUser::getUserName, s).one();
        if(ObjectUtil.isNull(one)){
            throw new UsernameNotFoundException("用户不存在!");
        }
        List<GrantedAuthority> oath= AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        //从数据返回对象,得到用户名和密码
        return new User(one.getUserName(),new BCryptPasswordEncoder().encode(one.getPassword()),oath);
    }
}

即可通过查询数据库进行登录验证。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值