Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring security custom-filter with java configuration

How can I replace default filter with custom filter in java configuration? In XML it would be, for example:

<bean id="myFilter" class="lalalal.MyFilter">
<property name="authenticationManager" ref="authenticationManager"/>
</bean>

<security:http auto-config="true">     
      <security:custom-filter ref="myFilter" position="FORM_LOGIN_FILTER"/>
</security:http> 

About filterBefore, filterAfter and default filter inhereting I know.

like image 536
Serhii Soboliev Avatar asked Nov 01 '22 05:11

Serhii Soboliev


1 Answers

Assuming you have an understanding in general of Java configuration for Spring-security, adding filters is relatively simple (general details of updating spring-security config to java here):

So in your WebSecurityConfigurerAdapter implementation, do something like this:

@Configuration
@EnableWebSecurity
class SecurityConfiguration extends WebSecurityConfigurerAdapter {

   @Override protected void configure(HttpSecurity http) throws Exception {

       //Custom security filters
       http.addFilterBefore( myFilter(), BasicAuthenticationFilter.class );

       //Rest of the security configuration goes here
       ...
   }

That is a very cut down example - but hopefully helps enough - you would put additional security configuration here (e.g. role based restrictions, csrf, session config etc) and myFilter() is another method defining the bean you mention in the question that sets up your Filter. There is also an addFilterAfter() method and you can choose where to place your filter in the chain.

Here is an example for API security that shows some custom filters being used.

like image 98
rhinds Avatar answered Nov 18 '22 16:11

rhinds