spring-security
前言
一、新建web项目,引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
二、账号密码登录
1.方式一配置文件,在yml中配置(实际中不实用)
server:
port: 20074
spring:
application:
name: yimall-spring
security:
user:
name: clientAdmin
password: 123456
2.方式二 代码中配置 继承类WebSecurityConfigurerAdapter (实际中不实用)
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
String strPassword = bCryptPasswordEncoder.encode("123456");
auth.inMemoryAuthentication().withUser("root").password(strPassword).roles("admin");
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
3.方式三数据库查询(实际中常用)
步骤一:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private UserDetailsService userDetailsServiceImpl;
/**
* 指定UserDetailsService 验证
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsServiceImpl).passwordEncoder(passwordEncoder);
}
/**
* 密码验证器
* @return
*/
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
步骤二:模拟查询
@Configuration
public class UserDetailsServiceImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Collection<GrantedAuthority> authorities = new ArrayList<>();
UserDetails userDetails = User.withUsername("admin").password(new BCryptPasswordEncoder().encode("123456")).authorities(authorities).build();
return userDetails ;
}
}
连接mybatis-puls 查询:
@Configuration
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
System.out.println("----------------->" + s);
User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserName, s));
if (Objects.isNull(user)) {
throw new RuntimeException("登录账号不存在");
}
return new LoginUser(user);
}
}
三、常用注解
(一)@Secured 基于角色的控制
(二)@PreAuthorize("@pms.hasPermission(‘permission:role:edit’)") 进入方法前验证权限
@SpringBootApplication
@MapperScan("com.veryreader.d2p.**.mapper")
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class ApiServerApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(ApiServerApplication.class, args);
}
}