最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Spring Security如何配置JSON登錄

 更新時(shí)間:2017年07月30日 11:57:20   作者:zerouwar  
這篇文章主要介紹了詳解Spring Security如何配置JSON登錄,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

spring security用了也有一段時(shí)間了,弄過(guò)異步和多數(shù)據(jù)源登錄,也看過(guò)一點(diǎn)源碼,最近弄rest,然后順便搭oauth2,前端用json來(lái)登錄,沒想到spring security默認(rèn)居然不能獲取request中的json數(shù)據(jù),谷歌一波后只在stackoverflow找到一個(gè)回答比較靠譜,還是得要重寫filter,于是在這里填一波坑。

準(zhǔn)備工作

基本的spring security配置就不說(shuō)了,網(wǎng)上一堆例子,只要弄到普通的表單登錄和自定義UserDetailsService就可以。因?yàn)樾枰貙慒ilter,所以需要對(duì)spring security的工作流程有一定的了解,這里簡(jiǎn)單說(shuō)一下spring security的原理。


spring security 是基于javax.servlet.Filter的,因此才能在spring mvc(DispatcherServlet基于Servlet)前起作用。

  1. UsernamePasswordAuthenticationFilter:實(shí)現(xiàn)Filter接口,負(fù)責(zé)攔截登錄處理的url,帳號(hào)和密碼會(huì)在這里獲取,然后封裝成Authentication交給AuthenticationManager進(jìn)行認(rèn)證工作
  2. Authentication:貫穿整個(gè)認(rèn)證過(guò)程,封裝了認(rèn)證的用戶名,密碼和權(quán)限角色等信息,接口有一個(gè)boolean isAuthenticated()方法來(lái)決定該Authentication認(rèn)證成功沒;
  3. AuthenticationManager:認(rèn)證管理器,但本身并不做認(rèn)證工作,只是做個(gè)管理者的角色。例如默認(rèn)實(shí)現(xiàn)ProviderManager會(huì)持有一個(gè)AuthenticationProvider數(shù)組,把認(rèn)證工作交給這些AuthenticationProvider,直到有一個(gè)AuthenticationProvider完成了認(rèn)證工作。
  4. AuthenticationProvider:認(rèn)證提供者,默認(rèn)實(shí)現(xiàn),也是最常使用的是DaoAuthenticationProvider。我們?cè)谂渲脮r(shí)一般重寫一個(gè)UserDetailsService來(lái)從數(shù)據(jù)庫(kù)獲取正確的用戶名密碼,其實(shí)就是配置了DaoAuthenticationProvider的UserDetailsService屬性,DaoAuthenticationProvider會(huì)做帳號(hào)和密碼的比對(duì),如果正常就返回給AuthenticationManager一個(gè)驗(yàn)證成功的Authentication

看UsernamePasswordAuthenticationFilter源碼里的obtainUsername和obtainPassword方法只是簡(jiǎn)單地調(diào)用request.getParameter方法,因此如果用json發(fā)送用戶名和密碼會(huì)導(dǎo)致DaoAuthenticationProvider檢查密碼時(shí)為空,拋出BadCredentialsException。

/**
   * Enables subclasses to override the composition of the password, such as by
   * including additional values and a separator.
   * <p>
   * This might be used for example if a postcode/zipcode was required in addition to
   * the password. A delimiter such as a pipe (|) should be used to separate the
   * password and extended value(s). The <code>AuthenticationDao</code> will need to
   * generate the expected password in a corresponding manner.
   * </p>
   *
   * @param request so that request attributes can be retrieved
   *
   * @return the password that will be presented in the <code>Authentication</code>
   * request token to the <code>AuthenticationManager</code>
   */
  protected String obtainPassword(HttpServletRequest request) {
    return request.getParameter(passwordParameter);
  }

  /**
   * Enables subclasses to override the composition of the username, such as by
   * including additional values and a separator.
   *
   * @param request so that request attributes can be retrieved
   *
   * @return the username that will be presented in the <code>Authentication</code>
   * request token to the <code>AuthenticationManager</code>
   */
  protected String obtainUsername(HttpServletRequest request) {
    return request.getParameter(usernameParameter);
  }

重寫UsernamePasswordAnthenticationFilter

上面UsernamePasswordAnthenticationFilter的obtainUsername和obtainPassword方法的注釋已經(jīng)說(shuō)了,可以讓子類來(lái)自定義用戶名和密碼的獲取工作。但是我們不打算重寫這兩個(gè)方法,而是重寫它們的調(diào)用者attemptAuthentication方法,因?yàn)閖son反序列化畢竟有一定消耗,不會(huì)反序列化兩次,只需要在重寫的attemptAuthentication方法中檢查是否json登錄,然后直接反序列化返回Authentication對(duì)象即可。這樣我們沒有破壞原有的獲取流程,還是可以重用父類原有的attemptAuthentication方法來(lái)處理表單登錄。

/**
 * AuthenticationFilter that supports rest login(json login) and form login.
 * @author chenhuanming
 */
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

  @Override
  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

    //attempt Authentication when Content-Type is json
    if(request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)
        ||request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)){

      //use jackson to deserialize json
      ObjectMapper mapper = new ObjectMapper();
      UsernamePasswordAuthenticationToken authRequest = null;
      try (InputStream is = request.getInputStream()){
        AuthenticationBean authenticationBean = mapper.readValue(is,AuthenticationBean.class);
        authRequest = new UsernamePasswordAuthenticationToken(
            authenticationBean.getUsername(), authenticationBean.getPassword());
      }catch (IOException e) {
        e.printStackTrace();
        new UsernamePasswordAuthenticationToken(
            "", "");
      }finally {
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
      }
    }

    //transmit it to UsernamePasswordAuthenticationFilter
    else {
      return super.attemptAuthentication(request, response);
    }
  }
}

封裝的AuthenticationBean類,用了lombok簡(jiǎn)化代碼(lombok幫我們寫getter和setter方法而已)

@Getter
@Setter
public class AuthenticationBean {
  private String username;
  private String password;
}

WebSecurityConfigurerAdapter配置

重寫Filter不是問(wèn)題,主要是怎么把這個(gè)Filter加到spring security的眾多filter里面。

@Override
protected void configure(HttpSecurity http) throws Exception {
  http
      .cors().and()
      .antMatcher("/**").authorizeRequests()
      .antMatchers("/", "/login**").permitAll()
      .anyRequest().authenticated()
      //這里必須要寫formLogin(),不然原有的UsernamePasswordAuthenticationFilter不會(huì)出現(xiàn),也就無(wú)法配置我們重新的UsernamePasswordAuthenticationFilter
      .and().formLogin().loginPage("/")
      .and().csrf().disable();

  //用重寫的Filter替換掉原有的UsernamePasswordAuthenticationFilter
  http.addFilterAt(customAuthenticationFilter(),
  UsernamePasswordAuthenticationFilter.class);
}

//注冊(cè)自定義的UsernamePasswordAuthenticationFilter
@Bean
CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
  CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
  filter.setAuthenticationSuccessHandler(new SuccessHandler());
  filter.setAuthenticationFailureHandler(new FailureHandler());
  filter.setFilterProcessesUrl("/login/self");

  //這句很關(guān)鍵,重用WebSecurityConfigurerAdapter配置的AuthenticationManager,不然要自己組裝AuthenticationManager
  filter.setAuthenticationManager(authenticationManagerBean());
  return filter;
}

題外話,如果搭自己的oauth2的server,需要讓spring security oauth2共享同一個(gè)AuthenticationManager(源碼的解釋是這樣寫可以暴露出這個(gè)AuthenticationManager,也就是注冊(cè)到spring ioc)

@Override
@Bean // share AuthenticationManager for web and oauth
public AuthenticationManager authenticationManagerBean() throws Exception {
  return super.authenticationManagerBean();
}

至此,spring security就支持表單登錄和異步j(luò)son登錄了。

參考來(lái)源

stackoverflow的問(wèn)答

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • IDEA使用Lombok簡(jiǎn)化POJO代碼的示例

    IDEA使用Lombok簡(jiǎn)化POJO代碼的示例

    今天小編就為大家分享一篇關(guān)于IDEA使用Lombok簡(jiǎn)化POJO代碼的示例,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-01-01
  • 為什么SpringBoot的jar可以直接運(yùn)行

    為什么SpringBoot的jar可以直接運(yùn)行

    這篇文章主要介紹了為什么SpringBoot的jar可以直接運(yùn)行,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • Java中的線程私有變量ThreadLocal詳解

    Java中的線程私有變量ThreadLocal詳解

    這篇文章主要介紹了Java中的線程私有變量ThreadLocal詳解,ThreadLoalMap是ThreadLocal中的一個(gè)靜態(tài)內(nèi)部類,類似HashMap的數(shù)據(jù)結(jié)構(gòu),但并沒有實(shí)現(xiàn)Map接口,需要的朋友可以參考下
    2023-08-08
  • Java獲取此次請(qǐng)求URL以及服務(wù)器根路徑的方法

    Java獲取此次請(qǐng)求URL以及服務(wù)器根路徑的方法

    這篇文章主要介紹了Java獲取此次請(qǐng)求URL以及服務(wù)器根路徑的方法,需要的朋友可以參考下
    2015-08-08
  • 深入學(xué)習(xí)java內(nèi)存化和函數(shù)式協(xié)同

    深入學(xué)習(xí)java內(nèi)存化和函數(shù)式協(xié)同

    這篇文章主要介紹了深入學(xué)習(xí)java內(nèi)存化和函數(shù)式協(xié)同,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,,需要的朋友可以參考下
    2019-06-06
  • SpringBoot整合分布式鎖redisson的示例代碼

    SpringBoot整合分布式鎖redisson的示例代碼

    這篇文章主要介紹了SpringBoot整合分布式鎖redisson,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-02-02
  • java類與對(duì)象案例之打字游戲

    java類與對(duì)象案例之打字游戲

    這篇文章主要為大家詳細(xì)介紹了java類與對(duì)象案例之打字游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-07-07
  • java制作簡(jiǎn)單驗(yàn)證碼功能

    java制作簡(jiǎn)單驗(yàn)證碼功能

    這篇文章主要為大家詳細(xì)介紹了java制作簡(jiǎn)單驗(yàn)證碼功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-11-11
  • Java實(shí)現(xiàn)日志文件監(jiān)聽并讀取相關(guān)數(shù)據(jù)的方法實(shí)踐

    Java實(shí)現(xiàn)日志文件監(jiān)聽并讀取相關(guān)數(shù)據(jù)的方法實(shí)踐

    本文主要介紹了Java實(shí)現(xiàn)日志文件監(jiān)聽并讀取相關(guān)數(shù)據(jù)的方法實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • java中switch case語(yǔ)句需要加入break的原因解析

    java中switch case語(yǔ)句需要加入break的原因解析

    這篇文章主要介紹了java中switch case語(yǔ)句需要加入break的原因解析的相關(guān)資料,需要的朋友可以參考下
    2017-07-07

最新評(píng)論

玉门市| 开鲁县| 玉山县| 徐闻县| 高邮市| 甘孜县| 株洲县| 西乡县| 桐柏县| 德钦县| 嘉善县| 信阳市| 三门峡市| 措勤县| 红原县| 忻城县| 乐陵市| 敦化市| 清河县| 安西县| 靖西县| 鲁山县| 星座| 阆中市| 平舆县| 和龙市| 松原市| 广汉市| 高邮市| 大邑县| 兴安盟| 九龙坡区| 甘洛县| 杭锦后旗| 武宣县| 自贡市| 女性| 邵东县| 临泽县| 廉江市| 水城县|