Spring Security是一種基於Spring框架的安全選項,在Spring Boot應用程序中支持對應用程序進行身份驗證和授權。Spring Security 5.5.0於2021年6月發布,這個版本引入了許多新特性和重大變化,其中一些經驗在Spring Security 6.0中得以發揚光大。
一、Web安全
一個Web應用程序通常由許多不同的Web資源組成,包括靜態文件、視圖模板、控制器和RESTful服務。Spring Security 6.0 提供了基於路徑和基於方法的安全性,以保護應用程序中的每個資源。
首先,我們需要在pom.xml中添加以下依賴項:
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>6.0.0</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>6.0.0</version> </dependency>
我們定義一個WebSecurityConfiguration以嚮應用程序添加基於路徑的安全性。在此示例中,我們定義了基本身份驗證的用戶名和密碼。
@Configuration @EnableWebSecurity public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/**").permitAll() .and().httpBasic(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("{noop}admin").roles("ADMIN") .and() .withUser("user").password("{noop}password").roles("USER"); } }
以上代碼定義了兩個用戶admin和user,其中admin用戶擁有ROLE_ADMIN角色,而user用戶沒有特殊的角色。使用antMatchers()方法定義了訪問特定URL時所需的角色。在這種情況下,我們定義了/admin/**URL需要ADMIN角色來訪問,其他URL可以從任何角色訪問。HTTP基本身份驗證還被註冊以保護路徑。
二、OAuth2.0安全
OAuth 2.0是常用的API安全協議,允許用戶授權第三方應用程序訪問他們在其他資源伺服器上的數據。Spring Security 6.0 提供了一個OAuth 2.0客戶端和服務端的實現。
我們需要在pom.xml中添加以下依賴項:
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-oauth2-client</artifactId> <version>6.0.0</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-oauth2-jose</artifactId> <version>6.0.0</version> </dependency>
現在我們可以定義一個OAuth2認證伺服器,它將接收來自客戶端的請求,並確認用戶身份認證。
@Configuration @EnableAuthorizationServer public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { private final JwtAccessTokenConverter jwtAccessTokenConverter; public AuthorizationServerConfiguration(JwtAccessTokenConverter jwtAccessTokenConverter) { this.jwtAccessTokenConverter = jwtAccessTokenConverter; } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("my-client") .secret("{noop}secret") .authorizedGrantTypes("client_credentials") .scopes("read", "write") .accessTokenValiditySeconds(3600); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.tokenStore(new JwtTokenStore(jwtAccessTokenConverter)); } }
在這裡,我們定義了一個名為my-client的客戶端,該客戶端使用client_credentials授予類型獲得OAuth 2.0令牌。還定義了讀取和寫入哪些作用域,並設置令牌有效期為3600秒。最終,我們將JWT令牌存儲在JwtTokenStore中。
三、全局安全性
Spring Security 6.0引入了全局安全性特性,通過默認全局安全配置保護應用程序的每個資源。全局安全配置成為應用程序所有端點的默認安全配置,從而提供了內置的安全性。
我們需要在pom.xml中添加以下依賴項:
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>6.0.0</version> </dependency>
我們還需要定義一個全局安全配置類。
@Configuration public class GlobalSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and().formLogin() .and().httpBasic(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("{noop}admin").roles("ADMIN") .and() .withUser("user").password("{noop}password").roles("USER"); } }
在這裡,我們定義了全局身份驗證和授權,默認情況下所有請求都需要經過身份驗證。我們也定義了兩個用戶,admin和user用戶,以及他們的角色和密碼。
四、個性化登錄頁面
Spring Security 6.0支持自定義登錄頁面,該頁面可以替換默認登錄頁面。我們可以通過配置添加自己的loginPage()方法來實現這個目標。
@Configuration @EnableWebSecurity public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .successHandler(customAuthenticationSuccessHandler) .permitAll() .and() .logout().permitAll(); } }
在這裡,我們定義了一個loginPage()方法,將使用自定義登錄頁面作為登錄頁面。我們還定義了一個自定義登錄成功處理程序,該處理程序需要繼承AuthenticationSuccessHandler以提供自己的身份驗證成功邏輯。
五、結語
Spring Security 6.0是一個非常有用和強大的安全性框架,它提供了全面的安全性選項,包括Web安全,OAuth2.0安全和全局安全性。在我們的應用程序中使用Spring Security 6.0可以保護我們的資源免受未經授權的訪問和攻擊。
完整代碼示例,可以在Github上進行查看。
原創文章,作者:FOCN,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/141408.html