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

spring security自定義認(rèn)證登錄的全過程記錄

 更新時(shí)間:2017年12月22日 09:27:22   作者:CatalpaFlat  
這篇文章主要給大家介紹了關(guān)于spring security自定義認(rèn)證登錄的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。

spring security使用分類:

如何使用spring security,相信百度過的都知道,總共有四種用法,從簡到深為:

1、不用數(shù)據(jù)庫,全部數(shù)據(jù)寫在配置文件,這個(gè)也是官方文檔里面的demo;

2、使用數(shù)據(jù)庫,根據(jù)spring security默認(rèn)實(shí)現(xiàn)代碼設(shè)計(jì)數(shù)據(jù)庫,也就是說數(shù)據(jù)庫已經(jīng)固定了,這種方法不靈活,而且那個(gè)數(shù)據(jù)庫設(shè)計(jì)得很簡陋,實(shí)用性差;

3、spring security和Acegi不同,它不能修改默認(rèn)filter了,但支持插入filter,所以根據(jù)這個(gè),我們可以插入自己的filter來靈活使用;

4、暴力手段,修改源碼,前面說的修改默認(rèn)filter只是修改配置文件以替換filter而已,這種是直接改了里面的源碼,但是這種不符合OO設(shè)計(jì)原則,而且不實(shí)際,不可用。

本文主要介紹了關(guān)于spring security自定義認(rèn)證登錄的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說了,來一起看看詳細(xì)的介紹吧。

1.概要

1.1.簡介

spring security是一種基于 Spring AOP 和 Servlet 過濾器的安全框架,以此來管理權(quán)限認(rèn)證等。

1.2.spring security 自定義認(rèn)證流程

1)認(rèn)證過程

生成未認(rèn)證的AuthenticationToken                 

 ↑(獲取信息)  (根據(jù)AuthenticationToken分配provider)     
 AuthenticationFilter -> AuthenticationManager -> AuthenticationProvider
        ↓(認(rèn)證)
       UserDetails(一般查詢數(shù)據(jù)庫獲?。?
        ↓(通過)
        生成認(rèn)證成功的AuthenticationToken
         ↓(存放)
        SecurityContextHolder

2)將AuthenticationFilter加入到security過濾鏈(資源服務(wù)器中配置),如:

http.addFilterBefore(AuthenticationFilter, AbstractPreAuthenticatedProcessingFilter.class)

或者:

http.addFilterAfter(AuthenticationFilter, UsernamePasswordAuthenticationFilter.class)

2.以手機(jī)號(hào)短信登錄為例

2.1.開發(fā)環(huán)境

  • SpringBoot
  • Spring security
  • Redis

2.2.核心代碼分析

2.2.1.自定義登錄認(rèn)證流程

2.2.1.1.自定義認(rèn)證登錄Token

/**
 * 手機(jī)登錄Token
 *
 * @author : CatalpaFlat
 */
public class MobileLoginAuthenticationToken extends AbstractAuthenticationToken {
 private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
 private static final Logger logger = LoggerFactory.getLogger(MobileLoginAuthenticationToken.class.getName());
 private final Object principal;
 public MobileLoginAuthenticationToken(String mobile) {
 super(null);
 this.principal = mobile;
 this.setAuthenticated(false);
 logger.info("MobileLoginAuthenticationToken setAuthenticated ->false loading ...");
 }
 public MobileLoginAuthenticationToken(Object principal,
      Collection<? extends GrantedAuthority> authorities) {
 super(authorities);
 this.principal = principal;
 // must use super, as we override
 super.setAuthenticated(true);
 logger.info("MobileLoginAuthenticationToken setAuthenticated ->true loading ...");
 }
 @Override
 public void setAuthenticated(boolean authenticated) {
 if (authenticated) {
  throw new IllegalArgumentException(
   "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
 }
 super.setAuthenticated(false);
 }
 @Override
 public Object getCredentials() {
 return null;
 }
 @Override
 public Object getPrincipal() {
 return this.principal;
 }
 @Override
 public void eraseCredentials() {
 super.eraseCredentials();
 }
}

注:

setAuthenticated():判斷是否已認(rèn)證

  • 在過濾器時(shí),會(huì)生成一個(gè)未認(rèn)證的AuthenticationToken,此時(shí)調(diào)用的是自定義token的setAuthenticated(),此時(shí)設(shè)置為false -> 未認(rèn)證
  • 在提供者時(shí),會(huì)生成一個(gè)已認(rèn)證的AuthenticationToken,此時(shí)調(diào)用的是父類的setAuthenticated(),此時(shí)設(shè)置為true -> 已認(rèn)證

2.2.1.1.自定義認(rèn)證登錄過濾器

/**
 * 手機(jī)短信登錄過濾器
 *
 * @author : CatalpaFlat
 */
public class MobileLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
 private boolean postOnly = true;
 private static final Logger logger = LoggerFactory.getLogger(MobileLoginAuthenticationFilter.class.getName());
 @Getter
 @Setter
 private String mobileParameterName;
 public MobileLoginAuthenticationFilter(String mobileLoginUrl, String mobileParameterName,
      String httpMethod) {
 super(new AntPathRequestMatcher(mobileLoginUrl, httpMethod));
 this.mobileParameterName = mobileParameterName;
 logger.info("MobileLoginAuthenticationFilter loading ...");
 }
 @Override
 public Authentication attemptAuthentication(HttpServletRequest request,      HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
 if (postOnly && !request.getMethod().equals(HttpMethod.POST.name())) {
  throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
 }
 //get mobile
 String mobile = obtainMobile(request);
 //assemble token
 MobileLoginAuthenticationToken authRequest = new MobileLoginAuthenticationToken(mobile);

 // Allow subclasses to set the "details" property
 setDetails(request, authRequest);

 return this.getAuthenticationManager().authenticate(authRequest);
 }
 /**
 * 設(shè)置身份認(rèn)證的詳情信息
 */
 private void setDetails(HttpServletRequest request, MobileLoginAuthenticationToken authRequest) {
 authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
 }
 /**
 * 獲取手機(jī)號(hào)
 */
 private String obtainMobile(HttpServletRequest request) {
 return request.getParameter(mobileParameterName);
 }
 public void setPostOnly(boolean postOnly) {
 this.postOnly = postOnly;
 }
}

注:attemptAuthentication()方法:

  • 過濾指定的url、httpMethod
  • 獲取所需請(qǐng)求參數(shù)數(shù)據(jù)封裝生成一個(gè)未認(rèn)證的AuthenticationToken
  • 傳遞給AuthenticationManager認(rèn)證

2.2.1.1.自定義認(rèn)證登錄提供者

/**
 * 手機(jī)短信登錄認(rèn)證提供者
 *
 * @author : CatalpaFlat
 */
public class MobileLoginAuthenticationProvider implements AuthenticationProvider {
 private static final Logger logger = LoggerFactory.getLogger(MobileLoginAuthenticationProvider.class.getName());
 @Getter
 @Setter
 private UserDetailsService customUserDetailsService;
 public MobileLoginAuthenticationProvider() {
 logger.info("MobileLoginAuthenticationProvider loading ...");
 }
 /**
 * 認(rèn)證
 */
 @Override
 public Authentication authenticate(Authentication authentication) throws AuthenticationException {
 //獲取過濾器封裝的token信息
 MobileLoginAuthenticationToken authenticationToken = (MobileLoginAuthenticationToken) authentication;
 //獲取用戶信息(數(shù)據(jù)庫認(rèn)證)
 UserDetails userDetails = customUserDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());
 //不通過
 if (userDetails == null) {
  throw new InternalAuthenticationServiceException("Unable to obtain user information");
 }
 //通過
 MobileLoginAuthenticationToken authenticationResult = new MobileLoginAuthenticationToken(userDetails, userDetails.getAuthorities());
 authenticationResult.setDetails(authenticationToken.getDetails());

 return authenticationResult;
 }
 /**
 * 根據(jù)token類型,來判斷使用哪個(gè)Provider
 */
 @Override
 public boolean supports(Class<?> authentication) {
 return MobileLoginAuthenticationToken.class.isAssignableFrom(authentication);
 }
}

注:authenticate()方法

  • 獲取過濾器封裝的token信息
  • 調(diào)取UserDetailsService獲取用戶信息(數(shù)據(jù)庫認(rèn)證)->判斷通過與否
  • 通過則封裝一個(gè)新的AuthenticationToken,并返回

2.2.1.1.自定義認(rèn)證登錄認(rèn)證配置

@Configuration(SpringBeanNameConstant.DEFAULT_CUSTOM_MOBILE_LOGIN_AUTHENTICATION_SECURITY_CONFIG_BN)
public class MobileLoginAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
 private static final Logger logger = LoggerFactory.getLogger(MobileLoginAuthenticationSecurityConfig.class.getName());
 @Value("${login.mobile.url}")
 private String defaultMobileLoginUrl;
 @Value("${login.mobile.parameter}")
 private String defaultMobileLoginParameter;
 @Value("${login.mobile.httpMethod}")
 private String defaultMobileLoginHttpMethod;
 @Autowired
 private CustomYmlConfig customYmlConfig;
 @Autowired
 private UserDetailsService customUserDetailsService;
 @Autowired
 private AuthenticationSuccessHandler customAuthenticationSuccessHandler;
 @Autowired
 private AuthenticationFailureHandler customAuthenticationFailureHandler;
 public MobileLoginAuthenticationSecurityConfig() {
 logger.info("MobileLoginAuthenticationSecurityConfig loading ...");
 }
 @Override
 public void configure(HttpSecurity http) throws Exception {
 MobilePOJO mobile = customYmlConfig.getLogins().getMobile();
 String url = mobile.getUrl();
 String parameter = mobile.getParameter().getMobile();
 String httpMethod = mobile.getHttpMethod();
 MobileLoginAuthenticationFilter mobileLoginAuthenticationFilter = new MobileLoginAuthenticationFilter(StringUtils.isBlank(url) ? defaultMobileLoginUrl : url,
  StringUtils.isBlank(parameter) ? defaultMobileLoginUrl : parameter, StringUtils.isBlank(httpMethod) ? defaultMobileLoginHttpMethod : httpMethod); mobileLoginAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); mobileLoginAuthenticationFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler); mobileLoginAuthenticationFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);
 MobileLoginAuthenticationProvider mobileLoginAuthenticationProvider = new MobileLoginAuthenticationProvider(); mobileLoginAuthenticationProvider.setCustomUserDetailsService(customUserDetailsService);
 http.authenticationProvider(mobileLoginAuthenticationProvider)
  .addFilterAfter(mobileLoginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
 }
}

注:configure()方法

實(shí)例化AuthenticationFilter和AuthenticationProvider

將AuthenticationFilter和AuthenticationProvider添加到spring security中。

2.2.2.基于redis自定義驗(yàn)證碼校驗(yàn)

2.2.2.1.基于redis自定義驗(yàn)證碼過濾器

/**
 * 驗(yàn)證碼過濾器
 *
 * @author : CatalpaFlat
 */
@Component(SpringBeanNameConstant.DEFAULT_VALIDATE_CODE_FILTER_BN)
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {
 private static final Logger logger = LoggerFactory.getLogger(ValidateCodeFilter.class.getName());
 @Autowired
 private CustomYmlConfig customYmlConfig;
 @Autowired
 private RedisTemplate<Object, Object> redisTemplate;
 /**
  * 驗(yàn)證請(qǐng)求url與配置的url是否匹配的工具類
  */
 private AntPathMatcher pathMatcher = new AntPathMatcher();
 public ValidateCodeFilter() {
  logger.info("Loading ValidateCodeFilter...");
 }
 @Override
 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
         FilterChain filterChain) throws ServletException, IOException {
  String url = customYmlConfig.getLogins().getMobile().getUrl();
  if (pathMatcher.match(url, request.getRequestURI())) {
   String deviceId = request.getHeader("deviceId");
   if (StringUtils.isBlank(deviceId)) {
    throw new CustomException(HttpStatus.NOT_ACCEPTABLE.value(), "Not deviceId in the head of the request");
   }
   String codeParamName = customYmlConfig.getLogins().getMobile().getParameter().getCode();
   String code = request.getParameter(codeParamName);
   if (StringUtils.isBlank(code)) {
    throw new CustomException(HttpStatus.NOT_ACCEPTABLE.value(), "Not code in the parameters of the request");
   }
   String key = SystemConstant.DEFAULT_MOBILE_KEY_PIX + deviceId;
   SmsCodePO smsCodePo = (SmsCodePO) redisTemplate.opsForValue().get(key);
   if (smsCodePo.isExpried()){
    throw new CustomException(HttpStatus.BAD_REQUEST.value(), "The verification code has expired");
   }
   String smsCode = smsCodePo.getCode();
   if (StringUtils.isBlank(smsCode)) {
    throw new CustomException(HttpStatus.BAD_REQUEST.value(), "Verification code does not exist");
   }
   if (StringUtils.equals(code, smsCode)) {
    redisTemplate.delete(key);
    //let it go
    filterChain.doFilter(request, response);
   } else {
    throw new CustomException(HttpStatus.BAD_REQUEST.value(), "Validation code is incorrect");
   }
  }else {
   //let it go
   filterChain.doFilter(request, response);
  }
 }
}

注:doFilterInternal()

自定義驗(yàn)證碼過濾校驗(yàn)

2.2.2.2.將自定義驗(yàn)證碼過濾器添加到spring security過濾器鏈

http.addFilterBefore(validateCodeFilter, AbstractPreAuthenticatedProcessingFilter.class)

注:添加到認(rèn)證預(yù)處理過濾器前

3.測(cè)試效果

最后附上源碼地址:https://gitee.com/CatalpaFlat/springSecurity.git  (本地下載

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

  • Java上傳文件進(jìn)度條的實(shí)現(xiàn)方法(附demo源碼下載)

    Java上傳文件進(jìn)度條的實(shí)現(xiàn)方法(附demo源碼下載)

    這篇文章主要介紹了Java上傳文件進(jìn)度條的實(shí)現(xiàn)方法,可簡單實(shí)現(xiàn)顯示文件上傳比特?cái)?shù)及進(jìn)度的功能,并附帶demo源碼供讀者下載參考,需要的朋友可以參考下
    2015-12-12
  • JDK版本修改不生效的解決方法

    JDK版本修改不生效的解決方法

    本文主要介紹了在配置新電腦環(huán)境時(shí)遇到JDK版本切換失敗的問題,文中通過圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-03-03
  • SpringBoot集成Redis的實(shí)現(xiàn)示例

    SpringBoot集成Redis的實(shí)現(xiàn)示例

    這篇文章主要介紹了SpringBoot集成Redis的實(shí)現(xiàn)示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-11-11
  • java中VO的使用解析

    java中VO的使用解析

    這篇文章主要介紹了java中VO的使用解析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Java實(shí)現(xiàn)五子棋單機(jī)版

    Java實(shí)現(xiàn)五子棋單機(jī)版

    這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)五子棋單機(jī)版,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • 使用ShardingSphere-Proxy實(shí)現(xiàn)分表分庫

    使用ShardingSphere-Proxy實(shí)現(xiàn)分表分庫

    這篇文章介紹了使用ShardingSphere-Proxy實(shí)現(xiàn)分表分庫的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-02-02
  • 在Spring環(huán)境中正確關(guān)閉線程池的姿勢(shì)

    在Spring環(huán)境中正確關(guān)閉線程池的姿勢(shì)

    這篇文章主要介紹了在Spring環(huán)境中正確關(guān)閉線程池的姿勢(shì),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • Spring Boot 如何整合連接池

    Spring Boot 如何整合連接池

    這篇文章主要介紹了Spring Boot 如何整合連接池,幫助大家更好的理解和學(xué)習(xí)spring boot框架,感興趣的朋友可以了解下
    2020-11-11
  • SpringBoot?整合Security權(quán)限控制的初步配置

    SpringBoot?整合Security權(quán)限控制的初步配置

    這篇文章主要為大家介紹了SpringBoot?整合Security權(quán)限控制的初步配置實(shí)例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • java多線程讀寫文件示例

    java多線程讀寫文件示例

    這篇文章主要介紹了java多線程讀寫文件示例,需要的朋友可以參考下
    2014-04-04

最新評(píng)論

东兰县| 仪陇县| 凤庆县| 济宁市| 陇川县| 长春市| 中超| 南通市| 江北区| 台北市| 威海市| 江陵县| 白河县| 萝北县| 钟祥市| 淮南市| 海城市| 八宿县| 康乐县| 宝兴县| 资源县| 丽江市| 安宁市| 逊克县| 丹棱县| 赤城县| 西华县| 沾化县| 哈尔滨市| 大同县| 静海县| 图木舒克市| 宣化县| 双桥区| 定边县| 雷波县| 玛纳斯县| 沂南县| 克拉玛依市| 龙口市| 城口县|