1、引入依賴
spring-boot版本2.7.3,如未特殊說明版本默認使用此版本
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
2、撰寫controller并啟動springboot服務
@RestController
public class HelloController {
@GetMapping("/")
public String hello(){
return "hello SpringSecurity";
}
}
- 啟動

- 訪問http://localhost:8080/

- 登陸使用賬號:user,密碼:04e74f23-0e97-4ee9-957e-2004a2e60692

- SecurityProperties

3、自動配置SpringBootWebSecurityConfiguration
- SecurityFilterChainConfiguration

- WebSecurityConfigurerAdapter中有所有的Security相關的配置,只需要繼承重新對應屬性即可完成自定義
- 由于新版本的Security已經棄用WebSecurityConfigurerAdapter所以注冊SecurityFilterChain即可
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity.authorizeRequests()
.mvcMatchers("/index").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and().build();
}

4、默認登陸頁面DefaultLoginPageGeneratingFilter

4.1、SecurityFilterChainConfiguration默認實作的SecurityFilterChain
- 容器中沒有WebSecurityConfigurerAdapter型別的bean實體自動配置才會生效

4.2、UsernamePasswordAuthenticationFilter

4.3、attemptAuthentication方法

4.4、 ProviderManager的authenticate方法

4.5、 AuthenticationProvider實作AbstractUserDetailsAuthenticationProvider中的authenticate方法

4.6、 UserDetails實作類DaoAuthenticationProvider的retrieveUser方法

4.7、UserDetailsService實作類InMemoryUserDetailsManager的loadUserByUsername方法

4.8、 UserDetailsService

4.9、 UserDetailsServiceAutoConfiguration

- 容器中沒有:AuthenticationManager、AuthenticationProvider、UserDetailsService、AuthenticationManagerResolver這4個bean實體才會加載InMemoryUserDetailsManager


4.10、 SecurityProperties



- 可以通過spring.security.user.password=123456自定義密碼
5、 自定義認證
5.1、由于新版本的Security已經棄用WebSecurityConfigurerAdapter所以注冊SecurityFilterChain即可
github示例
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity.authorizeRequests()
.mvcMatchers("/index").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and().build();
}
5.2、 自定義登陸頁面
5.2.1、html
- 使用UsernamePasswordAuthenticationFilter用戶名和密碼欄位名必須是username和password,且必須是POST的方式提交

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form th:action="@{/doLogin}" method="post">
<p>用戶名:<label>
<input name="username" type="text"/>
</label></p>
<p>密碼:<label>
<input name="password" type="password"/>
</label></p>
<p>
<input type="submit">
</p>
</form>
</body>
</html>
5.2.2、SecurityFilterChain配置
@Configuration
public class WebSecurityConfigurer {
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
.mvcMatchers("/index").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin()
//自定義登陸頁面
.loginPage("/toLogin")
//自定義登陸頁面后必須指定處理登陸請求的url
.loginProcessingUrl("/doLogin")
.and()
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
5.2.3、 controller
@Controller
public class LoginController {
@RequestMapping("toLogin")
public String toLogin(){
return "login";
}
}
5.2.4、 自定義登陸使用的用戶名和密碼欄位名使用usernameParameter和passwordParameter
@Configuration
public class WebSecurityConfigurer {
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
.mvcMatchers("/index").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin()
//自定義登陸頁面
.loginPage("/toLogin")
//自定義登陸頁面后必須指定處理登陸請求的url
.loginProcessingUrl("/doLogin")
// 自定義接收用戶名的引數名為uname
.usernameParameter("uname")
// 自定義接收密碼的引數名為pwd
.passwordParameter("pwd")
.and()
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
}
- form表單中對應引數名也需要修改,用戶名為:uname,密碼為:pwd

5.3、 自定義認證成功后訪問的頁面
- successForwardUrl(轉發),必須使用POST請求,每次都會跳轉到指定請求
- defaultSuccessUrl(重定向),必須使用GET請求,不會每次都跳轉定義的頁面,默認會記錄認證攔截的請求,如果是攔截的受限資源會優先跳轉到之前被攔截的請求,需要每次都跳轉使用.defaultSuccessUrl("/test",true)即可

- 二選一
// 登陸認證成功后跳轉的頁面(轉發),必須使用POST請求
// .successForwardUrl("/test")
// 陸認證成功后跳轉的頁面(重定向),必須使用GET請求
.defaultSuccessUrl("/test",true)
5.4、 前后端分離處理方式

5.4.1、 實作AuthenticationSuccessHandler介面
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Map<String,Object> map = new HashMap<>();
map.put("msg", "登陸成功");
map.put("code", HttpStatus.OK);
map.put("authentication", authentication);
String s = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(s);
}
}
5.4.2、修改SecurityFilterChain配置
- 使用successHandler(new MyAuthenticationSuccessHandler())
@Configuration
public class WebSecurityConfigurer {
@Bean
@SuppressWarnings("all")
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
.mvcMatchers("/index").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin()
//自定義登陸頁面
.loginPage("/toLogin")
//自定義登陸頁面后必須指定處理登陸請求的url
.loginProcessingUrl("/doLogin")
// 自定義接收用戶名的引數名為uname
.usernameParameter("uname")
// 自定義接收密碼的引數名為pwd
.passwordParameter("pwd")
// 登陸認證成功后跳轉的頁面(轉發),必須使用POST請求
// .successForwardUrl("/test")
// 陸認證成功后跳轉的頁面(轉發),必須使用GET請求
// .defaultSuccessUrl("/test",true)
//不會每次都跳轉定義的頁面,默認會記錄認證攔截的請求,如果是攔截的受限資源會優先跳轉到之前被攔截的請求,需要每次都跳轉使defaultSuccessUrl("/test",true)
// .defaultSuccessUrl("/test")
// 前后端分離時代自定義認證成功處理
.successHandler(new MyAuthenticationSuccessHandler())
.and()
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
}
5.4.3、回傳資料

6、 認證失敗處理
- failureForwardUrl,轉發,請求必須是POST
- failureUrl,重定向,請求必須是GET
6.1、org.springframework.security.authentication.ProviderManager#authenticate

6.2、 org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter#doFilter(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)

6.3、 org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter#unsuccessfulAuthentication

6.4、 org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler#onAuthenticationFailure

6.5、 org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler#saveException

- 如果是轉發例外資訊存在request里面
- 如果是重定向例外資訊存在session里面,默認是重定向
- 引數名:SPRING_SECURITY_LAST_EXCEPTION
6.7、 前端取值展示
- 修改SecurityFilterChain配置
@Configuration
public class WebSecurityConfigurer {
@Bean
@SuppressWarnings("all")
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
.mvcMatchers("/index").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin()
//自定義登陸頁面
.loginPage("/toLogin")
//自定義登陸頁面后必須指定處理登陸請求的url
.loginProcessingUrl("/doLogin")
// 自定義接收用戶名的引數名為uname
.usernameParameter("uname")
// 自定義接收密碼的引數名為pwd
.passwordParameter("pwd")
// 登陸認證成功后跳轉的頁面(轉發),必須使用POST請求
// .successForwardUrl("/test")
// 陸認證成功后跳轉的頁面(轉發),必須使用GET請求
// .defaultSuccessUrl("/test",true)
//不會每次都跳轉定義的頁面,默認會記錄認證攔截的請求,如果是攔截的受限資源會優先跳轉到之前被攔截的請求,需要每次都跳轉使defaultSuccessUrl("/test",true)
// .defaultSuccessUrl("/test")
// 前后端分離時代自定義認證成功處理
.successHandler(new MyAuthenticationSuccessHandler())
// 認證失敗跳轉頁面,必須使用POST請求
.failureForwardUrl("/toLogin")
// 認證失敗跳轉頁面,,必須使用GET請求
// .failureUrl("/toLogin")
.and()
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
}
- html增加取值
<!-- 重定向錯誤資訊存在session中 -->
<p th:text="${session.SPRING_SECURITY_LAST_EXCEPTION}"></p>
<!-- 轉發錯誤資訊存在request中 -->
<p th:text="${SPRING_SECURITY_LAST_EXCEPTION}"></p>
6.8、 前后端分離處理方式

6.8.1、 實作AuthenticationFailureHandler介面
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
Map<String,Object> map = new HashMap<>();
map.put("msg", exception.getMessage());
map.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
String s = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(s);
}
}
6.8.2、修改SecurityFilterChain配置
- failureHandler
@Configuration
public class WebSecurityConfigurer {
@Bean
@SuppressWarnings("all")
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
.mvcMatchers("/index").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin()
//自定義登陸頁面
.loginPage("/toLogin")
//自定義登陸頁面后必須指定處理登陸請求的url
.loginProcessingUrl("/doLogin")
// 自定義接收用戶名的引數名為uname
.usernameParameter("uname")
// 自定義接收密碼的引數名為pwd
.passwordParameter("pwd")
// 登陸認證成功后跳轉的頁面(轉發),必須使用POST請求
// .successForwardUrl("/test")
// 陸認證成功后跳轉的頁面(轉發),必須使用GET請求
// .defaultSuccessUrl("/test",true)
//不會每次都跳轉定義的頁面,默認會記錄認證攔截的請求,如果是攔截的受限資源會優先跳轉到之前被攔截的請求,需要每次都跳轉使defaultSuccessUrl("/test",true)
// .defaultSuccessUrl("/test")
// 前后端分離時代自定義認證成功處理
.successHandler(new MyAuthenticationSuccessHandler())
// 認證失敗跳轉頁面,必須使用POST請求
// .failureForwardUrl("/toLogin")
// 認證失敗跳轉頁面,必須使用GET請求
// .failureUrl("/toLogin")
// 前后端分離時代自定義認證失敗處理
.failureHandler(new MyAuthenticationFailureHandler())
.and()
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
}
7、 注銷登錄
7.1、 默認方式
.logout()
// 指定注銷url,默認請求方式GET
.logoutUrl("/logout")
// 注銷成功后跳轉頁面
.logoutSuccessUrl("/toLogin")
@Configuration
public class WebSecurityConfigurer {
@Bean
@SuppressWarnings("all")
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
.mvcMatchers("/index").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin()
//自定義登陸頁面
.loginPage("/toLogin")
//自定義登陸頁面后必須指定處理登陸請求的url
.loginProcessingUrl("/doLogin")
// 自定義接收用戶名的引數名為uname
.usernameParameter("uname")
// 自定義接收密碼的引數名為pwd
.passwordParameter("pwd")
// 登陸認證成功后跳轉的頁面(轉發),必須使用POST請求
// .successForwardUrl("/test")
// 陸認證成功后跳轉的頁面(轉發),必須使用GET請求
// .defaultSuccessUrl("/test",true)
//不會每次都跳轉定義的頁面,默認會記錄認證攔截的請求,如果是攔截的受限資源會優先跳轉到之前被攔截的請求,需要每次都跳轉使defaultSuccessUrl("/test",true)
// .defaultSuccessUrl("/test")
// 前后端分離時代自定義認證成功處理
.successHandler(new MyAuthenticationSuccessHandler())
// 認證失敗跳轉頁面,必須使用POST請求
// .failureForwardUrl("/toLogin")
// 認證失敗跳轉頁面,必須使用GET請求
// .failureUrl("/toLogin")
// 前后端分離時代自定義認證失敗處理
.failureHandler(new MyAuthenticationFailureHandler())
.and()
// 注銷
.logout()
// 指定注銷url,默認請求方式GET
.logoutUrl("/logout")
// 銷毀session,默認為true
.invalidateHttpSession(true)
// 清除認證資訊,默認為true
.clearAuthentication(true)
// 注銷成功后跳轉頁面
.logoutSuccessUrl("/toLogin")
.and()
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
}
7.2、 自定義方式
// 注銷
.logout()
// 自定義注銷url
.logoutRequestMatcher(newOrRequestMatcher(
newAntPathRequestMatcher("/aa","GET"),
newAntPathRequestMatcher("/bb","POST")
))
// 注銷成功后跳轉頁面
.logoutSuccessUrl("/toLogin")
@Configuration
public class WebSecurityConfigurer {
@Bean
@SuppressWarnings("all")
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
.mvcMatchers("/index").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin()
//自定義登陸頁面
.loginPage("/toLogin")
//自定義登陸頁面后必須指定處理登陸請求的url
.loginProcessingUrl("/doLogin")
// 自定義接收用戶名的引數名為uname
.usernameParameter("uname")
// 自定義接收密碼的引數名為pwd
.passwordParameter("pwd")
// 登陸認證成功后跳轉的頁面(轉發),必須使用POST請求
// .successForwardUrl("/test")
// 陸認證成功后跳轉的頁面(轉發),必須使用GET請求
// .defaultSuccessUrl("/test",true)
//不會每次都跳轉定義的頁面,默認會記錄認證攔截的請求,如果是攔截的受限資源會優先跳轉到之前被攔截的請求,需要每次都跳轉使defaultSuccessUrl("/test",true)
// .defaultSuccessUrl("/test")
// 前后端分離時代自定義認證成功處理
.successHandler(new MyAuthenticationSuccessHandler())
// 認證失敗跳轉頁面,必須使用POST請求
// .failureForwardUrl("/toLogin")
// 認證失敗跳轉頁面,必須使用GET請求
// .failureUrl("/toLogin")
// 前后端分離時代自定義認證失敗處理
.failureHandler(new MyAuthenticationFailureHandler())
.and()
// 注銷
.logout()
// 指定注銷url,默認請求方式GET
// .logoutUrl("/logout")
.logoutRequestMatcher(new OrRequestMatcher(
new AntPathRequestMatcher("/aa","GET"),
new AntPathRequestMatcher("/bb","POST")
))
// 銷毀session,默認為true
.invalidateHttpSession(true)
// 清除認證資訊,默認為true
.clearAuthentication(true)
// 注銷成功后跳轉頁面
.logoutSuccessUrl("/toLogin")
.and()
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
}
7.3、 前后端分離

7.3.1、 實作LogoutSuccessHandler介面
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Map<String,Object> map = new HashMap<>();
map.put("msg", "注銷成功");
map.put("code", HttpStatus.OK.value());
map.put("authentication", authentication);
String s = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(s);
}
}
7.3.2、 修改SecurityFilterChain配置
- logoutSuccessHandler
@Configuration
public class WebSecurityConfigurer {
@Bean
@SuppressWarnings("all")
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
.mvcMatchers("/index").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin()
//自定義登陸頁面
.loginPage("/toLogin")
//自定義登陸頁面后必須指定處理登陸請求的url
.loginProcessingUrl("/doLogin")
// 自定義接收用戶名的引數名為uname
.usernameParameter("uname")
// 自定義接收密碼的引數名為pwd
.passwordParameter("pwd")
// 登陸認證成功后跳轉的頁面(轉發),必須使用POST請求
// .successForwardUrl("/test")
// 陸認證成功后跳轉的頁面(轉發),必須使用GET請求
// .defaultSuccessUrl("/test",true)
//不會每次都跳轉定義的頁面,默認會記錄認證攔截的請求,如果是攔截的受限資源會優先跳轉到之前被攔截的請求,需要每次都跳轉使defaultSuccessUrl("/test",true)
// .defaultSuccessUrl("/test")
// 前后端分離時代自定義認證成功處理
.successHandler(new MyAuthenticationSuccessHandler())
// 認證失敗跳轉頁面,必須使用POST請求
// .failureForwardUrl("/toLogin")
// 認證失敗跳轉頁面,必須使用GET請求
// .failureUrl("/toLogin")
// 前后端分離時代自定義認證失敗處理
.failureHandler(new MyAuthenticationFailureHandler())
.and()
// 注銷
.logout()
// 指定默認注銷url,默認請求方式GET
// .logoutUrl("/logout")
// 自定義注銷url
.logoutRequestMatcher(new OrRequestMatcher(
new AntPathRequestMatcher("/aa","GET"),
new AntPathRequestMatcher("/bb","POST")
))
// 銷毀session,默認為true
.invalidateHttpSession(true)
// 清除認證資訊,默認為true
.clearAuthentication(true)
// 注銷成功后跳轉頁面
// .logoutSuccessUrl("/toLogin")
.logoutSuccessHandler(new MyLogoutSuccessHandler())
.and()
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
}
8、獲取用戶認證資訊

- 三種策略模式,調整通過修改VM options
// 如果沒有設定自定義的策略,就采用MODE_THREADLOCAL模式
public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL";
// 采用InheritableThreadLocal,它是ThreadLocal的一個子類,適用多執行緒的環境
public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL";
// 全域策略,實作方式就是static SecurityContext contextHolder
public static final String MODE_GLOBAL = "MODE_GLOBAL";
-Dspring.security.strategy=MODE_INHERITABLETHREADLOCAL

8.1、 使用代碼獲取
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = (User) authentication.getPrincipal();
System.out.println("身份資訊:" + authentication.getPrincipal());
System.out.println("用戶:" + user.getUsername());
System.out.println("權限資訊:" + authentication.getAuthorities());

8.2、 前端頁面獲取
8.2.1、 引入依賴
- 不需要版本號
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
8.2.2、 匯入命名空間,獲取資料
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form th:action="@{/bb}" method="post">
<p>
<input type="submit" value="https://www.cnblogs.com/wandaren/archive/2022/10/29/注銷登陸">
</p>
</form>
<hr>
<h2>獲取認證用戶資訊</h2>
<ul>
<!-- <li sec:authentication="name"></li>-->
<!-- <li sec:authentication="authorities"></li>-->
<!-- <li sec:authentication="credentials"></li>-->
<!-- <li sec:authentication="authenticated"></li>-->
<li sec:authentication="principal.username"></li>
<li sec:authentication="principal.authorities"></li>
<li sec:authentication="principal.accountNonExpired"></li>
<li sec:authentication="principal.accountNonLocked"></li>
<li sec:authentication="principal.credentialsNonExpired"></li>
</ul>
</body>
</html>

9、 自定義資料源
9.1、 流程分析

When the user submits their credentials, the AbstractAuthenticationProcessingFilter creates an Authentication from the HttpServletRequest to be authenticated. The type of Authentication created depends on the subclass of AbstractAuthenticationProcessingFilter. For example, UsernamePasswordAuthenticationFilter creates a UsernamePasswordAuthenticationToken from a username and password that are submitted in the HttpServletRequest.
Next, the Authentication is passed into the AuthenticationManager to be authenticated.
If authentication fails, then Failure
- The SecurityContextHolder is cleared out.
- RememberMeServices.loginFail is invoked. If remember me is not configured, this is a no-op.
- AuthenticationFailureHandler is invoked.
If authentication is successful, then Success.
- SessionAuthenticationStrategy is notified of a new log in.
- The Authentication is set on the SecurityContextHolder. Later the SecurityContextPersistenceFilter saves the SecurityContext to the HttpSession.
- RememberMeServices.loginSuccess is invoked. If remember me is not configured, this is a no-op.
- ApplicationEventPublisher publishes an InteractiveAuthenticationSuccessEvent.
- AuthenticationSuccessHandler is invoked.



9.2、 修改WebSecurityConfigurer
@Autowired
DataSource dataSource;
@Bean
public PasswordEncoder bcryptPasswordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
public UserDetailsService users(PasswordEncoder encoder) {
// The builder will ensure the passwords are encoded before saving in memory
UserDetails user = User.withUsername("user")
.password(encoder.encode("123"))
.roles("USER")
.build();
UserDetails admin = User.withUsername("admin")
.password(encoder.encode("123"))
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
public UserDetailsService users() {
JdbcUserDetailsManager users = new JdbcUserDetailsManager(dataSource);
// UserDetails admin = User.withUsername("齊豐")
// .password(encoder.encode("123456"))
// .roles("USER")
// .build();
// users.createUser(admin);
System.out.println(dataSource.getClass());
return users;
}
9.3、 In-Memory Authentication
- 修改SecurityFilterChain
- 通過指定userDetailsService來切換不同的認證資料儲存方式
@Bean
@SuppressWarnings("all")
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity
.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
.mvcMatchers("/index").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin()
//自定義登陸頁面
.loginPage("/toLogin")
//自定義登陸頁面后必須指定處理登陸請求的url
.loginProcessingUrl("/doLogin")
// 自定義接收用戶名的引數名為uname
.usernameParameter("uname")
// 自定義接收密碼的引數名為pwd
.passwordParameter("pwd")
// 登陸認證成功后跳轉的頁面(轉發),必須使用POST請求
// .successForwardUrl("/test")
// 陸認證成功后跳轉的頁面(轉發),必須使用GET請求
// .defaultSuccessUrl("/test",true)
//不會每次都跳轉定義的頁面,默認會記錄認證攔截的請求,如果是攔截的受限資源會優先跳轉到之前被攔截的請求,需要每次都跳轉使defaultSuccessUrl("/test",true)
// .defaultSuccessUrl("/test")
// 前后端分離時代自定義認證成功處理
.successHandler(new MyAuthenticationSuccessHandler())
// 認證失敗跳轉頁面,必須使用POST請求
// .failureForwardUrl("/toLogin")
// 認證失敗跳轉頁面,必須使用GET請求
// .failureUrl("/toLogin")
// 前后端分離時代自定義認證失敗處理
.failureHandler(new MyAuthenticationFailureHandler())
.and()
// 注銷
.logout()
// 指定默認注銷url,默認請求方式GET
// .logoutUrl("/logout")
// 自定義注銷url
.logoutRequestMatcher(new OrRequestMatcher(
new AntPathRequestMatcher("/aa", "GET"),
new AntPathRequestMatcher("/bb", "POST")
))
// 銷毀session,默認為true
.invalidateHttpSession(true)
// 清除認證資訊,默認為true
.clearAuthentication(true)
// 注銷成功后跳轉頁面
// .logoutSuccessUrl("/toLogin")
.logoutSuccessHandler(new MyLogoutSuccessHandler())
.and()
.userDetailsService(users(bcryptPasswordEncoder()))
// .userDetailsService(users())
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
9.4、 JDBC Authentication
9.3.1、 引入依賴
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.11</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
9.3.2、 資料庫表及連接地址配置
- 表結構官方檔案
org/springframework/security/core/userdetails/jdbc/users.ddl

- 資料庫連連配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.0.0.128:3306/test
username: wq
password: 123456
9.3.3、 修改SecurityFilterChain
- 通過指定userDetailsService來切換不同的認證資料儲存方式
@Configuration
public class WebSecurityConfigurer {
@Autowired
DataSource dataSource;
@Bean
public PasswordEncoder bcryptPasswordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
public UserDetailsService inMemoryUsers(PasswordEncoder encoder) {
// The builder will ensure the passwords are encoded before saving in memory
UserDetails user = User.withUsername("user")
.password(encoder.encode("123"))
.roles("USER")
.build();
UserDetails admin = User.withUsername("admin")
.password(encoder.encode("123"))
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
public UserDetailsService jdbcUsers(PasswordEncoder encoder) {
JdbcUserDetailsManager users = new JdbcUserDetailsManager(dataSource);
// UserDetails admin = User.withUsername("齊豐")
// .password(encoder.encode("123456"))
// .roles("USER")
// .build();
// users.deleteUser(admin.getUsername());
// users.createUser(admin);
System.out.println(dataSource.getClass());
return users;
}
@Bean
@SuppressWarnings("all")
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity
.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
.mvcMatchers("/index").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin(login ->
login
//自定義登陸頁面
.loginPage("/toLogin")
//自定義登陸頁面后必須指定處理登陸請求的url
.loginProcessingUrl("/doLogin")
// 自定義接收用戶名的引數名為uname
.usernameParameter("uname")
//自定義接收密碼的引數名為pwd
.passwordParameter("pwd")
// 認證成功后跳轉的頁面(轉發),必須使用POST請求
//.successForwardUrl("/test")
// 證成功后跳轉的頁面(重定向),必須使用GET請求
//.defaultSuccessUrl("/test")
//不會每次都跳轉定義的頁面,默認會記錄認證攔截的請求,如果是攔截的受限資源會優先跳轉到之前被攔截的請求,需要每次都跳轉使defaultSuccessUrl("/test",true)
//.defaultSuccessUrl("/test",true)
//前后端分離時代自定義認證成功處理
.successHandler(new MyAuthenticationSuccessHandler())
//前后端分離時代自定義認證失敗處理
.failureHandler(new MyAuthenticationFailureHandler())
)
//注銷
.logout(logout -> {
logout
//指定默認注銷url,默認請求方式GET
//.logoutUrl("/logout")
.logoutRequestMatcher(
//自定義注銷url
new OrRequestMatcher(
new AntPathRequestMatcher("/aa", "GET"),
new AntPathRequestMatcher("/bb", "POST")))
//注銷成功后跳轉頁面
//.logoutSuccessUrl("/toLogin")
//前后端分離時代自定義注銷登錄處理器
.logoutSuccessHandler(new MyLogoutSuccessHandler())
//銷毀session,默認為true
.invalidateHttpSession(true)
//清除認證資訊,默認為true
.clearAuthentication(true);
})
//指定UserDetailsService來切換認證資訊不同的存盤方式(資料源)
.userDetailsService(inMemoryUsers(bcryptPasswordEncoder()))
.userDetailsService(jdbcUsers(bcryptPasswordEncoder()))
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
}
方式一:通過指定userDetailsService來切換不同的認證資料儲存方式,也可同時指定多個如:
.userDetailsService(users(bcryptPasswordEncoder()))
.userDetailsService(users())
方式二:在指定自定義的UserDetailsService上加上@Bean注解,或者實作UserDetailsService介面

9.5、擴展JDBC Authentication之mysql
表設計



-- test1.`user` definition
CREATE TABLE `user` (
`userId` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(100) NOT NULL COMMENT '用戶名',
`password` varchar(500) NOT NULL COMMENT '密碼',
`accountNonExpired` tinyint(1) NOT NULL,
`enabled` tinyint(1) NOT NULL,
`accountNonLocked` tinyint(1) NOT NULL,
`credentialsNonExpired` tinyint(1) NOT NULL,
PRIMARY KEY (`userId`),
UNIQUE KEY `user_UN` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- test1.`role` definition
CREATE TABLE `role` (
`roleId` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`name_zh` varchar(100) NOT NULL,
PRIMARY KEY (`roleId`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- test1.`role` definition
CREATE TABLE `role` (
`roleId` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`name_zh` varchar(100) NOT NULL,
PRIMARY KEY (`roleId`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO test1.`user` (username,password,accountNonExpired,enabled,accountNonLocked,credentialsNonExpired) VALUES
('root','{noop}123',1,1,1,1),
('admin','{noop}123',1,1,1,1),
('qifeng','{noop}123',1,1,1,1);
INSERT INTO test1.`role` (name,name_zh) VALUES
('ROLE_product','商品管理員'),
('ROLE_admin','系統管理員'),
('ROLE_user','用戶管理員');
INSERT INTO test1.user_role (userId,roleId) VALUES
(1,1),
(1,2),
(2,2),
(3,3);
9.5.1、引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.11</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
9.5.2、配置資料庫連接
server:
port: 8081
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.0.0.128:3306/test1
username: wq
password: 123456
mybatis:
type-aliases-package: com.wanqi.pojo
mapper-locations: classpath:mapper/*.xml
9.5.3、撰寫物體類與Mapper
User
User繼承UserDetails方便擴展
public class User implements UserDetails {
private Long userId;
private String username;
private String password;
/** 賬戶是否過期 */
private Boolean accountNonExpired;
/** 賬戶是否激活 */
private Boolean enabled;
/** 賬戶是否被鎖定 */
private Boolean accountNonLocked;
/** 密碼是否過期 */
private Boolean credentialsNonExpired;
private List<Role> roles = new ArrayList<>();
public User() {
}
public User(String username, String password, Boolean accountNonExpired, Boolean enabled, Boolean accountNonLocked, Boolean credentialsNonExpired, List<Role> roles) {
this.username = username;
this.password = password;
this.accountNonExpired = accountNonExpired;
this.enabled = enabled;
this.accountNonLocked = accountNonLocked;
this.credentialsNonExpired = credentialsNonExpired;
this.roles = roles;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<SimpleGrantedAuthority> authorities = new HashSet<>();
roles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getName())));
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return accountNonExpired;
}
@Override
public boolean isAccountNonLocked() {
return accountNonLocked;
}
@Override
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
@Override
public boolean isEnabled() {
return enabled;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setAccountNonExpired(Boolean accountNonExpired) {
this.accountNonExpired = accountNonExpired;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public void setAccountNonLocked(Boolean accountNonLocked) {
this.accountNonLocked = accountNonLocked;
}
public void setCredentialsNonExpired(Boolean credentialsNonExpired) {
this.credentialsNonExpired = credentialsNonExpired;
}
}
@Mapper
public interface UserMapper {
/**
* 根據用戶名查詢用戶
*/
User loadUserByUsername(@Param("username") String username);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wanqi.mapper.UserMapper">
<select id="loadUserByUsername" parameterType="String" resultType="user">
select * from user where username=#{username}
</select>
</mapper>
Role
public class Role {
private Long roleId;
private String name;
private String name_zh;
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getName_zh() {
return name_zh;
}
public void setName_zh(String name_zh) {
this.name_zh = name_zh;
}
public Role() {
}
public Role(String name, String name_zh) {
this.name = name;
this.name_zh = name_zh;
}
}
@Mapper
public interface RoleMapper {
/**
* 根據用戶編號查詢角色資訊
*/
List<Role> getRoleByUserId(@Param("userId") Long userId);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wanqi.mapper.RoleMapper">
<select id="getRoleByUserId" parameterType="Long" resultType="com.wanqi.pojo.Role">
select r.roleId,
r.name,
r.name_zh
from role r,user_role ur
where r.roleId = ur.roleId
and ur.userId= #{userId}
</select>
</mapper>
9.5.4、實作UserDetailsService介面
@Component("userDetailsImpl")
public class UserDetailsImpl implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
@Override
public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.loadUserByUsername(username);
if(user == null){
throw new UsernameNotFoundException("用戶名不存在");
}
List<Role> roles = roleMapper.getRoleByUserId(user.getUserId());
user.setRoles(roles);
return user;
}
}
9.5.5、指定認證資料源
- 通過 httpSecurity.userDetailsService(userDetailsImpl)
@Configuration
public class MyWebSecurityConfigurer {
private UserDetailsImpl userDetailsImpl;
@Autowired
public void setUserDetailsImpl(UserDetailsImpl userDetailsImpl) {
this.userDetailsImpl = userDetailsImpl;
}
@Bean
@SuppressWarnings("all")
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity
.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
.mvcMatchers("/index").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin(login ->
login
//自定義登陸頁面
.loginPage("/toLogin")
//自定義登陸頁面后必須指定處理登陸請求的url
.loginProcessingUrl("/doLogin")
// 自定義接收用戶名的引數名為uname
.usernameParameter("uname")
//自定義接收密碼的引數名為pwd
.passwordParameter("pwd")
// 認證成功后跳轉的頁面(轉發),必須使用POST請求
//.successForwardUrl("/test")
// 證成功后跳轉的頁面(重定向),必須使用GET請求
//.defaultSuccessUrl("/test")
//不會每次都跳轉定義的頁面,默認會記錄認證攔截的請求,如果是攔截的受限資源會優先跳轉到之前被攔截的請求,需要每次都跳轉使defaultSuccessUrl("/test",true)
//.defaultSuccessUrl("/test",true)
//前后端分離時代自定義認證成功處理
.successHandler(new MyAuthenticationSuccessHandler())
//前后端分離時代自定義認證失敗處理
.failureHandler(new MyAuthenticationFailureHandler())
)
//注銷
.logout(logout -> {
logout
//指定默認注銷url,默認請求方式GET
//.logoutUrl("/logout")
.logoutRequestMatcher(
//自定義注銷url
new OrRequestMatcher(
new AntPathRequestMatcher("/aa", "GET"),
new AntPathRequestMatcher("/bb", "POST")))
//注銷成功后跳轉頁面
//.logoutSuccessUrl("/toLogin")
//前后端分離時代自定義注銷登錄處理器
.logoutSuccessHandler(new MyLogoutSuccessHandler())
//銷毀session,默認為true
.invalidateHttpSession(true)
//清除認證資訊,默認為true
.clearAuthentication(true);
})
//指定UserDetailsService來切換認證資訊不同的存盤方式(資料源)
.userDetailsService(userDetailsImpl)
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
}
10、自定義JSON認證,前后端分離
10.1、HttpSecurity過濾器方法介紹
/*
* at:用指定的filter替換過濾器鏈中的指定filter
* before:放在過濾器鏈中哪一個filter之前
* after:放在過濾器鏈中哪一個filter之后
* httpSecurity.addFilterAt();
* httpSecurity.addFilterBefore(, );
* httpSecurity.addFilterAfter();
* */
10.2、自定義登錄處理filter
public class JsonLoginFilter extends UsernamePasswordAuthenticationFilter {
public JsonLoginFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
System.out.println("JosnLoginFilter");
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
try {
Map<String,String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
String username = map.get(getUsernameParameter());
username = (username != null) ? username.trim() : "";
String password = map.get(getPasswordParameter());
password = (password != null) ? password : "";
UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
password);
System.out.println(username);
System.out.println(password);
setDetails(request, authRequest);
return getAuthenticationManager().authenticate(authRequest);
} catch (IOException e) {
e.printStackTrace();
}
}
return super.attemptAuthentication(request, response);
}
}
10.3、組態檔撰寫
@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer {
private UserDetailsImpl userDetailsImpl;
@Autowired
public void setUserDetailsImpl(UserDetailsImpl userDetailsImpl) {
this.userDetailsImpl = userDetailsImpl;
}
@Bean
public PasswordEncoder bcryptPasswordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Autowired
AuthenticationConfiguration authenticationConfiguration;
/**
* 獲取AuthenticationManager(認證管理器),登錄時認證使用
* @return
* @throws Exception
*/
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public JsonLoginFilter josnLoginFilter() throws Exception {
System.out.println("setAuthenticationManager");
JsonLoginFilter filter = new JsonLoginFilter(authenticationManager());
filter.setUsernameParameter("uname");
filter.setPasswordParameter("pwd");
//前后端分離時代自定義認證成功處理
filter.setAuthenticationSuccessHandler(new MyAuthenticationSuccessHandler());
//前后端分離時代自定義認證失敗處理
filter.setAuthenticationFailureHandler(new MyAuthenticationFailureHandler());
return filter;
}
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity
.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/index").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin()
.and()
.addFilterAt(josnLoginFilter(),UsernamePasswordAuthenticationFilter.class)
//注銷
.logout(logout -> {
logout
.logoutRequestMatcher(
//自定義注銷url
new OrRequestMatcher(
new AntPathRequestMatcher("/aa", "GET"),
new AntPathRequestMatcher("/bb", "POST")))
//前后端分離時代自定義注銷登錄處理器
.logoutSuccessHandler(new MyLogoutSuccessHandler())
//銷毀session,默認為true
.invalidateHttpSession(true)
//清除認證資訊,默認為true
.clearAuthentication(true);
})
//指定UserDetailsService來切換認證資訊不同的存盤方式(資料源)
.userDetailsService(userDetailsImpl)
.exceptionHandling()
.authenticationEntryPoint((request, response, authException) -> {
// response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
response.setHeader("content-type", "application/json;charset=UTF-8");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().write("請先認證后重試!");
})
.and()
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
}
10.4、使用自定義filter注意事項
httpSecurity.formLogin()必須使用無參的
11、實作kaptcha圖片驗證碼
引入依賴
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
1、撰寫kaptcha配置類
@Configuration
public class KaptchaConfig {
@Bean
public Producer kaptchaProducer() {
Properties properties = new Properties();
//圖片的寬度
properties.setProperty("kaptcha.image.width", "150");
//圖片的高度
properties.setProperty("kaptcha.image.height", "50");
//字體大小
properties.setProperty("kaptcha.textproducer.font.size", "32");
//字體顏色(RGB)
properties.setProperty("kaptcha.textproducer.font.color", "0,0,0");
//驗證碼字符的集合
properties.setProperty("kaptcha.textproducer.char.string", "0123456789");
//驗證碼長度(即在上面集合中隨機選取幾位作為驗證碼)
properties.setProperty("kaptcha.textproducer.char.length", "4");
//圖片的干擾樣式
properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
DefaultKaptcha Kaptcha = new DefaultKaptcha();
Config config = new Config(properties);
Kaptcha.setConfig(config);
return Kaptcha;
}
}
2、自定義例外
public class KaptchaNotMatchException extends AuthenticationException {
public KaptchaNotMatchException(String msg, Throwable cause) {
super(msg, cause);
}
public KaptchaNotMatchException(String msg) {
super(msg);
}
}
11.1、傳統web開發方式
3、自定義Filter
public class VerifyCodeFilter extends UsernamePasswordAuthenticationFilter {
public static final String VERIFY_CODE_KEY = "kaptcha";
private String kaptchaParameter = VERIFY_CODE_KEY;
public void setKaptchaParameter(String kaptchaParameter) {
this.kaptchaParameter = kaptchaParameter;
}
public String getKaptchaParameter() {
return kaptchaParameter;
}
public VerifyCodeFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
String verifyCode = request.getParameter(getKaptchaParameter());
String verifyCodeOld = (String) request.getSession().getAttribute("verifyCode");
if (StringUtils.hasLength(verifyCode) && StringUtils.hasLength(verifyCodeOld)
&& verifyCode.equalsIgnoreCase(verifyCodeOld)) {
return super.attemptAuthentication(request, response);
}
throw new KaptchaNotMatchException("驗證碼錯誤");
}
}
4、提供生成驗證碼的介面
private Producer producer;
@Autowired
public void setProducer(Producer producer) {
this.producer = producer;
}
@RequestMapping("/vc.img")
public void img(HttpSession session, HttpServletResponse response) throws IOException {
String verifyCode = producer.createText();
BufferedImage image = producer.createImage(verifyCode);
session.setAttribute("verifyCode",verifyCode);
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
ImageIO.write(image, "jpg", outputStream);
}
5、登錄頁面添加驗證碼
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<p th:text="${session.SPRING_SECURITY_LAST_EXCEPTION}"></p>
<form th:action="@{/doLogin}" method="post">
<p>用戶名:<label>
<input name="uname" type="text"/>
</label></p>
<p>密碼:<label>
<input name="pwd" type="password"/>
</label></p>
<p>驗證碼:<label>
<input name="yzm" type="text"/>
<img th:src="https://www.cnblogs.com/wandaren/archive/2022/10/29/@{/vc.img}" alt=""/>
</label></p>
<p>
<input type="submit">
</p>
<p th:text="${SPRING_SECURITY_LAST_EXCEPTION}"></p>
</form>
</body>
</html>
6、配置WebSecurityConfigurer
@Configuration
@EnableWebSecurity
public class MyWebSecurityConfigurer {
private UserDetailsImpl userDetailsImpl;
@Autowired
public void setUserDetailsImpl(UserDetailsImpl userDetailsImpl) {
this.userDetailsImpl = userDetailsImpl;
}
@Autowired
AuthenticationConfiguration authenticationConfiguration;
@Bean
public PasswordEncoder bcryptPasswordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
/**
* 獲取AuthenticationManager(認證管理器),登錄時認證使用
* @return
* @throws Exception
*/
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
public VerifyCodeFilter verifyCodeFilter() throws Exception {
VerifyCodeFilter filter = new VerifyCodeFilter(authenticationManager());
// 自定義接收用戶名的引數名為uname
filter.setUsernameParameter("uname");
//自定義接收密碼的引數名為pwd
filter.setPasswordParameter("pwd");
filter.setKaptchaParameter("yzm");
filter.setFilterProcessesUrl("/doLogin");
//前后端分離時代自定義認證成功處理
filter.setAuthenticationSuccessHandler(new MyAuthenticationSuccessHandler());
//前后端分離時代自定義認證失敗處理
filter.setAuthenticationFailureHandler(new MyAuthenticationFailureHandler());
return filter;
}
@Bean
@SuppressWarnings("all")
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity
.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
.mvcMatchers("/vc.img").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin()
.loginPage("/toLogin")
.and()
.addFilterAt(verifyCodeFilter(), UsernamePasswordAuthenticationFilter.class)
//注銷
.logout(logout -> {
logout
//指定默認注銷url,默認請求方式GET
//.logoutUrl("/logout")
.logoutRequestMatcher(
//自定義注銷url
new OrRequestMatcher(
new AntPathRequestMatcher("/aa", "GET"),
new AntPathRequestMatcher("/bb", "POST")))
//注銷成功后跳轉頁面
.logoutSuccessUrl("/toLogin")
//前后端分離時代自定義注銷登錄處理器
// .logoutSuccessHandler(new MyLogoutSuccessHandler())
//銷毀session,默認為true
.invalidateHttpSession(true)
//清除認證資訊,默認為true
.clearAuthentication(true)
;})
//指定UserDetailsService來切換認證資訊不同的存盤方式(資料源)
.userDetailsService(userDetailsImpl)
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
}
11.2、前后端分離方式
3、提供生成驗證碼的介面
private Producer producer;
@Autowired
public void setProducer(Producer producer) {
this.producer = producer;
}
@RequestMapping("/cv.img")
public String verifyCoder(HttpSession session, HttpServletResponse response) throws IOException {
String verifyCode = producer.createText();
BufferedImage image = producer.createImage(verifyCode);
session.setAttribute("verifyCode",verifyCode);
FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream();
ImageIO.write(image, "jpg", outputStream);
return Base64Utils.encodeToString(outputStream.toByteArray());
}
4、自定義Filter
public class JsonLoginFilter extends UsernamePasswordAuthenticationFilter {
public static final String VERIFY_CODE_KEY = "kaptcha";
private String kaptchaParameter = VERIFY_CODE_KEY;
public void setKaptchaParameter(String kaptchaParameter) {
this.kaptchaParameter = kaptchaParameter;
}
public String getKaptchaParameter() {
return kaptchaParameter;
}
public JsonLoginFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
try {
Map<String, String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
String verifyCode = map.get(getKaptchaParameter());
String verifyCodeOld = (String) request.getSession().getAttribute("verifyCode");
if (!ObjectUtils.isEmpty(verifyCode) && !ObjectUtils.isEmpty(verifyCodeOld)
&& verifyCode.equalsIgnoreCase(verifyCodeOld)) {
String username = map.get(getUsernameParameter());
username = (username != null) ? username.trim() : "";
String password = map.get(getPasswordParameter());
password = (password != null) ? password : "";
UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
password);
System.out.println(username);
System.out.println(password);
setDetails(request, authRequest);
return getAuthenticationManager().authenticate(authRequest);
}
} catch (IOException e) {
e.printStackTrace();
}
}
throw new KaptchaNotMatchException("驗證碼錯誤");
}
}
5、配置WebSecurityConfigurer
@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer {
private UserDetailsImpl userDetailsImpl;
@Autowired
public void setUserDetailsImpl(UserDetailsImpl userDetailsImpl) {
this.userDetailsImpl = userDetailsImpl;
}
@Bean
public PasswordEncoder bcryptPasswordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Autowired
AuthenticationConfiguration authenticationConfiguration;
/**
* 獲取AuthenticationManager(認證管理器),登錄時認證使用
* @return
* @throws Exception
*/
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public JsonLoginFilter jsonLoginFilter() throws Exception {
JsonLoginFilter filter = new JsonLoginFilter(authenticationManager());
filter.setUsernameParameter("uname");
filter.setPasswordParameter("pwd");
filter.setKaptchaParameter("yzm");
//前后端分離時代自定義認證成功處理
filter.setAuthenticationSuccessHandler(new MyAuthenticationSuccessHandler());
//前后端分離時代自定義認證失敗處理
filter.setAuthenticationFailureHandler(new MyAuthenticationFailureHandler());
return filter;
}
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity
.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/cv.img").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin()
.and()
.addFilterAt(jsonLoginFilter(),UsernamePasswordAuthenticationFilter.class)
//注銷
.logout(logout -> {
logout
.logoutRequestMatcher(
//自定義注銷url
new OrRequestMatcher(
new AntPathRequestMatcher("/aa", "GET"),
new AntPathRequestMatcher("/bb", "POST")))
//前后端分離時代自定義注銷登錄處理器
.logoutSuccessHandler(new MyLogoutSuccessHandler())
//銷毀session,默認為true
.invalidateHttpSession(true)
//清除認證資訊,默認為true
.clearAuthentication(true);
})
//指定UserDetailsService來切換認證資訊不同的存盤方式(資料源)
.userDetailsService(userDetailsImpl)
.exceptionHandling()
.authenticationEntryPoint((request, response, authException) -> {
//response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
response.setHeader("content-type", "application/json;charset=UTF-8");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().write("請先認證后重試!");
})
.and()
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
}
12、密碼加密
12.1、不指定具體加密方式,通過DelegatingPasswordEncoder,根據前綴自動選擇
PasswordEncoder passwordEncoder =
PasswordEncoderFactories.createDelegatingPasswordEncoder();

12.2、指定具體加密方式
// Create an encoder with strength 16
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(16);
String result = encoder.encode("myPassword");
assertTrue(encoder.matches("myPassword", result));
// Create an encoder with all the defaults
Argon2PasswordEncoder encoder = new Argon2PasswordEncoder();
String result = encoder.encode("myPassword");
assertTrue(encoder.matches("myPassword", result));
// Create an encoder with all the defaults
Pbkdf2PasswordEncoder encoder = new Pbkdf2PasswordEncoder();
String result = encoder.encode("myPassword");
assertTrue(encoder.matches("myPassword", result));
// Create an encoder with all the defaults
SCryptPasswordEncoder encoder = new SCryptPasswordEncoder();
String result = encoder.encode("myPassword");
assertTrue(encoder.matches("myPassword", result));
13、密碼自動更新

實作UserDetailsPasswordService介面即可

@Component("userDetailsImpl")
public class UserDetailsImpl implements UserDetailsService, UserDetailsPasswordService {
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
@Override
public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.loadUserByUsername(username);
if(user == null){
throw new UsernameNotFoundException("用戶名不存在");
}
List<Role> roles = roleMapper.getRoleByUserId(user.getUserId());
user.setRoles(roles);
return user;
}
@Override
public UserDetails updatePassword(UserDetails user, String newPassword) {
int state = userMapper.updatePassword(newPassword, user.getUsername());
if (state == 1) {
((User) user).setPassword(newPassword);
}
return user;
}
}
14、Remember-Me
14.1、傳統web方式
14.1.1、login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form th:action="@{/doLogin}" method="post">
<p>用戶名:<label>
<input name="uname" type="text"/>
</label></p>
<p>密碼:<label>
<input name="pwd" type="password"/>
</label></p>
<p>記住我:<label>
<input name="remember-me" type="checkbox"/>
</label></p>
<p>
<input type="submit">
</p>
</form>
</body>
</html>
14.1.2、開啟rememberMeServices
- 基于記憶體實作
package com.wanqi.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import java.util.UUID;
@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer {
@Bean
public PasswordEncoder bcryptPasswordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
public UserDetailsService inMemoryUsers(PasswordEncoder encoder) {
// The builder will ensure the passwords are encoded before saving in memory
UserDetails user = User.withUsername("user")
.password(encoder.encode("123"))
.roles("USER")
.build();
UserDetails admin = User.withUsername("admin")
.password(encoder.encode("123"))
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
@Bean(name = "rememberMeServices")
public PersistentTokenBasedRememberMeServices rememberMeServices(){
return new PersistentTokenBasedRememberMeServices(UUID.randomUUID().toString(), inMemoryUsers(bcryptPasswordEncoder()), new InMemoryTokenRepositoryImpl());
}
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity
.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin(login ->
login
//自定義登陸頁面
.loginPage("/toLogin")
//自定義登陸頁面后必須指定處理登陸請求的url
.loginProcessingUrl("/doLogin")
// 自定義接收用戶名的引數名為uname
.usernameParameter("uname")
//自定義接收密碼的引數名為pwd
.passwordParameter("pwd")
// 認證成功后跳轉的頁面(轉發),必須使用POST請求
//.successForwardUrl("/test")
// 證成功后跳轉的頁面(重定向),必須使用GET請求
//.defaultSuccessUrl("/test")
//不會每次都跳轉定義的頁面,默認會記錄認證攔截的請求,如果是攔截的受限資源會優先跳轉到之前被攔截的請求,需要每次都跳轉使defaultSuccessUrl("/test",true)
.defaultSuccessUrl("/toLogout",true)
//前后端分離時代自定義認證成功處理
// .successHandler(new MyAuthenticationSuccessHandler())
//前后端分離時代自定義認證失敗處理
// .failureHandler(new MyAuthenticationFailureHandler())
.failureUrl("/404")
)
//注銷
.logout(logout -> {
logout
//指定默認注銷url,默認請求方式GET
// .logoutUrl("/logout")
.logoutRequestMatcher(
//自定義注銷url
new OrRequestMatcher(
new AntPathRequestMatcher("/aa", "GET"),
new AntPathRequestMatcher("/bb", "POST")))
//注銷成功后跳轉頁面
.logoutSuccessUrl("/toLogin")
//前后端分離時代自定義注銷登錄處理器
// .logoutSuccessHandler(new MyLogoutSuccessHandler())
//銷毀session,默認為true
.invalidateHttpSession(true)
//清除認證資訊,默認為true
.clearAuthentication(true);
})
//指定UserDetailsService來切換認證資訊不同的存盤方式(資料源)
.userDetailsService(inMemoryUsers(bcryptPasswordEncoder()))
//開啟rememberMe
.rememberMe()
//自定義rememberMe引數名
// .rememberMeParameter();
.rememberMeServices(rememberMeServices())
.and()
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
}
- 持久化,基于mysql實作
@Bean
public PersistentTokenRepository jdbcTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
//自動創建表結構,首次啟動設定為true
// jdbcTokenRepository.setCreateTableOnStartup(true);
return jdbcTokenRepository;
}
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return
//開啟權限驗證
httpSecurity
.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
.mvcMatchers("/404").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin(login ->
login
//自定義登陸頁面
.loginPage("/toLogin")
//自定義登陸頁面后必須指定處理登陸請求的url
.loginProcessingUrl("/doLogin")
// 自定義接收用戶名的引數名為uname
.usernameParameter("uname")
//自定義接收密碼的引數名為pwd
.passwordParameter("pwd")
// 認證成功后跳轉的頁面(轉發),必須使用POST請求
//.successForwardUrl("/test")
// 證成功后跳轉的頁面(重定向),必須使用GET請求
//.defaultSuccessUrl("/test")
//不會每次都跳轉定義的頁面,默認會記錄認證攔截的請求,如果是攔截的受限資源會優先跳轉到之前被攔截的請求,需要每次都跳轉使defaultSuccessUrl("/test",true)
.defaultSuccessUrl("/toLogout",true)
//前后端分離時代自定義認證成功處理
// .successHandler(new MyAuthenticationSuccessHandler())
//前后端分離時代自定義認證失敗處理
// .failureHandler(new MyAuthenticationFailureHandler())
.failureUrl("/404")
)
//注銷
.logout(logout -> {
logout
//指定默認注銷url,默認請求方式GET
// .logoutUrl("/logout")
.logoutRequestMatcher(
//自定義注銷url
new OrRequestMatcher(
new AntPathRequestMatcher("/aa", "GET"),
new AntPathRequestMatcher("/bb", "POST")))
//注銷成功后跳轉頁面
.logoutSuccessUrl("/toLogin")
//前后端分離時代自定義注銷登錄處理器
// .logoutSuccessHandler(new MyLogoutSuccessHandler())
//銷毀session,默認為true
.invalidateHttpSession(true)
//清除認證資訊,默認為true
.clearAuthentication(true);
})
//指定UserDetailsService來切換認證資訊不同的存盤方式(資料源)
.userDetailsService(inMemoryUsers(bcryptPasswordEncoder()))
//開啟rememberMe
.rememberMe()
.tokenRepository(jdbcTokenRepository())
.and()
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
}
14.2、前后端分離
14.2.1、自定義RememberMeServices實作類
package com.wanqi.service;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import javax.servlet.http.HttpServletRequest;
/**
* @Description 自定義RememberMeServices實作類
* @Version 1.0.0
* @Date 2022/9/5
* @Author wandaren
*/
public class RememberMeServices extends PersistentTokenBasedRememberMeServices {
public RememberMeServices(String key, UserDetailsService userDetailsService, PersistentTokenRepository tokenRepository) {
super(key, userDetailsService, tokenRepository);
}
@Override
protected boolean rememberMeRequested(HttpServletRequest request, String parameter) {
String paramValue = https://www.cnblogs.com/wandaren/archive/2022/10/29/request.getAttribute(AbstractRememberMeServices.DEFAULT_PARAMETER).toString();
return paramValue.equalsIgnoreCase("true") || paramValue.equalsIgnoreCase("on")
|| paramValue.equalsIgnoreCase("yes") || paramValue.equals("1");
}
}
14.2.2、自定義認證方式
package com.wanqi.security.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
import org.springframework.util.ObjectUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
/**
* @Description 處理Json方式的登錄請求
* @Version 1.0.0
* @Date 2022/8/21
* @Author wandaren
*/
public class JsonLoginFilter extends UsernamePasswordAuthenticationFilter {
public JsonLoginFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
try {
Map<String, String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
String username = map.get(getUsernameParameter());
username = (username != null) ? username.trim() : "";
String password = map.get(getPasswordParameter());
password = (password != null) ? password : "";
String rememberMe = map.get(AbstractRememberMeServices.DEFAULT_PARAMETER);
if (!ObjectUtils.isEmpty(rememberMe)) {
request.setAttribute(AbstractRememberMeServices.DEFAULT_PARAMETER, rememberMe);
}
UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
password);
System.out.println(username);
System.out.println(password);
setDetails(request, authRequest);
return getAuthenticationManager().authenticate(authRequest);
} catch (IOException e) {
e.printStackTrace();
}
}
throw new AuthenticationServiceException("Authentication ContentType not supported: " + request.getContentType());
}
}
14.2.3、配置
filter.setRememberMeServices(rememberMeServices());
.rememberMe()
.rememberMeServices(rememberMeServices())
.tokenRepository(jdbcTokenRepository())
package com.wanqi.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wanqi.security.filter.JsonLoginFilter;
import com.wanqi.service.RememberMeServices;
import com.wanqi.service.impl.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/5
* @Author wandaren
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
DataSource dataSource;
UserDetailsImpl userDetailsImpl;
@Autowired
public void setUserDetailsImpl(UserDetailsImpl userDetailsImpl) {
this.userDetailsImpl = userDetailsImpl;
}
@Bean
public PasswordEncoder bcryptPasswordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Autowired
public AuthenticationConfiguration authenticationConfiguration;
/**
* 獲取AuthenticationManager(認證管理器),登錄時認證使用
*
* @return
* @throws Exception
*/
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public JsonLoginFilter jsonLoginFilter() throws Exception {
JsonLoginFilter filter = new JsonLoginFilter(authenticationManager());
//指定認證url
filter.setFilterProcessesUrl("/doLogin");
//指定接收json,用戶名key
filter.setUsernameParameter("uname");
//指定接收json,密碼key
filter.setPasswordParameter("pwd");
filter.setAuthenticationManager(authenticationManager());
filter.setRememberMeServices(rememberMeServices());
//前后端分離時代自定義認證成功處理
filter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Map<String, Object> map = new HashMap<>();
map.put("msg", "登陸成功");
map.put("code", HttpStatus.OK.value());
map.put("authentication", authentication);
String s = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(s);
}
});
//前后端分離時代自定義認證失敗處理
filter.setAuthenticationFailureHandler((request, response, exception) -> {
Map<String, Object> map = new HashMap<>();
map.put("msg", exception.getMessage());
map.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
String s = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(s);
});
return filter;
}
@Bean
public PersistentTokenRepository jdbcTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
//自動創建表結構,首次啟動設定為true
// jdbcTokenRepository.setCreateTableOnStartup(true);
return jdbcTokenRepository;
}
@Bean
public RememberMeServices rememberMeServices(){
return new RememberMeServices(UUID.randomUUID().toString(), userDetailsImpl, jdbcTokenRepository());
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.addFilterAt(jsonLoginFilter(), UsernamePasswordAuthenticationFilter.class)
.logout(logout -> {
logout
.logoutRequestMatcher(
//自定義注銷url
new OrRequestMatcher(
new AntPathRequestMatcher("/aa", "GET"),
new AntPathRequestMatcher("/bb", "POST")))
//前后端分離時代自定義注銷登錄處理器
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Map<String, Object> map = new HashMap<>();
map.put("msg", "注銷成功");
map.put("code", HttpStatus.OK.value());
map.put("authentication", authentication);
String s = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(s);
}
})
//銷毀session,默認為true
.invalidateHttpSession(true)
//清除認證資訊,默認為true
.clearAuthentication(true);
})
//指定UserDetailsService來切換認證資訊不同的存盤方式(資料源)
.userDetailsService(userDetailsImpl)
.exceptionHandling()
.authenticationEntryPoint((request, response, authException) -> {
// response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
response.setHeader("content-type", "application/json;charset=UTF-8");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().write("請先認證后重試!");
})
.and()
.rememberMe()
.rememberMeServices(rememberMeServices())
.tokenRepository(jdbcTokenRepository())
.and()
//禁止csrf跨站請求保護
.csrf().disable()
.build();
}
}
15、會話管理

15.1、配置
package com.wanqi.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.session.HttpSessionEventPublisher;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/5
* @Author wandaren
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception{
httpSecurity.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.defaultSuccessUrl("/hello",true)
.and()
.csrf().disable()
.sessionManagement(session -> session
//最多一個會話
.maximumSessions(1)
//true:超過會話上限不再容許登錄
// .maxSessionsPreventsLogin(true)
// 會話失效(用戶被擠下線后)跳轉地址
// .expiredUrl("/login")
// 前后端分離處理方式
.expiredSessionStrategy(new SessionInformationExpiredStrategy() {
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
event.getResponse().setHeader("content-type", "application/json;charset=UTF-8");
event.getResponse().setStatus(HttpStatus.UNAUTHORIZED.value());
event.getResponse().getWriter().write("會話超時!");
}
})
);
return httpSecurity.build();
}
@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
}
15.2、共享會話
15.2.1、引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
15.2.2、撰寫配置
- application.yml
spring:
redis:
host: 172.16.156.139
port: 6379
password: qifeng
database: 0
main:
allow-circular-references: true
- RedisSessionConfig
package com.wanqi.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.security.web.session.HttpSessionEventPublisher;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/5
* @Author wandaren
*/
@Configuration
@EnableRedisHttpSession
public class RedisSessionConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.database}")
private int database;
@Bean
RedisStandaloneConfiguration redisStandaloneConfiguration() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setHostName(host);
redisStandaloneConfiguration.setPort(port);
redisStandaloneConfiguration.setPassword(password);
redisStandaloneConfiguration.setDatabase(database);
return redisStandaloneConfiguration;
}
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(redisStandaloneConfiguration());
}
@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
}
- SecurityConfig
package com.wanqi.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;
import javax.servlet.ServletException;
import java.io.IOException;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/5
* @Author wandaren
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig<S extends Session> {
@Autowired
private FindByIndexNameSessionRepository<S> sessionRepository;
@Bean
public PasswordEncoder bcryptPasswordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
public UserDetailsService inMemoryUsers(PasswordEncoder encoder) {
// The builder will ensure the passwords are encoded before saving in memory
UserDetails user = User.withUsername("user")
.password(encoder.encode("123"))
.roles("USER")
.build();
UserDetails admin = User.withUsername("admin")
.password(encoder.encode("123"))
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception{
httpSecurity.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.defaultSuccessUrl("/hello",true)
.and()
.csrf().disable()
.sessionManagement(session -> session
//最多一個會話
.maximumSessions(1)
//true超過會話上限不再容許登錄
.maxSessionsPreventsLogin(true)
// 被踢下線后跳轉地址
// .expiredUrl("/login")
.expiredSessionStrategy(new SessionInformationExpiredStrategy() {
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
event.getResponse().setHeader("content-type", "application/json;charset=UTF-8");
event.getResponse().setStatus(HttpStatus.UNAUTHORIZED.value());
event.getResponse().getWriter().write("會話超時!");
}
})
.sessionRegistry(sessionRegistry())
)
.userDetailsService(inMemoryUsers(bcryptPasswordEncoder()))
;
return httpSecurity.build();
}
@Bean
public SpringSessionBackedSessionRegistry<S> sessionRegistry() {
return new SpringSessionBackedSessionRegistry<>(this.sessionRepository);
}
}
16、CSRF防御
16.1、傳統web開發
- 登錄頁面加上_csrf
<input type="hidden" name="_csrf" th:value="https://www.cnblogs.com/wandaren/archive/2022/10/29/${_csrf.getToken()}">
- SecurityConfig配置修改
httpSecurity.csrf()
16.2、前后端分離開發
16.2.1、登陸頁面不需要令牌
httpSecurity.csrf()
//SpringSecurity處理登陸的默認方法不加令牌
.ignoringAntMatchers("/doLogin")
//將令牌保存到cookie,容許前端獲取
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
- 登陸后回傳cookie中包含XSRF-TOKEN

- 后續請求在請求頭增加X-XSRF-TOKEN,值為登陸cookie中的XSRF-TOKEN值

17、跨越處理
17.1、spring跨越處理
17.1.1、使用@CrossOrigin,可以作用到類上也可以作用到具體方法上
@RestController
public class HelloController {
@RequestMapping("/hello")
@CrossOrigin
public String hello(){
return "hello";
}
}
17.1.2、實作WebMvcConfigurer介面重寫addCorsMappings方法
package com.wanqi.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/6
* @Author wandaren
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//對哪些請求進行跨域處理
registry.addMapping("/**")
.allowCredentials(false)
.allowedHeaders("*")
.allowedMethods("*")
.allowedOrigins("*")
.exposedHeaders("")
.maxAge(3600)
;
}
}
17.1.3、使用CorsFilter
@Bean
FilterRegistrationBean<CorsFilter> corsFilter() {
FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedOrigins(Collections.singletonList("*"));
corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
corsConfiguration.setAllowedMethods(Collections.singletonList("*"));
corsConfiguration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
registrationBean.setFilter(new CorsFilter(source));
//指定Filter執行順序
registrationBean.setOrder(-1);
return registrationBean;
}
17.2、SpringSecurity跨域處理
17.2.1、 Security配置
@Bean
public CorsConfigurationSource configurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedOrigins(Collections.singletonList("*"));
corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
corsConfiguration.setAllowedMethods(Collections.singletonList("*"));
corsConfiguration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}
httpSecurity.cors()
.configurationSource(configurationSource())
18、權限管理/授權
18.1、針對url配置
- 配置SecurityConfig
package com.wanqi.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Collections;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/5
* @Author wandaren
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public PasswordEncoder bcryptPasswordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
public UserDetailsService inMemoryUsers(PasswordEncoder encoder) {
// The builder will ensure the passwords are encoded before saving in memory
UserDetails user = User.withUsername("user")
.password(encoder.encode("123"))
.roles("USER")
.build();
UserDetails admin = User.withUsername("admin")
.password(encoder.encode("123"))
.roles("ADMIN")
.build();
UserDetails qifeng = User.withUsername("qifeng")
.password(encoder.encode("123"))
.authorities("READ_HELLO","ROLE_ADMIN","ROLE_USER")
.build();
return new InMemoryUserDetailsManager(user, admin, qifeng);
}
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests()
//權限READ_HELLO
.mvcMatchers("/hello").hasAuthority("READ_HELLO")
//角色
.mvcMatchers("/admin").hasRole("ADMIN")
.mvcMatchers("/user").hasRole("USER")
.anyRequest().authenticated()
.and()
.csrf().disable()
.formLogin()
.and()
.logout(logout -> logout.logoutRequestMatcher(
//自定義注銷url
new OrRequestMatcher(
new AntPathRequestMatcher("/aa", "GET")))
.logoutSuccessUrl("/login")
)
.userDetailsService(inMemoryUsers(bcryptPasswordEncoder()))
;
return httpSecurity.build();
}
}
- 編碼HelloController
package com.wanqi.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/6
* @Author wandaren
*/
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "hello";
}
@RequestMapping("/admin")
public String admin(){
return "admin";
}
@RequestMapping("/user")
public String user(){
return "user";
}
}
18.2、針對方法配置
- 基于注解EnableMethodSecurity
- @EnableMethodSecurity(prePostEnabled = true)

- 配置開啟注解
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
- 編碼測驗介面
package com.wanqi.controller;
import com.wanqi.pojo.DataDamo;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/6
* @Author wandaren
*/
@RestController
@RequestMapping("/hi")
public class MethodController {
@PreAuthorize("hasRole('ADMIN') and authentication.name=='qifeng'")
@RequestMapping
public String hi() {
return "hi";
}
@PreAuthorize("authentication.name==#name")
@RequestMapping("h1")
public String hello(String name) {
return "hello: " + name;
}
//filterTarget必須是:陣列/集合
@PreFilter(value = "https://www.cnblogs.com/wandaren/archive/2022/10/29/filterObject.id%2 != 0", filterTarget = "dataDamos")
@RequestMapping("users")
public String users(@RequestBody List<DataDamo> dataDamos) {
return "hello: " + dataDamos;
}
@PostAuthorize("returnObject.id==1")
@RequestMapping("userId")
public DataDamo userId(Integer id) {
return new DataDamo(id, "ssss");
}
@PostFilter("filterObject.id>5")
@RequestMapping("lists")
public List<DataDamo> lists() {
List<DataDamo> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(new DataDamo(i, "sss" + i));
}
return list;
}
}
19、基于資料庫權限驗證
19.1、表結構
| 選單/權限 | 角色(可訪問) |
|---|---|
| /admin/** | ROLE_ADMIN |
| /user/** | ROLE_USER |
| /guest/** | ROLE_GUEST |
| 用戶 | 角色 |
|---|---|
| admin | ADMIN、USER |
| user | USER |
| qifeng | GUEST |

19.2、sql
- 選單/權限
CREATE TABLE `menu` (
`id` bigint NOT NULL AUTO_INCREMENT,
`pattern` varchar(128) COLLATE utf8mb4_general_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
INSERT INTO menu (pattern) VALUES
('/admin/**'),
('/user/**'),
('/guest/**');
- 角色
CREATE TABLE `role` (
`id` bigint NOT NULL AUTO_INCREMENT,
`name` varchar(100) COLLATE utf8mb4_general_ci NOT NULL,
`name_zh` varchar(100) COLLATE utf8mb4_general_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
INSERT INTO `role` (name,name_zh) VALUES
('ROLE_ADMIN','管理員'),
('ROLE_USER','普通用戶'),
('ROLE_GUEST','游客');
- 選單/權限-角色關系
CREATE TABLE `menu_role` (
`id` bigint NOT NULL AUTO_INCREMENT,
`mid` bigint NOT NULL,
`rid` bigint NOT NULL,
PRIMARY KEY (`id`),
KEY `menu_role_mid_IDX` (`mid`,`rid`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
INSERT INTO `security`.menu_role (mid,rid) VALUES
(1,1),
(2,2),
(3,2),
(3,3);
- 用戶
CREATE TABLE `user` (
`id` bigint NOT NULL AUTO_INCREMENT,
`username` varchar(100) COLLATE utf8mb4_general_ci NOT NULL COMMENT '用戶名',
`password` varchar(500) COLLATE utf8mb4_general_ci NOT NULL COMMENT '密碼',
`accountNonExpired` tinyint(1) NOT NULL COMMENT '賬戶是否過期',
`enabled` tinyint(1) NOT NULL COMMENT '賬戶是否激活',
`accountNonLocked` tinyint(1) NOT NULL COMMENT '賬戶是否被鎖定',
`credentialsNonExpired` tinyint(1) NOT NULL COMMENT '密碼是否過期',
PRIMARY KEY (`id`),
KEY `user_username_IDX` (`username`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
INSERT INTO `user` (username,password,accountNonExpired,enabled,accountNonLocked,credentialsNonExpired) VALUES
('admin','{noop}123',1,1,1,1),
('user','{noop}123',1,1,1,1),
('qifeng','{noop}123',1,1,1,1);
- 用戶-角色關系
CREATE TABLE `user_role` (
`id` bigint NOT NULL AUTO_INCREMENT,
`uid` bigint NOT NULL COMMENT '用戶編號',
`rid` bigint NOT NULL COMMENT '角色編號',
PRIMARY KEY (`id`),
KEY `user_role_userId_IDX` (`uid`,`rid`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
INSERT INTO `security`.user_role (uid,rid) VALUES
(1,1),
(1,2),
(2,2),
(3,3);
19.3、依賴,資料庫配置
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.11</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
server:
port: 8081
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://172.16.156.139:3306/security?allowPublicKeyRetrieval=true
username: wq
password: qifeng
mybatis:
type-aliases-package: com.wanqi.pojo
mapper-locations: classpath:mapper/*.xml
19.4、物體類與mapper
- 選單
package com.wanqi.pojo;
import java.util.ArrayList;
import java.util.List;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/7
* @Author wandaren
*/
public class Menu {
private Long id;
private String pattern;
private List<Role> roles = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public Menu(String pattern) {
this.pattern = pattern;
}
public Menu() {
}
@Override
public String toString() {
return "Menu{" +
"id=" + id +
", pattern='" + pattern + '\'' +
", roles=" + roles +
'}';
}
}
package com.wanqi.mapper;
import com.wanqi.pojo.Menu;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/7
* @Author wandaren
*/
@Mapper
public interface MenuMapper {
public List<Menu> getAllMenu();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wanqi.mapper.MenuMapper">
<resultMap id="MenuResultMap" type="com.wanqi.pojo.Menu">
<id property="id" column="id"/>
<result property="pattern" column="pattern"/>
<collection property="roles" ofType="com.wanqi.pojo.Role">
<id property="id" column="rid"/>
<result property="name" column="rname"/>
<result property="nameZh" column="rnameZh"/>
</collection>
</resultMap>
<select id="getAllMenu" resultMap="MenuResultMap">
Select m.*, r.id as rid, r.name as rname, r.name_zh as rnameZh From menu m
Left join menu_role mr on m.`id` = mr.`mid`
Left join role r on r.`id` = mr.`rid`
</select>
</mapper>
- 角色
package com.wanqi.pojo;
public class Role {
private Long id;
private String name;
private String nameZh;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNameZh() {
return nameZh;
}
public void setNameZh(String nameZh) {
this.nameZh = nameZh;
}
public Role() {
}
public Role(String name, String nameZh) {
this.name = name;
this.nameZh = nameZh;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", name='" + name + '\'' +
", nameZh='" + nameZh + '\'' +
'}';
}
}
package com.wanqi.mapper;
import com.wanqi.pojo.Role;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface RoleMapper {
/**
* 根據用戶編號查詢角色資訊
*/
List<Role> getRoleByUserId(@Param("userId") Long userId);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wanqi.mapper.RoleMapper">
<select id="getRoleByUserId" parameterType="Long" resultType="com.wanqi.pojo.Role">
select r.id,
r.name,
r.name_zh as nameZh
from role r,user_role ur
where r.id = ur.rid
and ur.uid= #{userId}
</select>
</mapper>
- 用戶
package com.wanqi.pojo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.*;
public class User implements UserDetails {
private Long id;
private String username;
private String password;
/** 賬戶是否過期
* 在MySQL中,0被認為是false,非零值被認為是true
* */
private Boolean accountNonExpired = true;
/** 賬戶是否激活 */
private Boolean enabled = true;
/** 賬戶是否被鎖定 */
private Boolean accountNonLocked = true;
/** 密碼是否過期 */
private Boolean credentialsNonExpired = true;
private List<Role> roles = new ArrayList<>();
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<SimpleGrantedAuthority> authorities = new HashSet<>();
roles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getName())));
return authorities;
}
public Long getId() {
return id;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public List<Role> getRoles() {
return roles;
}
@Override
public boolean isAccountNonExpired() {
return accountNonExpired;
}
@Override
public boolean isAccountNonLocked() {
return accountNonLocked;
}
@Override
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setId(Long id) {
this.id = id;
}
public void setAccountNonExpired(Boolean accountNonExpired) {
this.accountNonExpired = accountNonExpired;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public void setAccountNonLocked(Boolean accountNonLocked) {
this.accountNonLocked = accountNonLocked;
}
public void setCredentialsNonExpired(Boolean credentialsNonExpired) {
this.credentialsNonExpired = credentialsNonExpired;
}
}
package com.wanqi.mapper;
import com.wanqi.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface UserMapper {
/**
* 根據用戶名查詢用戶
*/
User loadUserByUsername(@Param("username") String username);
/**
* 添加用戶
* @param user
* @return int
*/
int save(User user);
/**
*
* 更新密碼
* @param password
* @param username
* @return int
*/
int updatePassword(@Param("password")String password,@Param("username") String username);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wanqi.mapper.UserMapper">
<select id="loadUserByUsername" parameterType="String" resultType="user">
select * from user where username=#{username}
</select>
<insert id="save" parameterType="user">
INSERT INTO `user` (username, password, accountNonExpired, enabled, accountNonLocked, credentialsNonExpired)
VALUES (#{username}, #{password}, #{accountNonExpired}, #{enabled}, #{accountNonLocked},
#{credentialsNonExpired});
</insert>
<update id="updatePassword">
UPDATE `user`
SET password= #{password}
WHERE username = #{username};
</update>
</mapper>
19.5、自定義的資源(url)權限(角色)資料獲取類
package com.wanqi.security.filter;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wanqi.mapper.MenuMapper;
import com.wanqi.pojo.Menu;
import com.wanqi.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import java.util.Collection;
import java.util.List;
/**
* @Description 自定義的資源(url)權限(角色)資料獲取類
* @Version 1.0.0
* @Date 2022/9/7
* @Author wandaren
*/
@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
@Autowired
private MenuMapper menuMapper;
@Bean
private AntPathMatcher antPathMatcher() {
return new AntPathMatcher();
}
/**
* 獲取用戶請求的某個具體的資源(url)所需要的權限(角色)集合
*/
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
//獲取當前請求物件
String requestURI = ((FilterInvocation) object).getRequest().getRequestURI();
//查詢所有的選單
List<Menu> allMenu = menuMapper.getAllMenu();
System.out.println(JSONUtil.toJsonStr(allMenu));
for (Menu menu : allMenu) {
if (antPathMatcher().match(menu.getPattern(), requestURI)) {
String[] roles = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
System.out.println(JSONUtil.toJsonStr(roles));
return SecurityConfig.createList(roles);
}
}
return null;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
@Override
public boolean supports(Class<?> clazz) {
return FilterInvocation.class.isAssignableFrom(clazz);
}
}
19.6、自定義獲取賬號資訊,與密碼自動更新
package com.wanqi.service.impl;
import cn.hutool.json.JSONUtil;
import com.wanqi.mapper.RoleMapper;
import com.wanqi.mapper.UserMapper;
import com.wanqi.pojo.Role;
import com.wanqi.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.List;
@Component("userDetailsImpl")
public class UserDetailsImpl implements UserDetailsService, UserDetailsPasswordService {
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
@Override
public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.loadUserByUsername(username);
System.out.println("---"+JSONUtil.toJsonStr(user));
if(user == null){
throw new UsernameNotFoundException("用戶名不存在");
}
List<Role> roles = roleMapper.getRoleByUserId(user.getId());
System.out.println("---"+JSONUtil.toJsonStr(roles));
user.setRoles(roles);
return user;
}
@Override
public UserDetails updatePassword(UserDetails user, String newPassword) {
int state = userMapper.updatePassword(newPassword, user.getUsername());
if (state == 1) {
((User) user).setPassword(newPassword);
}
return user;
}
}
19.7、自定義RememberMeServices實作類
package com.wanqi.service;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import javax.servlet.http.HttpServletRequest;
/**
* @Description 自定義RememberMeServices實作類
* @Version 1.0.0
* @Date 2022/9/5
* @Author wandaren
*/
public class RememberMeServices extends PersistentTokenBasedRememberMeServices {
public RememberMeServices(String key, UserDetailsService userDetailsService, PersistentTokenRepository tokenRepository) {
super(key, userDetailsService, tokenRepository);
}
@Override
protected boolean rememberMeRequested(HttpServletRequest request, String parameter) {
Object attribute = request.getAttribute(AbstractRememberMeServices.DEFAULT_PARAMETER);
if (attribute == null) {
return false;
}
String paramValue = https://www.cnblogs.com/wandaren/archive/2022/10/29/attribute.toString();
return paramValue.equalsIgnoreCase("true") || paramValue.equalsIgnoreCase("on")
|| paramValue.equalsIgnoreCase("yes") || paramValue.equals("1");
}
}
19.8、Security配置類
package com.wanqi.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wanqi.security.filter.CustomFilterInvocationSecurityMetadataSource;
import com.wanqi.service.RememberMeServices;
import com.wanqi.service.impl.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.UrlAuthorizationConfigurer;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/5
* @Author wandaren
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
DataSource dataSource;
@Autowired
CustomFilterInvocationSecurityMetadataSource customFilterInvocationSecurityMetadataSource;
UserDetailsImpl userDetailsImpl;
@Autowired
public void setUserDetailsImpl(UserDetailsImpl userDetailsImpl) {
this.userDetailsImpl = userDetailsImpl;
}
@Bean
public PasswordEncoder bcryptPasswordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Autowired
public AuthenticationConfiguration authenticationConfiguration;
/**
* 獲取AuthenticationManager(認證管理器),登錄時認證使用
*
* @return
* @throws Exception
*/
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public PersistentTokenRepository jdbcTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
//自動創建表結構,首次啟動設定為true
// jdbcTokenRepository.setCreateTableOnStartup(true);
return jdbcTokenRepository;
}
@Bean
public RememberMeServices rememberMeServices(){
return new RememberMeServices(UUID.randomUUID().toString(), userDetailsImpl, jdbcTokenRepository());
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
//獲取工廠物件
ApplicationContext applicationContext = httpSecurity.getSharedObject(ApplicationContext.class);
//設定自定義url權限處理
httpSecurity.apply(new UrlAuthorizationConfigurer<>(applicationContext))
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O object) {
object.setSecurityMetadataSource(customFilterInvocationSecurityMetadataSource);
//是否拒絕公共資源訪問
object.setRejectPublicInvocations(false);
return object;
}
});
httpSecurity.formLogin()
.and()
.logout(logout -> {
logout
.logoutRequestMatcher(
//自定義注銷url
new OrRequestMatcher(
new AntPathRequestMatcher("/aa", "GET"),
new AntPathRequestMatcher("/bb", "POST")))
//前后端分離時代自定義注銷登錄處理器
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Map<String, Object> map = new HashMap<>();
map.put("msg", "注銷成功");
map.put("code", HttpStatus.OK.value());
map.put("authentication", authentication);
String s = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(s);
}
})
//銷毀session,默認為true
.invalidateHttpSession(true)
//清除認證資訊,默認為true
.clearAuthentication(true);
})
//指定UserDetailsService來切換認證資訊不同的存盤方式(資料源)
.userDetailsService(userDetailsImpl)
.rememberMe()
.rememberMeServices(rememberMeServices())
.tokenRepository(jdbcTokenRepository())
.and()
//禁止csrf跨站請求保護
.csrf().disable();
return httpSecurity.build();
}
}
20、OAuth2
20.1、基于gitee實作快速登陸
- 依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<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.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- yaml配置
spring:
security:
oauth2:
client:
registration:
gitee:
client-id: daf0946aa26c28a661bbfb5bdb89357f8b90e121b53d98ba8b383afd348904e0
client-secret: 1021637c412d22bd2b706f15c0c5c9dad6df859d9f4a01e36b93575b50d98c5c
authorization-grant-type: authorization_code
redirect-uri: http://localhost:8080/login/oauth2/code/gitee
client-name: gitee
provider:
gitee:
authorization-uri: https://gitee.com/oauth/authorize
token-uri: https://gitee.com/oauth/token
user-info-uri: https://gitee.com/api/v5/user
user-name-attribute: name
- security配置類
package com.wanqi.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.web.SecurityFilterChain;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/8
* @Author wandaren
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
)
.oauth2Login();
return http.build();
}
@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
return new InMemoryClientRegistrationRepository(this.giteeClientRegistration());
}
private ClientRegistration giteeClientRegistration() {
return ClientRegistration.withRegistrationId("gitee")
.clientId("daf0946aa26c28a661bbfb5bdb89357f8b90e121b53d98ba8b383afd348904e0")
.clientSecret("1021637c412d22bd2b706f15c0c5c9dad6df859d9f4a01e36b93575b50d98c5c")
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("http://localhost:8080/login/oauth2/code/gitee")
.authorizationUri("https://gitee.com/oauth/authorize")
.tokenUri("https://gitee.com/oauth/token")
.userInfoUri("https://gitee.com/api/v5/user")
.userNameAttributeName("name")
.clientName("gitee")
.build();
}
}
(1)client_id、client-secret替換為Gitee獲取的資料
(2)authorization-grant-type:授權模式使用授權碼模式
(3)redirect-uri:回呼地址,填寫的與Gitee上申請的一致
(4)client-name:客戶端名稱,可以在登錄選擇頁面上顯示
Gitee的OAuth登錄需要自定義provider,Spring Security OAuth提供了配置的方式來實作,
(5)authorization-uri:授權服務器地址
(6)token-uri:授權服務器獲取token地址
(7)user-info-uri:授權服務器獲取用戶資訊的地址
(8)user-name-attribute:用戶資訊中的用戶名屬性
- gitee創建第三方應用

20.2、基于記憶體搭建授權服務器
- 引入依賴,版本使用
2.2.5.RELEASE
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 配置security
package com.wanqi.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/8
* @Author wandaren
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean(value = "https://www.cnblogs.com/wandaren/archive/2022/10/29/bcryptPasswordEncoder")
public PasswordEncoder bcryptPasswordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
public UserDetailsService inMemoryUsers(@Qualifier("bcryptPasswordEncoder") PasswordEncoder encoder) {
UserDetails admin = User.withUsername("admin")
.password(encoder.encode("123"))
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(admin);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//開啟權限驗證
http.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
.mvcMatchers("/index").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin().and()
//注銷
.logout(logout -> {
logout
//指定默認注銷url,默認請求方式GET
//.logoutUrl("/logout")
.logoutRequestMatcher(
//自定義注銷url
new OrRequestMatcher(
new AntPathRequestMatcher("/aa", "GET")))
//注銷成功后跳轉頁面
//.logoutSuccessUrl("/toLogin")
//前后端分離時代自定義注銷登錄處理器
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Map<String, Object> map = new HashMap<>();
map.put("msg", "注銷成功");
map.put("code", HttpStatus.OK.value());
map.put("authentication", authentication);
String s = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(s);
}
})
//銷毀session,默認為true
.invalidateHttpSession(true)
//清除認證資訊,默認為true
.clearAuthentication(true);
})
//指定UserDetailsService來切換認證資訊不同的存盤方式(資料源)
.userDetailsService(inMemoryUsers(bcryptPasswordEncoder()))
//禁止csrf跨站請求保護
.csrf().disable();
}
}
- 自定義 授權服務器配置
package com.wanqi.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import javax.annotation.Resource;
/**
* @Description 自定義 授權服務器配置
* @Version 1.0.0
* @Date 2022/9/8
* @Author wandaren
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Resource
private PasswordEncoder bcryptPasswordEncoder;
/**
* 用來配置授權服務器可以為那些客戶端授權
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("app")
//注冊客戶端密鑰
.secret(bcryptPasswordEncoder.encode("secret"))
.redirectUris("https://cn.bing.com")
//授權碼模式,5選一
.authorizedGrantTypes("authorization_code")
//.authorizedGrantTypes("client_credentials", "password", "implicit", "authorization_code", "refresh_token");
//令牌容許獲取的資源權限
.scopes("read:user")
;
}
}
請求是否同意授權:http://127.0.0.1:8080/oauth/authorize?client_id=app&redirect_uri=https://cn.bing.com&response_type=code
獲取令牌:http://app:secret@localhost:8080/oauth/token
- 獲取令牌

- 重繪令牌

- 修改自定義 授權服務器配置
.authorizedGrantTypes("authorization_code","refresh_token")
@Override
publicvoidconfigure(AuthorizationServerEndpointsConfigurerendpoints)throwsException{
endpoints.userDetailsService(userDetailsService);
}
package com.wanqi.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import javax.annotation.Resource;
/**
* @Description 自定義 授權服務器配置
* @Version 1.0.0
* @Date 2022/9/8
* @Author wandaren
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Resource
private PasswordEncoder bcryptPasswordEncoder;
@Resource
private UserDetailsService userDetailsService;
/**
* 用來配置授權服務器可以為那些客戶端授權
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("app")
//注冊客戶端密鑰
.secret(bcryptPasswordEncoder.encode("secret"))
.redirectUris("https://cn.bing.com")
/* 授權碼模式:client_credentials
* 重繪令牌:refresh_token
* */
.authorizedGrantTypes("authorization_code","refresh_token")
//.authorizedGrantTypes("client_credentials", "password", "implicit", "authorization_code", "refresh_token");
//令牌容許獲取的資源權限
.scopes("read:user")
;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.userDetailsService(userDetailsService);
}
}
20.3、基于redis搭建授權服務器
1、引入依賴,spirng-boot版本2.2.5.RELEASE
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2、配置redis
spring:
redis:
port: 6379
host: 172.16.156.139
password: qifeng
database: 1 #指定資料庫
3、Security配置類
package com.wanqi.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/8
* @Author wandaren
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean(value = "https://www.cnblogs.com/wandaren/archive/2022/10/29/bcryptPasswordEncoder")
public PasswordEncoder bcryptPasswordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(inMemoryUsers(bcryptPasswordEncoder()));
}
@Override
@Bean
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
@Bean
public UserDetailsService inMemoryUsers(@Qualifier("bcryptPasswordEncoder") PasswordEncoder encoder) {
UserDetails admin = User.withUsername("admin")
.password(encoder.encode("123"))
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(admin);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//開啟權限驗證
http.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
.mvcMatchers("/toLogin").permitAll()
.mvcMatchers("/index").permitAll()
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin().and()
//注銷
.logout(logout -> {
logout
//指定默認注銷url,默認請求方式GET
//.logoutUrl("/logout")
.logoutRequestMatcher(
//自定義注銷url
new OrRequestMatcher(
new AntPathRequestMatcher("/aa", "GET")))
//注銷成功后跳轉頁面
//.logoutSuccessUrl("/toLogin")
//前后端分離時代自定義注銷登錄處理器
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Map<String, Object> map = new HashMap<>();
map.put("msg", "注銷成功");
map.put("code", HttpStatus.OK.value());
map.put("authentication", authentication);
String s = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(s);
}
})
//銷毀session,默認為true
.invalidateHttpSession(true)
//清除認證資訊,默認為true
.clearAuthentication(true);
})
//指定UserDetailsService來切換認證資訊不同的存盤方式(資料源)
.userDetailsService(inMemoryUsers(bcryptPasswordEncoder()))
//禁止csrf跨站請求保護
.csrf().disable();
}
}
4、自定義 授權服務器配置
package com.wanqi.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import javax.annotation.Resource;
/**
* @Description 自定義 授權服務器配置
* @Version 1.0.0
* @Date 2022/9/8
* @Author wandaren
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Resource
private PasswordEncoder bcryptPasswordEncoder;
@Resource
private UserDetailsService userDetailsService;
@Autowired
private AuthenticationManager authenticationManager ;
@Autowired
private RedisConnectionFactory redisConnectionFactory ;
/**
* 用來配置授權服務器可以為那些客戶端授權
*
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("app")
//注冊客戶端密鑰
.secret(bcryptPasswordEncoder.encode("secret"))
.redirectUris("https://cn.bing.com")
/* 授權碼模式:client_credentials
* 簡化模式:implicit
* 密碼模式:password
* 客戶端模式:client_credentials
* 重繪令牌:refresh_token
* */
.authorizedGrantTypes("authorization_code", "refresh_token")
//.authorizedGrantTypes("client_credentials", "password", "implicit", "authorization_code", "refresh_token");
//令牌容許獲取的資源權限
.scopes("read:user")
// token的有效期
.accessTokenValiditySeconds(24*3600)
// refresh_token的有效期
.refreshTokenValiditySeconds(24*7*3600);
super.configure(clients);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.userDetailsService(userDetailsService)
.authenticationManager(authenticationManager)
.tokenStore(redisTokenStore());
}
public TokenStore redisTokenStore(){
return new RedisTokenStore(redisConnectionFactory) ;
}
/*
* 請求是否同意授權:http://127.0.0.1:8080/oauth/authorize?client_id=app&redirect_uri=https://cn.bing.com&response_type=code
* 獲取令牌:http://app:secret@localhost:8080/oauth/token
*
*/
}
20.4、基于redis搭建資源服務器
1、匯入依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2、redis配置
spring:
redis:
port: 6379
host: 172.16.156.139
password: qifeng
database: 1 #指定資料庫
server:
port: 8081
3、自定義資源服務器配置
package com.wanqi.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
/**
* @Description 自定義資源服務器配置
* @Version 1.0.0
* @Date 2022/9/8
* @Author wandaren
*/
@Configuration
@EnableResourceServer
public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {
@Autowired
private RedisConnectionFactory redisConnectionFactory ;
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(redisTokenStore());
super.configure(resources);
}
public TokenStore redisTokenStore(){
return new RedisTokenStore(redisConnectionFactory) ;
}
}
4、模擬資源
package com.wanqi.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/8
* @Author wandaren
*/
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "hello";
}
}
- http://127.0.0.1:8081/hello?access_token=cfa1e9c4-9501-466a-9b87-9ba415bd0821

20.5、基于jwt搭建授權服務器
1、依賴匯入,版本2.2.5.RELEASE
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2、Security配置
package com.wanqi.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/9/8
* @Author wandaren
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean(value = "https://www.cnblogs.com/wandaren/archive/2022/10/29/bcryptPasswordEncoder")
public PasswordEncoder bcryptPasswordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(inMemoryUsers(bcryptPasswordEncoder()));
}
@Override
@Bean
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
@Bean
public UserDetailsService inMemoryUsers(@Qualifier("bcryptPasswordEncoder") PasswordEncoder encoder) {
UserDetails admin = User.withUsername("admin")
.password(encoder.encode("123"))
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(admin);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//開啟權限驗證
http.authorizeRequests()
//permitAll直接放行,必須在anyRequest().authenticated()前面
//anyRequest所有請求都需要認證
.anyRequest().authenticated()
.and()
//使用form表單驗證
.formLogin().and()
//注銷
.logout(logout -> {
logout
//指定默認注銷url,默認請求方式GET
//.logoutUrl("/logout")
.logoutRequestMatcher(
//自定義注銷url
new OrRequestMatcher(
new AntPathRequestMatcher("/aa", "GET")))
//注銷成功后跳轉頁面
//.logoutSuccessUrl("/toLogin")
//前后端分離時代自定義注銷登錄處理器
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Map<String, Object> map = new HashMap<>();
map.put("msg", "注銷成功");
map.put("code", HttpStatus.OK.value());
map.put("authentication", authentication);
String s = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(s);
}
})
//銷毀session,默認為true
.invalidateHttpSession(true)
//清除認證資訊,默認為true
.clearAuthentication(true);
})
//指定UserDetailsService來切換認證資訊不同的存盤方式(資料源)
.userDetailsService(inMemoryUsers(bcryptPasswordEncoder()))
//禁止csrf跨站請求保護
.csrf().disable();
}
}
3、jwt內容增強
package com.wanqi.config;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import sun.jvm.hotspot.opto.HaltNode;
import java.util.HashMap;
import java.util.Map;
/**
* @Description jwt內容增強
* @Version 1.0.0
* @Date 2022/9/9
* @Author wandaren
*/
public class JwtTokenEnhancer implements TokenEnhancer {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
Map<String,Object> map = new HashMap<>();
map.put("test", "jwt內容增強");
((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(map);
return accessToken;
}
}
4、授權服務器配置
package com.wanqi.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import java.util.ArrayList;
import java.util.List;
@Configuration
// 開啟授權服務器的功能
@EnableAuthorizationServer
public class JWTAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
/**
* 添加第三方的客戶端
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
// 第三方客戶端的名稱
.withClient("app")
// 第三方客戶端的密鑰
.secret(passwordEncoder.encode("secret"))
.redirectUris("https://cn.bing.com")
/* 授權碼模式:client_credentials
* 簡化模式:implicit
* 密碼模式:password
* 客戶端模式:client_credentials
* 重繪令牌:refresh_token
* */
.authorizedGrantTypes("authorization_code", "refresh_token")
//第三方客戶端的授權范圍
.scopes("all")
// token的有效期
.accessTokenValiditySeconds(24 * 3600)
// refresh_token的有效期
.refreshTokenValiditySeconds(24 * 7 * 3600);
super.configure(clients);
}
/**
* 配置驗證管理器,UserdetailService
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
super.configure(endpoints);
//配置jwt增強內容
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
List<TokenEnhancer> list = new ArrayList<>();
list.add(jwtTokenEnhancer());
list.add(jwtAccessTokenConverter());
tokenEnhancerChain.setTokenEnhancers(list);
endpoints.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService)
//設定token 存盤策略
.tokenStore(jwtTokenStore())
.accessTokenConverter(jwtAccessTokenConverter())
.tokenEnhancer(tokenEnhancerChain);
}
/**
* jwtTokenStore
*
* @return
*/
@Bean
public TokenStore jwtTokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
tokenConverter.setSigningKey("name");
return tokenConverter;
}
@Bean
JwtTokenEnhancer jwtTokenEnhancer() {
return new JwtTokenEnhancer();
}
}
20.6、基于jwt搭建資源服務器
1、依賴匯入,版本2.2.5.RELEASE
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2、資源服務器配置
package com.wanqi.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
/**
* @Description 自定義資源服務器配置
* @Version 1.0.0
* @Date 2022/9/8
* @Author wandaren
*/
@Configuration
@EnableResourceServer
public class JWTResourceServerConfigurer extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
super.configure(resources);
resources.resourceId("app")
.tokenStore(jwtTokenStore())
.stateless(true);
}
@Bean
public TokenStore jwtTokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
tokenConverter.setSigningKey("name");
return tokenConverter;
}
}

- 決議jwt令牌https://jwt.io/

- 請求資源服務器
- http://127.0.0.1:8081/hello?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NjI3NzU0MjMsInVzZXJfbmFtZSI6ImFkbWluIiwiYXV0aG9yaXRpZXMiOlsiUk9MRV9BRE1JTiIsIlJPTEVfVVNFUiJdLCJqdGkiOiI2MDhmYWIwOS1jN2NkLTQyOWItYjVhMy0yZmM3YzI1NDU3ZmQiLCJjbGllbnRfaWQiOiJhcHAiLCJzY29wZSI6WyJhbGwiXX0.NpwTkYDmtrNZRNFG5WIvxZqH9FBXhPHSojcCi7GiKfA
- 請求頭使用Authorization:Bearer XXXXXX或者使用引數access_token=XXXXXXX

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/523084.html
標籤:其他

