一、准备
1、创建SpringBoot项目
2、pom.xml配置依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
3、创建一个controller
@RestController
public class LoginController {
@RequestMapping("/hello")
public String hello(){
return "Login Success!";
}
}
4、启动项目
访问你的controllern会出现以下界面
输入用户名: user
输入密码为你启动时控制台打印的password:
就可以访问了!
二、如何更改登录的用户和密码
- 配置文件
- 配置类
- 自定义编制实现类
1、配置文件:
配置yml文件:
server:
port: 8111
spring:
security:
user:
name: jiawen
password: 123
2、配置类:
新建一个类继承WebSecurityConfigurerAdapter
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String pass = passwordEncoder.encode("123");
auth.inMemoryAuthentication().withUser("admin").password(pass).roles("admin");
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
3、自定义实现类:
1、新建一个配置类继承WebSecurityConfigurerAdapter
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
2、实现UserDetailsService重写方法
@Service
public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
List<GrantedAuthority> roles = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
return new User("mary",new BCryptPasswordEncoder().encode("123"),roles);
}
}
3、启动项目访问
输入用户名: mary
输入密码:123
就可以访问了!