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

詳解spring security 配置多個AuthenticationProvider

 更新時間:2017年05月11日 09:56:13   作者:暮夜望日  
這篇文章主要介紹了詳解spring security 配置多個AuthenticationProvider ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

前言

發(fā)現(xiàn)很少關(guān)于spring security的文章,基本都是入門級的,配個UserServiceDetails或者配個路由控制就完事了,而且很多還是xml配置,國內(nèi)通病...so,本文里的配置都是java配置,不涉及xml配置,事實上我也不會xml配置

spring security的大體介紹

spring security本身如果只是說配置,還是很簡單易懂的(我也不知道網(wǎng)上說spring security難,難在哪里),簡單不需要特別的功能,一個WebSecurityConfigurerAdapter的實現(xiàn),然后實現(xiàn)UserServiceDetails就是簡單的數(shù)據(jù)庫驗證了,這個我就不說了。

spring security大體上是由一堆Filter(所以才能在spring mvc前攔截請求)實現(xiàn)的,F(xiàn)ilter有幾個,登出Filter(LogoutFilter),用戶名密碼驗證Filter(UsernamePasswordAuthenticationFilter)之類的,F(xiàn)ilter再交由其他組件完成細(xì)分的功能,例如最常用的UsernamePasswordAuthenticationFilter會持有一個AuthenticationManager引用,AuthenticationManager顧名思義,驗證管理器,負(fù)責(zé)驗證的,但AuthenticationManager本身并不做具體的驗證工作,AuthenticationManager持有一個AuthenticationProvider集合,AuthenticationProvider才是做驗證工作的組件,AuthenticationManager和AuthenticationProvider的工作機(jī)制可以大概看一下這兩個的java doc,然后成功失敗都有相對應(yīng)該Handler 。大體的spring security的驗證工作流程就是這樣了。

開始配置多AuthenticationProvider

首先,寫一個內(nèi)存認(rèn)證的AuthenticationProvider,這里我簡單地寫一個只有root帳號的AuthenticationProvider

package com.scau.equipment.config.common.security.provider;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2017-05-10.
 */
@Component
public class InMemoryAuthenticationProvider implements AuthenticationProvider {
  private final String adminName = "root";
  private final String adminPassword = "root";

  //根用戶擁有全部的權(quán)限
  private final List<GrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("CAN_SEARCH"),
      new SimpleGrantedAuthority("CAN_SEARCH"),
      new SimpleGrantedAuthority("CAN_EXPORT"),
      new SimpleGrantedAuthority("CAN_IMPORT"),
      new SimpleGrantedAuthority("CAN_BORROW"),
      new SimpleGrantedAuthority("CAN_RETURN"),
      new SimpleGrantedAuthority("CAN_REPAIR"),
      new SimpleGrantedAuthority("CAN_DISCARD"),
      new SimpleGrantedAuthority("CAN_EMPOWERMENT"),
      new SimpleGrantedAuthority("CAN_BREED"));

  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if(isMatch(authentication)){
      User user = new User(authentication.getName(),authentication.getCredentials().toString(),authorities);
      return new UsernamePasswordAuthenticationToken(user,authentication.getCredentials(),authorities);
    }
    return null;
  }

  @Override
  public boolean supports(Class<?> authentication) {
    return true;
  }

  private boolean isMatch(Authentication authentication){
    if(authentication.getName().equals(adminName)&&authentication.getCredentials().equals(adminPassword))
      return true;
    else
      return false;
  }
}

support方法檢查authentication的類型是不是這個AuthenticationProvider支持的,這里我簡單地返回true,就是所有都支持,這里所說的authentication為什么會有多個類型,是因為多個AuthenticationProvider可以返回不同的Authentication。

public Authentication authenticate(Authentication authentication) throws AuthenticationException 方法就是驗證過程。

如果AuthenticationProvider返回了null,AuthenticationManager會交給下一個支持authentication類型的AuthenticationProvider處理。

 另外需要一個數(shù)據(jù)庫認(rèn)證的AuthenticationProvider,我們可以直接用spring security提供的DaoAuthenticationProvider,設(shè)置一下UserServiceDetails和PasswordEncoder就可以了

 @Bean
  DaoAuthenticationProvider daoAuthenticationProvider(){
    DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
    daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
    daoAuthenticationProvider.setUserDetailsService(userServiceDetails);
    return daoAuthenticationProvider;
  }

最后在WebSecurityConfigurerAdapter里配置一個含有以上兩個AuthenticationProvider的AuthenticationManager,依然重用spring security提供的ProviderManager

package com.scau.equipment.config.common.security;

import com.scau.equipment.config.common.security.handler.AjaxLoginFailureHandler;
import com.scau.equipment.config.common.security.handler.AjaxLoginSuccessHandler;
import com.scau.equipment.config.common.security.provider.InMemoryAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.UserDetailsManagerConfigurer;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2017/2/17.
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  UserDetailsService userServiceDetails;

  @Autowired
  InMemoryAuthenticationProvider inMemoryAuthenticationProvider;

  @Bean
  DaoAuthenticationProvider daoAuthenticationProvider(){
    DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
    daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
    daoAuthenticationProvider.setUserDetailsService(userServiceDetails);
    return daoAuthenticationProvider;
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .rememberMe().alwaysRemember(true).tokenValiditySeconds(86400).and()
        .authorizeRequests()
          .antMatchers("/","/*swagger*/**", "/v2/api-docs").permitAll()
          .anyRequest().authenticated().and()
        .formLogin()
          .loginPage("/")
          .loginProcessingUrl("/login")
          .successHandler(new AjaxLoginSuccessHandler())
          .failureHandler(new AjaxLoginFailureHandler()).and()
        .logout().logoutUrl("/logout").logoutSuccessUrl("/");
  }

  @Override
  public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/public/**", "/webjars/**", "/v2/**", "/swagger**");
  }

  @Override
  protected AuthenticationManager authenticationManager() throws Exception {
    ProviderManager authenticationManager = new ProviderManager(Arrays.asList(inMemoryAuthenticationProvider,daoAuthenticationProvider()));
    //不擦除認(rèn)證密碼,擦除會導(dǎo)致TokenBasedRememberMeServices因為找不到Credentials再調(diào)用UserDetailsService而拋出UsernameNotFoundException
    authenticationManager.setEraseCredentialsAfterAuthentication(false);
    return authenticationManager;
  }

  /**
   * 這里需要提供UserDetailsService的原因是RememberMeServices需要用到
   * @return
   */
  @Override
  protected UserDetailsService userDetailsService() {
    return userServiceDetails;
  }
}

基本上都是重用了原有的類,很多都是默認(rèn)使用的,只不過為了修改下行為而重新配置。其實如果偷懶,直接用一個UserDetailsService,在里面做各種認(rèn)證也是可以的~不過這樣就沒意思了

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

相關(guān)文章

  • Java StringBuilder類相關(guān)知識總結(jié)

    Java StringBuilder類相關(guān)知識總結(jié)

    這篇文章主要介紹了Java StringBuilder類相關(guān)知識總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-02-02
  • JAVA面試題之緩存擊穿、緩存穿透、緩存雪崩的三者區(qū)別

    JAVA面試題之緩存擊穿、緩存穿透、緩存雪崩的三者區(qū)別

    當(dāng)服務(wù)器QPS比較高,并且對數(shù)據(jù)的實時性要求不高時,往往會接入緩存以達(dá)到快速Response、降低數(shù)據(jù)庫壓力的作用,常用來做緩存的中間件如Redis等。本文主要介紹了JAVA面試時??嫉木彺鎿舸⒋┩?、雪崩場景三者區(qū)別,有興趣的小伙伴可以看一下
    2021-11-11
  • 深入理解Java8新特性之接口中的默認(rèn)方法和靜態(tài)方法

    深入理解Java8新特性之接口中的默認(rèn)方法和靜態(tài)方法

    從Java8開始,程序允許在接口中包含帶有具體實現(xiàn)的方法,使用default修飾,這類方法就是默認(rèn)方法。默認(rèn)方法在接口中可以添加多個,并且Java8提供了很多對應(yīng)的接口默認(rèn)方法,接下來讓我們一起來看看吧
    2021-11-11
  • java 根據(jù)前端返回的字段名進(jìn)行查詢數(shù)據(jù)

    java 根據(jù)前端返回的字段名進(jìn)行查詢數(shù)據(jù)

    本文介紹了如何在Java中使用SpringDataJPA實現(xiàn)動態(tài)查詢功能,以便根據(jù)前端傳遞的字段名動態(tài)構(gòu)建查詢語句,通過創(chuàng)建實體類、Repository接口、構(gòu)建動態(tài)查詢、在Service層和Controller中使用動態(tài)查詢,實現(xiàn)了前后端分離架構(gòu)中的靈活查詢需求
    2024-11-11
  • 工廠方法在Spring框架中的運用

    工廠方法在Spring框架中的運用

    這篇文章介紹了工廠方法在Spring框架中的運用,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-10-10
  • MyBatis中$和#的深入講解

    MyBatis中$和#的深入講解

    這篇文章主要給大家介紹了關(guān)于MyBatis中$和#的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • java中多線程與線程池的基本使用方法

    java中多線程與線程池的基本使用方法

    在Java中,我們可以利用多線程來最大化地壓榨CPU多核計算的能力,下面這篇文章主要給大家介紹了關(guān)于java中多線程與線程池基本使用的相關(guān)資料,需要的朋友可以參考下
    2021-09-09
  • 使用maven的profile構(gòu)建不同環(huán)境配置的方法

    使用maven的profile構(gòu)建不同環(huán)境配置的方法

    這篇文章主要介紹了使用maven的profile構(gòu)建不同環(huán)境配置的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • Java學(xué)習(xí)之如何進(jìn)行JSON解析

    Java學(xué)習(xí)之如何進(jìn)行JSON解析

    JSON(JavaScript?Object?Notation)是一種輕量級的數(shù)據(jù)交換格式,它算是JavaScript語言的一部分,與XML一樣都可以用于數(shù)據(jù)的存儲和傳輸,本文講給大家介紹如何進(jìn)行JSON解析,需要的朋友可以參考下
    2023-12-12
  • Java?ObjectMapper的使用和使用過程中遇到的問題

    Java?ObjectMapper的使用和使用過程中遇到的問題

    在Java開發(fā)中,ObjectMapper是Jackson庫的核心類,用于將Java對象序列化為JSON字符串,或者將JSON字符串反序列化為Java對象,這篇文章主要介紹了Java?ObjectMapper的使用和使用過程中遇到的問題,需要的朋友可以參考下
    2024-07-07

最新評論

海淀区| 庄河市| 庆阳市| 正镶白旗| 合水县| 海伦市| 奇台县| 乌什县| 迁安市| 治县。| 成都市| 航空| 鲁甸县| 达日县| 赣州市| 乐业县| 绥中县| 蒲城县| 桂平市| 许昌县| 海晏县| 阳谷县| 龙里县| 大港区| 隆子县| 久治县| 嘉鱼县| 平南县| 柏乡县| 晋城| 穆棱市| 汤原县| 绵竹市| 弥勒县| 武宁县| 鹰潭市| 吐鲁番市| 汉寿县| 广南县| 柯坪县| 黄骅市|