Spring Security基於json登入實現過程詳解
阿新 • • 發佈:2020-08-18
主要是重寫attemptAuthentication方法
匯入依賴
<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>
相關配置和程式碼
application.properties配置密碼
spring.security.user.name=admin
spring.security.user.password=123
建立自定義身份過濾類
寫json登入之前先看一下原始碼,瞭解一下它是如何表單登入的
在idea連按下shift鍵,搜尋UsernamePasswordAuthenticationFilter類
進入後再按Ctrl+F12可以檢視該類的所有方法
進入方法
我們只需要在request.getParameter()那裡重寫一下不就可以實現json登陸
重寫attemptAuthentication(HttpServletRequestrequest,HttpServletResponseresponse)方法
只需要複製父類的方法,多加一個判斷json的方法。就能同時支援key-value形式可json形式的引數了
public class MyAuthenticationFilter extends UsernamePasswordAuthenticationFilter { @Override public Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response) throws AuthenticationException { if(!request.getMethod().equals("POST")){ throw new AuthenticationServiceException("Authentication method not supported" + request.getMethod()); } //說明是以json的形式傳遞引數 if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) { String username = null; String password = null; //將傳入的json資料轉換成map再通過get("key")獲得 try { Map<String,String> map =new ObjectMapper().readValue(request.getInputStream(),Map.class); username = map.get("username"); password = map.get("password"); } catch (IOException e) { e.printStackTrace(); } if (username == null) { } if (password == null) { } username = username.trim(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,password); setDetails(request,authRequest); return this.getAuthenticationManager().authenticate(authRequest); } return super.attemptAuthentication(request,response); } }
建立SecurityConfig配置類
注:自定義的過濾類和security原來那個表單登陸過濾設定是分開的
體現在filter.setFilterProcessesUrl()和loginProcessingUrl
因此表單登陸和json登陸的,successHandler判斷也要分開寫,
一會下面有效果圖也可以印證這一點
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginProcessingUrl("/doLogin") .permitAll() .and() .csrf().disable(); //將自定義的過濾器加進來,第二引數表示加到usernamePasswordAuthenticationFilter所在的位置 http.addFilterAt(myAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class); } @Bean MyAuthenticationFilter myAuthenticationFilter() throws Exception{ MyAuthenticationFilter filter = new MyAuthenticationFilter(); filter.setAuthenticationManager(authenticationManagerBean()); return filter; } }
建立Controller
@RestController public class HelloController { @GetMapping("/hello") public String hello(){ return "hello security"; } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。