spring security搭建使用
引用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
创建controller
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping
public String getUsers() {
return "Hello Spring Security";
}
}
运行程序,直接访问http://localhost:8080/user
弹出用户输出账号密码程序。
系统默认生成账号user,查看运行日志,发现默认生成一个密码
输入之后就登录了系统,再次访问地址就可以看到"Hello Spring Security"
这个登录框是SpringSecurity是框架自己提供的,被称为httpBasicLogin
添加自定义用户密码
继承UserDetailsService
public class MyUserService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
log.info("用户名:{}",username);
//使用默认加密密码
BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
String pwd = bc.encode("111111");
log.info("密码:{}",pwd);
//封装用户信息
User user = new User(username,pwd,
AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
return user;
}
}
配置文件类
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserService myUserService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.and()
.authorizeRequests()
.anyRequest()
.authenticated();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserService)
.passwordEncoder(passwordEncoder());
}
@Bean
protected PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
再次运行http://localhost:8080/user,使用密码111111即可登录成功