溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring Security基于json登錄的方法

發(fā)布時間:2020-08-19 11:01:21 來源:億速云 閱讀:306 作者:小新 欄目:開發(fā)技術

小編給大家分享一下Spring Security基于json登錄的方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

主要是重寫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

創(chuàng)建自定義身份過濾類

寫json登錄之前先看一下源碼,了解一下它是如何表單登錄的

在idea連按下shift鍵,搜索UsernamePasswordAuthenticationFilter類

Spring Security基于json登錄的方法

進入后再按Ctrl+F12可以查看該類的所有方法

Spring Security基于json登錄的方法

進入方法

Spring Security基于json登錄的方法

我們只需要在request.getParameter()那里重寫一下不就可以實現(xiàn)json登陸

重寫attemptAuthentication(HttpServletRequestrequest,HttpServletResponseresponse)方法

只需要復制父類的方法,多加一個判斷json的方法。就能同時支持key-value形式可json形式的參數(shù)了

Spring Security基于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的形式傳遞參數(shù)
    if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
      String username = null;
      String password = null;
      //將傳入的json數(shù)據(jù)轉換成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);
  }
}

創(chuàng)建SecurityConfig配置類

Spring Security基于json登錄的方法

注:自定義的過濾類和security原來那個表單登陸過濾設置是分開的

體現(xiàn)在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();
    //將自定義的過濾器加進來,第二參數(shù)表示加到usernamePasswordAuthenticationFilter所在的位置
    http.addFilterAt(myAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
  }

  @Bean
  MyAuthenticationFilter myAuthenticationFilter() throws Exception{
    MyAuthenticationFilter filter = new MyAuthenticationFilter();
    filter.setAuthenticationManager(authenticationManagerBean());
    return filter;

  }
}

創(chuàng)建Controller

@RestController
public class HelloController {
  @GetMapping("/hello")
  public String hello(){
    return "hello security";
  }
}

Spring Security基于json登錄的方法

Spring Security基于json登錄的方法

Spring Security基于json登錄的方法

上是Spring Security基于json登錄的方法的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI