- <dependencies>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- dependency>
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-securityartifactId>
- dependency>
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- dependency>
- <dependency>
- <groupId>com.baomidougroupId>
- <artifactId>mybatis-plus-boot-starterartifactId>
- <version>3.5.1version>
- dependency>
- dependencies>
配置数据库连接 yml
- server:
- port: 8080
- spring:
- datasource:
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql://localhost:3306/easymybatis?serverTimezone=GMT%2B8
- username: root
- password: 123456
数据库结构:
- @Service
- public class MyUserDetailService implements UserDetailsService {
- @Autowired
- private UserMapper userMapper;
- @Override
- public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
- QueryWrapper
queryWrapper=new QueryWrapper<>(); - queryWrapper.eq("name",s);
- MemberUser memberUser = userMapper.selectOne(queryWrapper);
- if (memberUser==null){
- throw new UsernameNotFoundException("验证失败");
- }
- List
auths= AuthorityUtils.commaSeparatedStringToAuthorityList("role"); - return new User(memberUser.getName(),new BCryptPasswordEncoder().encode(memberUser.getPassword()),auths);
- }
- }
- @SpringBootConfiguration
- public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
- @Autowired
- private MyUserDetailService userDetailService;
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- //super.configure(auth);
- //用DetailService 方式鉴权
- auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
- }
- //老版不分离自定义登录方案
- /* @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.formLogin()
- .loginPage("index.html") //登录页面
- .successForwardUrl("success.html") //登录成功跳转
- .loginProcessingUrl("/user/login").permitAll() //请求服务器路径
- .and().authorizeRequests()
- .antMatchers("/","index/html").permitAll() //不需要认证
- .antMatchers("/test").hasAnyAuthority("role") //拥有权限才能访问
- .anyRequest().authenticated()
- .and().csrf().disable();
- }
- */
- //加密措施
- @Bean
- PasswordEncoder passwordEncoder(){
- return new BCryptPasswordEncoder();
- }
- }
- @RestController
- @RequestMapping("test")
- public class TestController {
- @GetMapping("hello")
- public String test(){
- return "hello security";
- }
- }