怎么在SpringSecurity中自定義過濾器

本篇文章給大家分享的是有關(guān)怎么在SpringSecurity中自定義過濾器,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

創(chuàng)新互聯(lián)服務(wù)項目包括布爾津網(wǎng)站建設(shè)、布爾津網(wǎng)站制作、布爾津網(wǎng)頁制作以及布爾津網(wǎng)絡(luò)營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢、行業(yè)經(jīng)驗、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,布爾津網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到布爾津省份的部分城市,未來相信會繼續(xù)擴大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!

一、創(chuàng)建自己定義的Filter

我們先在web包下創(chuàng)建好幾個包并定義如下幾個類

怎么在SpringSecurity中自定義過濾器

CustomerAuthFilter:

package com.bdqn.lyrk.security.study.web.filter;

import com.bdqn.lyrk.security.study.web.authentication.UserJoinTimeAuthentication;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class CustomerAuthFilter extends AbstractAuthenticationProcessingFilter {

  private AuthenticationManager authenticationManager;


  public CustomerAuthFilter(AuthenticationManager authenticationManager) {

    super(new AntPathRequestMatcher("/login", "POST"));
    this.authenticationManager = authenticationManager;

  }

  @Override
  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    String username = request.getParameter("username");
    UserJoinTimeAuthentication usernamePasswordAuthenticationToken =new UserJoinTimeAuthentication(username);
    Authentication authentication = this.authenticationManager.authenticate(usernamePasswordAuthenticationToken);
    if (authentication != null) {
      super.setContinueChainBeforeSuccessfulAuthentication(true);
    }
    return authentication;
  }
}

該類繼承AbstractAuthenticationProcessingFilter,這個filter的作用是對最基本的用戶驗證的處理,我們必須重寫attemptAuthentication方法。Authentication接口表示授權(quán)接口,通常情況下業(yè)務(wù)認證通過時會返回一個這個對象。super.setContinueChainBeforeSuccessfulAuthentication(true) 設(shè)置成true的話,會交給其他過濾器處理。

二、定義UserJoinTimeAuthentication

package com.bdqn.lyrk.security.study.web.authentication;

import org.springframework.security.authentication.AbstractAuthenticationToken;

public class UserJoinTimeAuthentication extends AbstractAuthenticationToken {
  private String username;

  public UserJoinTimeAuthentication(String username) {
    super(null);
    this.username = username;
  }


  @Override
  public Object getCredentials() {
    return null;
  }

  @Override
  public Object getPrincipal() {
    return username;
  }
}

自定義授權(quán)方式,在這里接收username的值處理,其中g(shù)etPrincipal我們可以用來存放登錄名,getCredentials可以存放密碼,這些方法來自于Authentication接口

三、定義AuthenticationProvider

package com.bdqn.lyrk.security.study.web.authentication;

import com.bdqn.lyrk.security.study.app.pojo.Student;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.Date;

/**
 * 基本的驗證方式
 *
 * @author chen.nie
 * @date 2018/6/12
 **/
public class UserJoinTimeAuthenticationProvider implements AuthenticationProvider {
  private UserDetailsService userDetailsService;

  public UserJoinTimeAuthenticationProvider(UserDetailsService userDetailsService) {
    this.userDetailsService = userDetailsService;
  }

  /**
   * 認證授權(quán),如果jointime在當前時間之后則認證通過
   * @param authentication
   * @return
   * @throws AuthenticationException
   */
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = (String) authentication.getPrincipal();
    UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
    if (!(userDetails instanceof Student)) {
      return null;
    }
    Student student = (Student) userDetails;
    if (student.getJoinTime().after(new Date()))
      return new UserJoinTimeAuthentication(username);
    return null;
  }

  /**
   * 只處理UserJoinTimeAuthentication的認證
   * @param authentication
   * @return
   */
  @Override
  public boolean supports(Class<?> authentication) {
    return authentication.getName().equals(UserJoinTimeAuthentication.class.getName());
  }
}

AuthenticationManager會委托AuthenticationProvider進行授權(quán)處理,在這里我們需要重寫support方法,該方法定義Provider支持的授權(quán)對象,那么在這里我們是對UserJoinTimeAuthentication處理。

四、WebSecurityConfig

package com.bdqn.lyrk.security.study.app.config;

import com.bdqn.lyrk.security.study.app.service.UserService;
import com.bdqn.lyrk.security.study.web.authentication.UserJoinTimeAuthenticationProvider;
import com.bdqn.lyrk.security.study.web.filter.CustomerAuthFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * spring-security的相關(guān)配置
 *
 * @author chen.nie
 * @date 2018/6/7
 **/
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private UserService userService;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    /*
      1.配置靜態(tài)資源不進行授權(quán)驗證
      2.登錄地址及跳轉(zhuǎn)過后的成功頁不需要驗證
      3.其余均進行授權(quán)驗證
     */
    http.
        authorizeRequests().antMatchers("/static/**").permitAll().
        and().authorizeRequests().antMatchers("/user/**").hasRole("7022").
        and().authorizeRequests().anyRequest().authenticated().
        and().formLogin().loginPage("/login").successForwardUrl("/toIndex").permitAll()
        .and().logout().logoutUrl("/logout").invalidateHttpSession(true).deleteCookies().permitAll()
    ;

    http.addFilterBefore(new CustomerAuthFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);


  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //設(shè)置自定義userService
    auth.userDetailsService(userService);
    auth.authenticationProvider(new UserJoinTimeAuthenticationProvider(userService));
  }

  @Override
  public void configure(WebSecurity web) throws Exception {
    super.configure(web);
  }
}

以上就是怎么在SpringSecurity中自定義過濾器,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學到更多知識。更多詳情敬請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

網(wǎng)站題目:怎么在SpringSecurity中自定義過濾器
當前鏈接:http://muchs.cn/article48/gdeeep.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供虛擬主機建站公司、用戶體驗、網(wǎng)站內(nèi)鏈、定制開發(fā)、關(guān)鍵詞優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

小程序開發(fā)