HelloWorld
依赖
<!--不知道为什么必须加,不加程序直接报Process finished with exit code 0后程序关闭关闭-->
<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>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
启动项目
默认路径http://localhost:8080/
,启动后如下图。
Using generated security password: 9a7334f2-e4a9-4987-892e-ebfa605a9c89
什么都不配置security会自动设置一个用户名为user,密码上面字符串的用户。虽然界面什么的有点丑,但是只需要引入两个security有关依赖,要什么自行车。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-soq8r4UK-1623204632196)(E:\马士兵\spring\springsecurity\springsecurity\blog\img\01_02.png)]
自定义用户名密码
方法一、配置文件
spring.security.user.name=123
spring.security.user.password=123
方法二、类定义
@Configuration
@EnableWebSecurity
public class MyConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//依照xml的写法定义的配置
auth
.inMemoryAuthentication()
.withUser("111")
.password("111")
.roles("admin")
.and()
//可定义多个用户 使用and返回上一级
.withUser("222")
.password("222")
.roles("user");
}
//密码加密类型
//NoOpPasswordEncoder 明文密码已经被移除,NoOpPasswordEncoder 只能存在于 demo 中
@Bean
PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
方法三、自定义userDetailsService
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public UserDetailsService userDetailsService() {
//直接写在内存之中,可以写入到各种数据库中,进行业务逻辑的验证
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
User user = new User("111", new BCryptPasswordEncoder().encode("111")
, true, true, true, true
, Collections.singletonList(new SimpleGrantedAuthority("admin")));
manager.createUser(user);
manager.createUser(User.withUsername("222").password(new BCryptPasswordEncoder().encode("222")).roles("user").build());
return manager;
}
以上三种方法会进行覆盖,2>3>1,第二种方法会覆盖调另外两种。