<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>
写一个测试:
@RestController @RequestMapping("/demo") public class DemoController { @GetMapping("demo") public String demo(){ return "demo"; }
启动项目并访问。
默认:user
密码:控制台随机生成
登录后
基本原理: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::getStudentName, 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); } }
即可通过查询数据库进行登录验证。
标签: 开发日记