springBoot 2 x+securityは、カスタムリターンデータ構造がありません。

3758 ワード

1 Spring Boot異常が発生したとき、または保護されたリソースを要求したとき、またはユーザが認証を通過しなかったとき、デフォルトで返されたJsonデータ構造は以下の通りです。現在のインターフェースはヘッダ状態に応答しますか?statusは403です。明らかに、会社の開発規範によって、構造が{code”403、“message”:“先に登録してください!”、“data”:null}に戻る必要があります。また、応答ヘッド状態コードも200であり、403ではありません。(状態コード403の場合、フロントエンドは、errorにおいて要求結果を取得するために必要であり、フロントエンドがバックグラウンド応答結果を処理するのに不便であることは明らかである)
2 SecurityConfigクラスを作成し、SecurityConfigはWebSecurityConfigrer Adapterを継承します。@EnbaleGlobal MethodSecurity(prePostEnbaled=true)public class SecurityConfig extends WebSecurityConfigs
@Autowired
private TokenFilter tokenFilter;

@Autowired
private AuthenticationEntryPoint authenticationEntryPoint;

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
	return new BCryptPasswordEncoder();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
	http.csrf().disable();
	//   token,     session
	http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

	http.authorizeRequests()
			.antMatchers("/","/token", "/*.html", "/favicon.ico", "/css/**", "/js/**", "/fonts/**", "/layui/**", "/img/**",
					"/v2/api-docs/**", "/swagger-resources/**", "/webjars/**", "/pages/**", "/druid/**",
					"/statics/**","/login/**","/landing/**","/.well-known/**","/noLogin/**")
			.permitAll().anyRequest().authenticated();

	 http.formLogin().and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);

	http.headers().frameOptions().disable();
	http.headers().cacheControl();
	http.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);
}
ポイント:tokenFilterはカスタムフィルタで、使用フィルタを指定し、TokenFilterはOnecePerRequest Filterを継承します。
3 SecurityHandlerConfigを作成し、Authentication EntryPointの実装クラスを編集しています。Authentication EntryPoint:/*。
  • spring securityプロセッサ

  • @author:lucas*/@Configration pblic class Security HandlerConfigh(/*)
  • が登録されていません。401
  • に戻ります。

  • @return*/@Bean public Authentication Entication EntyPoint authentication EntryPoint(){return new Authentication Entication EntintImpl()}
  • class Authentication EntryPoint Impl implemens Authentication EntryPoint{
    	@Override
    	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException){
    		ResponseInfo info = new ResponseInfo(HttpStatus.UNAUTHORIZED.value() + "", "    ");
    		ResponseUtil.responseJson(response,request, HttpStatus.OK.value(), info);
    	}
    
    )
    public class ResponseInfo implemens Serializable{
    private static final long serialVersionUID = -4417715614021482064L;
    
    private String code;
    private String message;
    
    public ResponseInfo(String code, String message) {
    	super();
    	this.code = code;
    	this.message = message;
    }
    
    public String getCode() {
    	return code;
    }
    
    public void setCode(String code) {
    	this.code = code;
    }
    
    public String getMessage() {
    	return message;
    }
    
    public void setMessage(String message) {
    	this.message = message;
    }
    
    )
    public class ResponseUtil{
    public static void responseJson(HttpServletResponse response, HttpServletRequest request, int status, Object data) {
    	try {
    		response.setHeader("Access-Control-Allow-Origin", "*");
    		response.setHeader("Access-Control-Allow-Methods", "*");
    		response.setContentType("application/json;charset=UTF-8");
    		response.setStatus(status);
    
    		response.setStatus(status);
    		response.getWriter().write(JSONObject.toJSONString(data));
    	} catch (IOException e) {
    		e.printStackTrace();
    	}
    }
    
    }4このようにすれば、未登録応答カスタム構造が実現でき、応答ヘッダ状態コードは200: