欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring security 自定义过滤器实现Json参数传递并兼容表单参数(实例代码)

程序员文章站 2022-03-19 07:53:14
依赖 org.springframework.boot

依赖

 <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>
    <dependency>
      <groupid>org.projectlombok</groupid>
      <artifactid>lombok</artifactid>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupid>org.projectlombok</groupid>
      <artifactid>lombok</artifactid>
      <optional>true</optional>
    </dependency>
配置安全适配类

基本配置和配置自定义过滤器

package com.study.auth.config.core;
 
import com.study.auth.config.core.authentication.accountauthenticationprovider;
import com.study.auth.config.core.authentication.mailauthenticationprovider;
import com.study.auth.config.core.authentication.phoneauthenticationprovider;
import com.study.auth.config.core.filter.customerusernamepasswordauthenticationfilter;
import com.study.auth.config.core.handler.customerauthenticationfailurehandler;
import com.study.auth.config.core.handler.customerauthenticationsuccesshandler;
import com.study.auth.config.core.handler.customerlogoutsuccesshandler;
import com.study.auth.config.core.observer.customeruserdetailsservice;
import lombok.extern.slf4j.slf4j;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.annotation.bean;
import org.springframework.security.authentication.authenticationmanager;
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.crypto.bcrypt.bcryptpasswordencoder;
import org.springframework.security.web.authentication.abstractauthenticationprocessingfilter;
import org.springframework.security.web.authentication.usernamepasswordauthenticationfilter;
 
/**
 * @package: com.study.auth.config
 * @description: <>
 * @author: milla
 * @createdate: 2020/09/04 11:27
 * @updateuser: milla
 * @updatedate: 2020/09/04 11:27
 * @updateremark: <>
 * @version: 1.0
 */
@slf4j
@enablewebsecurity
public class websecurityconfig extends websecurityconfigureradapter {
 
  @autowired
  private accountauthenticationprovider provider;
  @autowired
  private mailauthenticationprovider mailprovider;
  @autowired
  private phoneauthenticationprovider phoneprovider;
  @autowired
  private customeruserdetailsservice userdetailsservice;
  @autowired
  private customerauthenticationsuccesshandler successhandler;
  @autowired
  private customerauthenticationfailurehandler failurehandler;
  @autowired
  private customerlogoutsuccesshandler logoutsuccesshandler;
 
  /**
   * 配置拦截器保护请求
   *
   * @param http
   * @throws exception
   */
  @override
  protected void configure(httpsecurity http) throws exception {
    //配置http基本身份验证//使用自定义过滤器-兼容json和表单登录
    http.addfilterbefore(customauthenticationfilter(), usernamepasswordauthenticationfilter.class)
        .httpbasic()
        .and().authorizerequests()
        //表示访问 /setting 这个接口,需要具备 admin 这个角色
        .antmatchers("/setting").hasrole("admin")
        //表示剩余的其他接口,登录之后就能访问
        .anyrequest()
        .authenticated()
        .and()
        .formlogin()
        //定义登录页面,未登录时,访问一个需要登录之后才能访问的接口,会自动跳转到该页面
        .loginpage("/notoken")
        //登录处理接口-登录时候访问的接口地址
        .loginprocessingurl("/account/login")
        //定义登录时,表单中用户名的 key,默认为 username
        .usernameparameter("username")
        //定义登录时,表单中用户密码的 key,默认为 password
        .passwordparameter("password")
//        //登录成功的处理器
//        .successhandler(successhandler)
//        //登录失败的处理器
//        .failurehandler(failurehandler)
        //允许所有用户访问
        .permitall()
        .and()
        .logout()
        .logouturl("/logout")
        //登出成功的处理
        .logoutsuccesshandler(logoutsuccesshandler)
        .permitall();
    //关闭csrf跨域攻击防御
    http.csrf().disable();
  }
 
  /**
   * 配置权限认证服务
   *
   * @param auth
   * @throws exception
   */
  @override
  protected void configure(authenticationmanagerbuilder auth) throws exception {
    //权限校验-只要有一个认证通过即认为是通过的(有一个认证通过就跳出认证循环)-适用于多登录方式的系统
//    auth.authenticationprovider(provider);
//    auth.authenticationprovider(mailprovider);
//    auth.authenticationprovider(phoneprovider);
    //直接使用userdetailsservice
    auth.userdetailsservice(userdetailsservice).passwordencoder(new bcryptpasswordencoder());
  }
 
  /**
   * 配置spring security的filter链
   *
   * @param web
   * @throws exception
   */
  @override
  public void configure(websecurity web) throws exception {
    //忽略拦截的接口
    web.ignoring().antmatchers("/notoken");
  }
 
  /**
   * 指定验证manager
   *
   * @return
   * @throws exception
   */
  @override
  @bean
  public authenticationmanager authenticationmanagerbean() throws exception {
    return super.authenticationmanagerbean();
  }
 
 
  /**
   * 注册自定义的usernamepasswordauthenticationfilter
   *
   * @return
   * @throws exception
   */
  @bean
  public abstractauthenticationprocessingfilter customauthenticationfilter() throws exception {
    abstractauthenticationprocessingfilter filter = new customerusernamepasswordauthenticationfilter();
    filter.setauthenticationsuccesshandler(successhandler);
    filter.setauthenticationfailurehandler(failurehandler);
    //过滤器拦截的url要和登录的url一致,否则不生效
    filter.setfilterprocessesurl("/account/login");
 
    //这句很关键,重用websecurityconfigureradapter配置的authenticationmanager,不然要自己组装authenticationmanager
    filter.setauthenticationmanager(authenticationmanagerbean());
    return filter;
  }
}
自定义过滤器 

根据contenttype是否为json进行判断,如果是就从body中读取参数,进行解析,并生成权限实体,进行权限认证

否则直接使用usernamepasswordauthenticationfilter中的方法

package com.study.auth.config.core.filter;
 
import com.fasterxml.jackson.databind.objectmapper;
import com.study.auth.config.core.util.authenticationstoreutil;
import com.study.auth.entity.bo.loginbo;
import lombok.extern.slf4j.slf4j;
import org.springframework.http.mediatype;
import org.springframework.security.authentication.usernamepasswordauthenticationtoken;
import org.springframework.security.core.authentication;
import org.springframework.security.core.authenticationexception;
import org.springframework.security.web.authentication.usernamepasswordauthenticationfilter;
 
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.io.ioexception;
import java.io.inputstream;
 
/**
 * @package: com.study.auth.config.core.filter
 * @description: <>
 * @author: milla
 * @createdate: 2020/09/11 16:04
 * @updateuser: milla
 * @updatedate: 2020/09/11 16:04
 * @updateremark: <>
 * @version: 1.0
 */
@slf4j
public class customerusernamepasswordauthenticationfilter extends usernamepasswordauthenticationfilter {
 
  /**
   * 空字符串
   */
  private final string empty = "";
 
 
  @override
  public authentication attemptauthentication(httpservletrequest request, httpservletresponse response) throws authenticationexception {
 
    //如果不是json使用自带的过滤器获取参数
    if (!request.getcontenttype().equals(mediatype.application_json_utf8_value) && !request.getcontenttype().equals(mediatype.application_json_value)) {
      string username = this.obtainusername(request);
      string password = this.obtainpassword(request);
      storeauthentication(username, password);
      authentication authentication = super.attemptauthentication(request, response);
      return authentication;
    }
 
    //如果是json请求使用取参数逻辑
    objectmapper mapper = new objectmapper();
    usernamepasswordauthenticationtoken authrequest = null;
    try (inputstream is = request.getinputstream()) {
      loginbo account = mapper.readvalue(is, loginbo.class);
      storeauthentication(account.getusername(), account.getpassword());
      authrequest = new usernamepasswordauthenticationtoken(account.getusername(), account.getpassword());
    } catch (ioexception e) {
      log.error("验证失败:{}", e);
      authrequest = new usernamepasswordauthenticationtoken(empty, empty);
    } finally {
      setdetails(request, authrequest);
      authentication authenticate = this.getauthenticationmanager().authenticate(authrequest);
      return authenticate;
    }
  }
 
  /**
   * 保存用户名和密码
   *
   * @param username 帐号/邮箱/手机号
   * @param password 密码/验证码
   */
  private void storeauthentication(string username, string password) {
    authenticationstoreutil.setusername(username);
    authenticationstoreutil.setpassword(password);
  }
}

 其中会有body中的传参问题,所以使用threadlocal传递参数

ps:枚举类具备线程安全性

package com.study.auth.config.core.util;
 
/**
 * @package: com.study.auth.config.core.util
 * @description: <使用枚举可以保证线程安全>
 * @author: milla
 * @createdate: 2020/09/11 17:48
 * @updateuser: milla
 * @updatedate: 2020/09/11 17:48
 * @updateremark: <>
 * @version: 1.0
 */
public enum authenticationstoreutil {
  authentication;
  /**
   * 登录认证之后的token
   */
  private final threadlocal<string> tokenstore = new threadlocal<>();
  /**
   * 需要验证用户名
   */
  private final threadlocal<string> usernamestore = new threadlocal<>();
  /**
   * 需要验证的密码
   */
  private final threadlocal<string> passwordstore = new threadlocal<>();
 
  public static string getusername() {
    return authentication.usernamestore.get();
  }
 
  public static void setusername(string username) {
    authentication.usernamestore.set(username);
  }
 
  public static string getpassword() {
    return authentication.passwordstore.get();
  }
 
  public static void setpassword(string password) {
    authentication.passwordstore.set(password);
  }
 
  public static string gettoken() {
    return authentication.tokenstore.get();
  }
 
  public static void settoken(string token) {
    authentication.tokenstore.set(token);
  }
 
  public static void clear() {
    authentication.tokenstore.remove();
    authentication.passwordstore.remove();
    authentication.usernamestore.remove();
  }
}
实现userdetailsservice接口
package com.study.auth.config.core.observer;
 
import lombok.extern.slf4j.slf4j;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.security.core.userdetails.user;
import org.springframework.security.core.userdetails.userdetails;
import org.springframework.security.core.userdetails.userdetailsservice;
import org.springframework.security.core.userdetails.usernamenotfoundexception;
import org.springframework.security.crypto.password.passwordencoder;
import org.springframework.stereotype.component;
 
/**
 * @package: com.study.auth.config.core
 * @description: <自定义用户处理类>
 * @author: milla
 * @createdate: 2020/09/04 13:53
 * @updateuser: milla
 * @updatedate: 2020/09/04 13:53
 * @updateremark: <>
 * @version: 1.0
 */
@slf4j
@component
public class customeruserdetailsservice implements userdetailsservice {
 
  @autowired
  private passwordencoder passwordencoder;
 
  @override
  public userdetails loaduserbyusername(string username) throws usernamenotfoundexception {
    //测试直接使用固定账户代替
    return user.withusername("admin").password(passwordencoder.encode("admin")).roles("admin", "user").build();
  }
}
 登录成功类
package com.study.auth.config.core.handler;
 
import org.springframework.security.core.authentication;
import org.springframework.security.web.authentication.authenticationsuccesshandler;
import org.springframework.stereotype.component;
 
import javax.servlet.servletexception;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.io.ioexception;
 
/**
 * @package: com.study.auth.config.core.handler
 * @description: <登录成功处理类>
 * @author: milla
 * @createdate: 2020/09/08 17:39
 * @updateuser: milla
 * @updatedate: 2020/09/08 17:39
 * @updateremark: <>
 * @version: 1.0
 */
@component
public class customerauthenticationsuccesshandler implements authenticationsuccesshandler {
  @override
  public void onauthenticationsuccess(httpservletrequest request, httpservletresponse response, authentication authentication) throws ioexception, servletexception {
    httpservletresponseutil.loginsuccess(response);
  }
}
 登录失败
package com.study.auth.config.core.handler;
 
import org.springframework.security.core.authenticationexception;
import org.springframework.security.web.authentication.authenticationfailurehandler;
import org.springframework.stereotype.component;
 
import javax.servlet.servletexception;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.io.ioexception;
 
/**
 * @package: com.study.auth.config.core.handler
 * @description: <登录失败操作类>
 * @author: milla
 * @createdate: 2020/09/08 17:42
 * @updateuser: milla
 * @updatedate: 2020/09/08 17:42
 * @updateremark: <>
 * @version: 1.0
 */
@component
public class customerauthenticationfailurehandler implements authenticationfailurehandler {
  @override
  public void onauthenticationfailure(httpservletrequest request, httpservletresponse response, authenticationexception exception) throws ioexception, servletexception {
    httpservletresponseutil.loginfailure(response, exception);
  }
}
 登出成功类
package com.study.auth.config.core.handler;
 
import org.springframework.security.core.authentication;
import org.springframework.security.web.authentication.logout.logoutsuccesshandler;
import org.springframework.stereotype.component;
 
import javax.servlet.servletexception;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.io.ioexception;
 
/**
 * @package: com.study.auth.config.core.handler
 * @description: <登出成功>
 * @author: milla
 * @createdate: 2020/09/08 17:44
 * @updateuser: milla
 * @updatedate: 2020/09/08 17:44
 * @updateremark: <>
 * @version: 1.0
 */
@component
public class customerlogoutsuccesshandler implements logoutsuccesshandler {
  @override
  public void onlogoutsuccess(httpservletrequest request, httpservletresponse response, authentication authentication) throws ioexception, servletexception {
    httpservletresponseutil.logoutsuccess(response);
  }
}
返回值工具类 
package com.study.auth.config.core.handler;
 
import com.alibaba.fastjson.json;
import com.study.auth.comm.responsedata;
import com.study.auth.constant.commonconstant;
import org.springframework.http.mediatype;
import org.springframework.security.core.authenticationexception;
 
import javax.servlet.http.httpservletresponse;
import java.io.ioexception;
import java.io.printwriter;
 
/**
 * @package: com.study.auth.config.core.handler
 * @description: <>
 * @author: milla
 * @createdate: 2020/09/08 17:45
 * @updateuser: milla
 * @updatedate: 2020/09/08 17:45
 * @updateremark: <>
 * @version: 1.0
 */
public final class httpservletresponseutil {
 
  public static void loginsuccess(httpservletresponse resp) throws ioexception {
    responsedata success = responsedata.success();
    success.setmsg("login success");
    response(resp, success);
  }
 
  public static void logoutsuccess(httpservletresponse resp) throws ioexception {
    responsedata success = responsedata.success();
    success.setmsg("logout success");
    response(resp, success);
  }
 
  public static void loginfailure(httpservletresponse resp, authenticationexception exception) throws ioexception {
    responsedata failure = responsedata.error(commonconstant.ex_run_time_exception, exception.getmessage());
    response(resp, failure);
  }
 
  private static void response(httpservletresponse resp, responsedata data) throws ioexception {
    //直接输出的时候还是需要使用utf-8字符集
    resp.setcontenttype(mediatype.application_json_utf8_value);
    printwriter out = resp.getwriter();
    out.write(json.tojsonstring(data));
    out.flush();
  }
}

 其他对象见controller 层返回值的公共包装类-避免每次都包装一次返回-initializingbean增强

至此,就可以传递json参数了 

Spring security 自定义过滤器实现Json参数传递并兼容表单参数(实例代码)

到此这篇关于spring security 自定义过滤器实现json参数传递并兼容表单参数的文章就介绍到这了,更多相关spring security 自定义过滤器内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!