认证指定URL地址

This commit is contained in:
bunny 2025-07-10 21:28:45 +08:00
parent 7e23ca1c55
commit 344057b20f
5 changed files with 113 additions and 8 deletions

View File

@ -21,8 +21,7 @@
<module>official</module>
<module>step-1</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source>
@ -40,11 +39,11 @@
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>

View File

@ -0,0 +1,103 @@
# 入门案例
## SpringSecurity6基本使用
添加项目依赖
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
创建一个类,加上下面两个注解即可`@EnableWebSecurity`,`@Configuration`
```java
@EnableWebSecurity
@Configuration
public class SecurityWebConfiguration {
}
```
## 自定义登录页
> [!IMPORTANT]
>
> 使用自定义页面时候需要在控制器中指定当前跳转的地址否则Security无法知道你要去往那个页面即使写上了URL也无法跳转。
在下面示例中定义了自定义登录页,当然也可以定义错误页、退出页等等。
### 开启和禁用
如果需要使用默认的选项可以使用`.formLogin(Customizer.withDefaults())`即可。
如果需要禁用登录页`.formLogin(AbstractHttpConfigurer::disable)`。
### 需要认证指定URL地址
#### 普通认证拦截方式
需要认证URL地址可以像下面这样写。
```java
String[] permitAllUrls = {
"/", "/doc.html/**",
"/webjars/**", "/images/**", ".well-known/**", "favicon.ico", "/error/**",
"/v3/api-docs/**"
};
http.authorizeHttpRequests(authorizeRequests ->
// 访问路径为 /api/** 时需要进行认证
authorizeRequests
.requestMatchers("/api/**").authenticated()
.requestMatchers(permitAllUrls).permitAll()
)
```
### 完整示例
```java
@EnableMethodSecurity
@EnableWebSecurity
@Configuration
public class SecurityWebConfiguration {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
String[] permitAllUrls = {
"/", "/doc.html/**",
"/webjars/**", "/images/**", ".well-known/**", "favicon.ico", "/error/**",
"/v3/api-docs/**"
};
http.authorizeHttpRequests(authorizeRequests ->
// 访问路径为 /api/** 时需要进行认证
authorizeRequests
.requestMatchers("/api/**").authenticated()
.requestMatchers(permitAllUrls).permitAll()
)
.formLogin(loginPage -> loginPage
// 自定义登录页路径
.loginPage("/login-page")
// 处理登录的URL默认就是/login
.loginProcessingUrl("/login")
// 登录成功跳转
.defaultSuccessUrl("/")
// 登录失败跳转
.failureUrl("/login-page?error=true")
.permitAll()
)
// 使用默认的登录
// .formLogin(Customizer.withDefaults())
// 禁用表单登录
// .formLogin(AbstractHttpConfigurer::disable)
.logout(logout -> logout
.logoutSuccessUrl("/login-page?logout=true")
.permitAll()
);
return http.build();
}
}
```

View File

@ -25,11 +25,12 @@ public class SecurityConfiguration {
String generatedPassword = passwordEncoder.encode("123456");
// 创建用户
UserDetails userDetails1 = User.withUsername("bunny").password(generatedPassword).roles("USER").build();
UserDetails userDetails1 = User.withUsername("bunny").password(generatedPassword).roles("USER").authorities("read").build();
UserDetails userDetails2 = User.withUsername("rabbit").password(generatedPassword).roles("USER").build();
UserDetails userDetails3 = User.withUsername("admin").password(generatedPassword).roles("ADMIN").authorities("all").build();
// 返回内存中的用户
return new InMemoryUserDetailsManager(userDetails1, userDetails2);
return new InMemoryUserDetailsManager(userDetails1, userDetails2, userDetails3);
}
/**
@ -47,7 +48,7 @@ public class SecurityConfiguration {
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
// 自定义实现密码加密器
// 自定义实现密码加密器如果使用自定义不用使用 Bean注入
// return new MD5PasswordEncoder();
}
}

View File

@ -39,6 +39,8 @@ public class SecurityWebConfiguration {
)
// 使用默认的登录
// .formLogin(Customizer.withDefaults())
// 禁用表单登录
// .formLogin(AbstractHttpConfigurer::disable)
.logout(logout -> logout
.logoutSuccessUrl("/login-page?logout=true")
.permitAll()

View File

@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="zh-cn" xmlns:th="http://www.thymeleaf.org">
<html lang="zh_CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">