Spring Security入门案例

一、spring security 简介

Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它是用于保护基于Spring的应用程序的实际标准。

Spring Security是一个框架,致力于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Spring Security的真正强大之处在于可以轻松扩展以满足自定义要求

巴拉巴拉…(详情看官方文档

二、入门案例(demo)

首先创建SpringBoot项目,核心依赖

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

编写一个controller(我这里写的是TestController)

@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

}

接着启动项目,注意看控制台
在这里插入图片描述
这里会默认生成一个登录密码,如果我们未做任何配置,security会在启动时自动生成一个随机密码。
然后打开浏览器,访问 http://localhost:8080/test/hello

在这里插入图片描述
如果出现这个登录界面,说明security已经起作用了,这里security默认用户名为 user,密码去控制台查看。

在这里插入图片描述
登录成功后显示如下
在这里插入图片描述
到这里demo案例就OK了,接着使用自定义的方式,修改登录密码。

三、自定义用户名和密码

3.1、在application.yml中修改

server:
  port: 8080
  
spring:
  security:
    user:
      name: admin #用户名
      password: 1234 #密码

3.2、编写配置类修改

主要继承 **WebSecurityConfigurerAdapter**类,重写 configure()方法

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        //加密
        String encode = bCryptPasswordEncoder.encode("1234");
        auth.inMemoryAuthentication().withUser("admin").password(encode).roles("admin");
    }

    /**
     * 密码加密
     *
     * @return BCryptPasswordEncoder
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

3.3、自定义实现类(常用)

前面两个都是单用户,将用户名和密码存入内存中,实际操作中认证都是需要操作数据库的,从数据库中获取用户信息(权限列表等)
需要我们自己去是实现 UserDetailsService接口

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//        //加密
//        String encode = bCryptPasswordEncoder.encode("1234");
//        auth.inMemoryAuthentication().withUser("admin").password(encode).roles("admin");
//    }

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    	//使用自定义UserDetailsService实现
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
    
    /**
     * 密码加密
     *
     * @return BCryptPasswordEncoder
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //从数据库获取用户信息 mybatisPlus
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", s);
        Users users = userMapper.selectOne(queryWrapper);
        if (users == null) {
            throw new UsernameNotFoundException("用户不存在!");
        }
        List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        return new User(users.getUsername(), new BCryptPasswordEncoder().encode(users.getPassword()), role);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值