目录
一:创建一个springboot项目
- 启动类
public class SecondEurekaClientApplication { public static void main(String[] args) { SpringApplication.run(SecondEurekaClientApplication.class, args); } }
- controller
@RestController public class MainController { @GetMapping("/123") public Object login(){ return "hello world"; } }
- 启动访问(正常)
二:引入spring security
implementation 'org.springframework.boot:spring-boot-starter-security'
-
启动项目–观察控制台
会看到spring security自动生成的密码(uuid) -
访问网页
会看到spring security使用了默认登录页面,默认用户user,密码就是上面的,输入用户密码成功访问
注意:引入spring security依赖时,会自动启动spring security
禁用:@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })
三:自定义WebSecurityConfig
1. 创建WebSecurityConfig
/* 开启web security配置 这是一个组合注解 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {}
2. 重写configure(HttpSecurity http)
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() /* 需要授权的请求 */
.anyRequest().authenticated() /* 对任何一个请求,都需要认证 */
.and() /* 完成上一个配置,进行下一步配置 */
.httpBasic(); /* 开启httpBasic登录 */
}
3. 启动项目,访问页面
会弹出一个登录窗口,默认用户user,密码,自动生成在控制台
4. 自定义登录用户和密码
- 配置AuthenticationManager
两种方式(区别 configureGlobal可以跨多个WebSecurityConfigurerAdapter;configure只能只能作用一个)
①:重写configure(AuthenticationManagerBuilder auth)
②:注入 configureGlobal(AuthenticationManagerBuilder auth)@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { super.configure(auth); }
@Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {}
- 基于inMemoryAuthentication的模式创建用户
/** * spring5.0之后,spring security必须设置加密方法否则会报 * There is no PasswordEncoder mapped for the id "null" * @return 加密 */ @Bean public BCryptPasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(4); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(passwordEncoder()) .withUser("admin").password(passwordEncoder().encode("admin")).roles("USER"); }
最后启动应用,输入admin,admin成功通过验证
5. 自定义登录页面和退出页面
- 配置mvc
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/home").setViewName("home"); registry.addViewController("/main").setViewName("main"); registry.addViewController("/").setViewName("home"); registry.addViewController("/hello").setViewName("hello"); registry.addViewController("/login").setViewName("login"); } }
- 配置HttpSecurity
示例:@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() /* 需要授权的请求 */ .antMatchers("/login","/home").permitAll() /* 过滤不需要认证的路径 */ .anyRequest().authenticated() /* 对任何一个请求,都需要认证 */ .and() /* 完成上一个配置,进行下一步配置 */ //.httpBasic(); .formLogin() /* 配置表单登录 */ .loginPage("/login") /* 设置登录页面 */ .and() .logout() /* 登出 */ .logoutSuccessUrl("/home"); /* 设置退出页面 */ }
6. 项目地址
Spring Security最简单的搭建
下面的是我的公众号二维码图片,欢迎关注。