Spring security 自定義過濾器實現Json參數傳遞並兼容表單參數(實例代碼)
依賴
<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.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
配置安全適配類
基本配置和配置自定義過濾器
package com.study.auth.config.core; import com.study.auth.config.core.authentication.AccountAuthenticationProvider; import com.study.auth.config.core.authentication.MailAuthenticationProvider; import com.study.auth.config.core.authentication.PhoneAuthenticationProvider; import com.study.auth.config.core.filter.CustomerUsernamePasswordAuthenticationFilter; import com.study.auth.config.core.handler.CustomerAuthenticationFailureHandler; import com.study.auth.config.core.handler.CustomerAuthenticationSuccessHandler; import com.study.auth.config.core.handler.CustomerLogoutSuccessHandler; import com.study.auth.config.core.observer.CustomerUserDetailsService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; 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.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /** * @Package: com.study.auth.config * @Description: <> * @Author: milla * @CreateDate: 2020/09/04 11:27 * @UpdateUser: milla * @UpdateDate: 2020/09/04 11:27 * @UpdateRemark: <> * @Version: 1.0 */ @Slf4j @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AccountAuthenticationProvider provider; @Autowired private MailAuthenticationProvider mailProvider; @Autowired private PhoneAuthenticationProvider phoneProvider; @Autowired private CustomerUserDetailsService userDetailsService; @Autowired private CustomerAuthenticationSuccessHandler successHandler; @Autowired private CustomerAuthenticationFailureHandler failureHandler; @Autowired private CustomerLogoutSuccessHandler logoutSuccessHandler; /** * 配置攔截器保護請求 * * @param http * @throws Exception */ @Override protected void configure(HttpSecurity http) throws Exception { //配置HTTP基本身份驗證//使用自定義過濾器-兼容json和表單登錄 http.addFilterBefore(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) .httpBasic() .and().authorizeRequests() //表示訪問 /setting 這個接口,需要具備 admin 這個角色 .antMatchers("/setting").hasRole("admin") //表示剩餘的其他接口,登錄之後就能訪問 .anyRequest() .authenticated() .and() .formLogin() //定義登錄頁面,未登錄時,訪問一個需要登錄之後才能訪問的接口,會自動跳轉到該頁面 .loginPage("/noToken") //登錄處理接口-登錄時候訪問的接口地址 .loginProcessingUrl("/account/login") //定義登錄時,表單中用戶名的 key,默認為 username .usernameParameter("username") //定義登錄時,表單中用戶密碼的 key,默認為 password .passwordParameter("password") // //登錄成功的處理器 // .successHandler(successHandler) // //登錄失敗的處理器 // .failureHandler(failureHandler) //允許所有用戶訪問 .permitAll() .and() .logout() .logoutUrl("/logout") //登出成功的處理 .logoutSuccessHandler(logoutSuccessHandler) .permitAll(); //關閉csrf跨域攻擊防禦 http.csrf().disable(); } /** * 配置權限認證服務 * * @param auth * @throws Exception */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //權限校驗-隻要有一個認證通過即認為是通過的(有一個認證通過就跳出認證循環)-適用於多登錄方式的系統 // auth.authenticationProvider(provider); // auth.authenticationProvider(mailProvider); // auth.authenticationProvider(phoneProvider); //直接使用userDetailsService auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); } /** * 配置Spring Security的Filter鏈 * * @param web * @throws Exception */ @Override public void configure(WebSecurity web) throws Exception { //忽略攔截的接口 web.ignoring().antMatchers("/noToken"); } /** * 指定驗證manager * * @return * @throws Exception */ @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } /** * 註冊自定義的UsernamePasswordAuthenticationFilter * * @return * @throws Exception */ @Bean public AbstractAuthenticationProcessingFilter customAuthenticationFilter() throws Exception { AbstractAuthenticationProcessingFilter filter = new CustomerUsernamePasswordAuthenticationFilter(); filter.setAuthenticationSuccessHandler(successHandler); filter.setAuthenticationFailureHandler(failureHandler); //過濾器攔截的url要和登錄的url一致,否則不生效 filter.setFilterProcessesUrl("/account/login"); //這句很關鍵,重用WebSecurityConfigurerAdapter配置的AuthenticationManager,不然要自己組裝AuthenticationManager filter.setAuthenticationManager(authenticationManagerBean()); return filter; } }
自定義過濾器
根據ContentType是否為json進行判斷,如果是就從body中讀取參數,進行解析,並生成權限實體,進行權限認證
否則直接使用UsernamePasswordAuthenticationFilter中的方法
package com.study.auth.config.core.filter; import com.fasterxml.jackson.databind.ObjectMapper; import com.study.auth.config.core.util.AuthenticationStoreUtil; import com.study.auth.entity.bo.LoginBO; import lombok.extern.slf4j.Slf4j; import org.springframework.http.MediaType; 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 javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; /** * @Package: com.study.auth.config.core.filter * @Description: <> * @Author: milla * @CreateDate: 2020/09/11 16:04 * @UpdateUser: milla * @UpdateDate: 2020/09/11 16:04 * @UpdateRemark: <> * @Version: 1.0 */ @Slf4j public class CustomerUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter { /** * 空字符串 */ private final String EMPTY = ""; @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { //如果不是json使用自帶的過濾器獲取參數 if (!request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE) && !request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) { String username = this.obtainUsername(request); String password = this.obtainPassword(request); storeAuthentication(username, password); Authentication authentication = super.attemptAuthentication(request, response); return authentication; } //如果是json請求使用取參數邏輯 ObjectMapper mapper = new ObjectMapper(); UsernamePasswordAuthenticationToken authRequest = null; try (InputStream is = request.getInputStream()) { LoginBO account = mapper.readValue(is, LoginBO.class); storeAuthentication(account.getUsername(), account.getPassword()); authRequest = new UsernamePasswordAuthenticationToken(account.getUsername(), account.getPassword()); } catch (IOException e) { log.error("驗證失敗:{}", e); authRequest = new UsernamePasswordAuthenticationToken(EMPTY, EMPTY); } finally { setDetails(request, authRequest); Authentication authenticate = this.getAuthenticationManager().authenticate(authRequest); return authenticate; } } /** * 保存用戶名和密碼 * * @param username 帳號/郵箱/手機號 * @param password 密碼/驗證碼 */ private void storeAuthentication(String username, String password) { AuthenticationStoreUtil.setUsername(username); AuthenticationStoreUtil.setPassword(password); } }
其中會有body中的傳參問題,所以使用ThreadLocal傳遞參數
PS:枚舉類具備線程安全性
package com.study.auth.config.core.util; /** * @Package: com.study.auth.config.core.util * @Description: <使用枚舉可以保證線程安全> * @Author: milla * @CreateDate: 2020/09/11 17:48 * @UpdateUser: milla * @UpdateDate: 2020/09/11 17:48 * @UpdateRemark: <> * @Version: 1.0 */ public enum AuthenticationStoreUtil { AUTHENTICATION; /** * 登錄認證之後的token */ private final ThreadLocal<String> tokenStore = new ThreadLocal<>(); /** * 需要驗證用戶名 */ private final ThreadLocal<String> usernameStore = new ThreadLocal<>(); /** * 需要驗證的密碼 */ private final ThreadLocal<String> passwordStore = new ThreadLocal<>(); public static String getUsername() { return AUTHENTICATION.usernameStore.get(); } public static void setUsername(String username) { AUTHENTICATION.usernameStore.set(username); } public static String getPassword() { return AUTHENTICATION.passwordStore.get(); } public static void setPassword(String password) { AUTHENTICATION.passwordStore.set(password); } public static String getToken() { return AUTHENTICATION.tokenStore.get(); } public static void setToken(String token) { AUTHENTICATION.tokenStore.set(token); } public static void clear() { AUTHENTICATION.tokenStore.remove(); AUTHENTICATION.passwordStore.remove(); AUTHENTICATION.usernameStore.remove(); } }
實現UserDetailsService接口
package com.study.auth.config.core.observer; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; 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.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; /** * @Package: com.study.auth.config.core * @Description: <自定義用戶處理類> * @Author: milla * @CreateDate: 2020/09/04 13:53 * @UpdateUser: milla * @UpdateDate: 2020/09/04 13:53 * @UpdateRemark: <> * @Version: 1.0 */ @Slf4j @Component public class CustomerUserDetailsService implements UserDetailsService { @Autowired private PasswordEncoder passwordEncoder; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //測試直接使用固定賬戶代替 return User.withUsername("admin").password(passwordEncoder.encode("admin")).roles("admin", "user").build(); } }
登錄成功類
package com.study.auth.config.core.handler; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @Package: com.study.auth.config.core.handler * @Description: <登錄成功處理類> * @Author: milla * @CreateDate: 2020/09/08 17:39 * @UpdateUser: milla * @UpdateDate: 2020/09/08 17:39 * @UpdateRemark: <> * @Version: 1.0 */ @Component public class CustomerAuthenticationSuccessHandler implements AuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { HttpServletResponseUtil.loginSuccess(response); } }
登錄失敗
package com.study.auth.config.core.handler; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @Package: com.study.auth.config.core.handler * @Description: <登錄失敗操作類> * @Author: milla * @CreateDate: 2020/09/08 17:42 * @UpdateUser: milla * @UpdateDate: 2020/09/08 17:42 * @UpdateRemark: <> * @Version: 1.0 */ @Component public class CustomerAuthenticationFailureHandler implements AuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { HttpServletResponseUtil.loginFailure(response, exception); } }
登出成功類
package com.study.auth.config.core.handler; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @Package: com.study.auth.config.core.handler * @Description: <登出成功> * @Author: milla * @CreateDate: 2020/09/08 17:44 * @UpdateUser: milla * @UpdateDate: 2020/09/08 17:44 * @UpdateRemark: <> * @Version: 1.0 */ @Component public class CustomerLogoutSuccessHandler implements LogoutSuccessHandler { @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { HttpServletResponseUtil.logoutSuccess(response); } }
返回值工具類
package com.study.auth.config.core.handler; import com.alibaba.fastjson.JSON; import com.study.auth.comm.ResponseData; import com.study.auth.constant.CommonConstant; import org.springframework.http.MediaType; import org.springframework.security.core.AuthenticationException; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * @Package: com.study.auth.config.core.handler * @Description: <> * @Author: milla * @CreateDate: 2020/09/08 17:45 * @UpdateUser: milla * @UpdateDate: 2020/09/08 17:45 * @UpdateRemark: <> * @Version: 1.0 */ public final class HttpServletResponseUtil { public static void loginSuccess(HttpServletResponse resp) throws IOException { ResponseData success = ResponseData.success(); success.setMsg("login success"); response(resp, success); } public static void logoutSuccess(HttpServletResponse resp) throws IOException { ResponseData success = ResponseData.success(); success.setMsg("logout success"); response(resp, success); } public static void loginFailure(HttpServletResponse resp, AuthenticationException exception) throws IOException { ResponseData failure = ResponseData.error(CommonConstant.EX_RUN_TIME_EXCEPTION, exception.getMessage()); response(resp, failure); } private static void response(HttpServletResponse resp, ResponseData data) throws IOException { //直接輸出的時候還是需要使用UTF-8字符集 resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); PrintWriter out = resp.getWriter(); out.write(JSON.toJSONString(data)); out.flush(); } }
其他對象見Controller 層返回值的公共包裝類-避免每次都包裝一次返回-InitializingBean增強
至此,就可以傳遞Json參數瞭
到此這篇關於Spring security 自定義過濾器實現Json參數傳遞並兼容表單參數的文章就介紹到這瞭,更多相關Spring security 自定義過濾器內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- SpringBoot Security權限控制自定義failureHandler實例
- Security框架:如何使用CorsFilter解決前端跨域請求問題
- springSecurity實現簡單的登錄功能
- SpringBoot 整合Security權限控制的初步配置
- Spring Security之默認的過濾器鏈及自定義Filter操作