Spring Boot register a filter after spring security filter is executed - spring-boot

I have defined 2 filters which should run on every request, but only after SecurityContextHolder's context is set by spring boot.
However, i always get SecurityContextHolder.getContext().getAuthentication() as null.
Here is my filter configuration:
#Bean
public FilterRegistrationBean SecurityContextHystrixRequestVariableSetterBean() throws Exception {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(securityContextHystrixRequestVariableSetterFilter());
registration.setOrder(Ordered.LOWEST_PRECEDENCE);
return registration;
}
#Bean
public FilterRegistrationBean HystrixRequestContextEnablerFilterBean() throws Exception {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(hystrixRequestContextEnablerFilter());
registration.setOrder(Ordered.LOWEST_PRECEDENCE);
return registration;
}
Filter details:
public class SecurityContextHystrixRequestVariableSetterFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
SecurityContextHystrixRequestVariable.getInstance().set(SecurityContextHolder.getContext());
chain.doFilter(request, response);
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void destroy() {
}
}
public class HystrixRequestContextEnablerFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HystrixRequestContext context = HystrixRequestContext.initializeContext();
try {
chain.doFilter(request, response);
} finally {
context.shutdown();
}
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void destroy() {
}
}

You can use OncePerRequestFilter:
public class CustomFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
//do
chain.doFilter(request, response);
}
}
#Configuration
public class CustomConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterAfter(new SecurityFilter(authenticationManager()), AnonymousAuthenticationFilter.class)
}
}

Related

#Value variable is null in customFilter implementing Filter

my custom filter is not taking value from .properties/.yml file
Note: property file is located at src/main/resources folder
#Slf4j
public class CustomFilter implements Filter {
#Value("${xyz.domainName:http://localhost:8080/x1}")
private String DOMAIN_NAME;
private static final String REDIRECT_URL_ENDPOINT = "/v1/xyz/abc/";
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String url = request.getRequestURL().toString();
String id = url.substring(url.lastIndexOf("/") + 1);
if (url.startsWith(DOMAIN_NAME)) {
ServletContext context = request.getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher(REDIRECT_URL_ENDPOINT + id);
dispatcher.forward(request, response);
}
else
filterChain.doFilter(request, response);
}
}
Edit (Added WebSecurityConfigClass): My WebSecurityConfig class looks like:
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new CustomFilter(), ApiKeyAuthFilter.class);
}
}
Looking at the code, you filter is not managed by the Spring Context, therefore Spring-related functionalities like #Value do not work. So, let Spring take care of your filter.
#Component
#Slf4j
public class CustomFilter implements Filter {
#Value("${xyz.domainName:http://localhost:8080/x1}")
private String DOMAIN_NAME;
private static final String REDIRECT_URL_ENDPOINT = "/v1/xyz/abc/";
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String url = request.getRequestURL().toString();
String id = url.substring(url.lastIndexOf("/") + 1);
if (url.startsWith(DOMAIN_NAME)) {
ServletContext context = request.getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher(REDIRECT_URL_ENDPOINT + id);
dispatcher.forward(request, response);
}
else
filterChain.doFilter(request, response);
}
#Bean
public FilterRegistrationBean registerFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(this);
registration.addUrlPatterns("/*");
return registration;
}
}
If you want to register the filter before a Spring security filter you can do this:
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private Customfilter customfilter;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(customfilter, ApiKeyAuthFilter.class);
}
}

Spring Boot Rest API filter not invoked

I want to implement filter on my Spring Boot Rest API project but some how my filter not invoked. I have added below implementation for that.
public class AutorizationFilter implements Filter{
Logger log = LoggerFactory.getLogger(AutorizationFilter.class);
#Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("**** Start ****");
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
log.info("**** doFilter ****");
chain.doFilter(request, response);
}
#Override
public void destroy() {
log.info("**** end ****");
}}
init and destroy method are working but doFilter method not invoke.
#Configuration
public class RestApiConfig {
#Bean
public FilterRegistrationBean<AutorizationFilter> filterRegistrationBean(){
FilterRegistrationBean<AutorizationFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new AutorizationFilter());
registrationBean.addUrlPatterns("/**");
return registrationBean;
}}
My controller is as below:
#RestController
#RequestMapping("/home")
public class HomeController {
#RequestMapping(value="/hello",method=RequestMethod.GET)
public ResponseEntity<Object> hello() {
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("data","called home controller");
return new ResponseEntity<>(resultMap,HttpStatus.OK);
}
}
Any one please help me why dofilter method is not working.
finally i found the solution, I need to replace registrationBean.addUrlPatterns("/**") with registrationBean.addUrlPatterns("/*") and it's working fine for me.

Spring Session + REST + Custom Authentication Filter(read credentials from JSON rather query param)

I'm trying to convert my rest services authentication from basic authentication to form based authentication the below code works fine(Note I've commented out custom authentication filter) if I send authentication details in url as query parameter something like this http://localhost:8080/login?username=dfdf&&password=sdsdd
However I'm not keen on sending credentials as query parameter instead I would prefer to send it as json, Hence I've created custom authentication filter. When I add the custom authentication filter, my spring session stops working. I cannot find x-auth-token field in my response header. Any suggestion how to enable spring session and custom authentication together/or may be easier way to handle json input for credentials.
#Configuration
#EnableWebSecurity
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private ObjectMapper objectMapper;
#Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
#Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/register", "/index.html").permitAll().and().authorizeRequests()
.anyRequest().authenticated().and().requestCache().requestCache(new NullRequestCache()).and()
.formLogin().failureHandler(getRESTAuthenticationFailureHandler())
.successHandler(getRESTAuthenticationSuccessHandler()).usernameParameter("username")
.passwordParameter("password").and().exceptionHandling()
.authenticationEntryPoint(getRESTAuthenticationEntryPoint()).and()
//.addFilter(getAuthenticationFilter())
.csrf().disable();
}
#Bean
public HttpSessionStrategy httpSessionStrategy() {
return new HeaderHttpSessionStrategy();
}
#Bean
public RESTAuthenticationEntryPoint getRESTAuthenticationEntryPoint() {
return new RESTAuthenticationEntryPoint();
}
#Bean
public RESTAuthenticationSuccessHandler getRESTAuthenticationSuccessHandler() {
return new RESTAuthenticationSuccessHandler();
}
#Bean
public RESTAuthenticationFailureHandler getRESTAuthenticationFailureHandler() {
return new RESTAuthenticationFailureHandler();
}
#Bean
public AuthenticationFilter getAuthenticationFilter() {
AuthenticationFilter filter = new AuthenticationFilter();
try {
filter.setAuthenticationManager(this.authenticationManager());
} catch (Exception e) {
e.printStackTrace();
}
return filter;
}
public class RESTAuthenticationEntryPoint implements AuthenticationEntryPoint {
#Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
}
public class RESTAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
clearAuthenticationAttributes(request);
}
}
public class RESTAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
super.onAuthenticationFailure(request, response, exception);
}
}
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final Logger LOG = LoggerFactory.getLogger(AuthenticationFilter.class);
private boolean postOnly = true;
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
String username = null;
String password = null;
UserDetails userDetails = null;
if ("application/json".equals(request.getHeader("Content-Type"))) {
userDetails = getJson(request);
if (userDetails != null) {
username = userDetails.getUsername();
}
} else {
username = obtainUsername(request);
}
if ("application/json".equals(request.getHeader("Content-Type"))) {
if (userDetails != null) {
password = userDetails.getPassword();
}
} else {
password = obtainPassword(request);
}
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
private UserDetails getJson(HttpServletRequest request) {
try {
final List<String> data = IOUtils.readLines(request.getReader());
final String jsonData = data.stream().collect(Collectors.joining());
LOG.info(jsonData);
UserDetails userDetails = objectMapper.readValue(jsonData, UserDetails.class);
return userDetails;
} catch (IOException e) {
LOG.error("Failed to read data {}", e.getMessage(), e);
return null;
}
}
}
}
As suggested I've created custom filter which converts json object to request parameter and adds to HttpServletRequest, However are there any inbuilt spring security custom filters to do the same job?
#Configuration
#EnableWebSecurity
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private ObjectMapper objectMapper;
#Bean
public FilterRegistrationBean contextFilterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
CstFilter contextFilter = new CstFilter();
registrationBean.addUrlPatterns("/login");
registrationBean.setFilter(contextFilter);
registrationBean.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
return registrationBean;
}
#Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
#Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(getRESTAuthenticationEntryPoint())
.and()
.formLogin()
.permitAll()
.loginProcessingUrl("/login")
.failureHandler(getRESTAuthenticationFailureHandler())
.successHandler(getRESTAuthenticationSuccessHandler())
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout()
.permitAll()
.logoutSuccessHandler(getRESTLogoutSuccessHandler())
.and()
.authorizeRequests()
.antMatchers("/", "/index.html")
.permitAll()
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.requestCache()
.requestCache(new NullRequestCache());
}
#Bean
public HttpSessionStrategy httpSessionStrategy() {
return new HeaderHttpSessionStrategy();
}
#Bean
public RESTAuthenticationEntryPoint getRESTAuthenticationEntryPoint() {
return new RESTAuthenticationEntryPoint();
}
#Bean
public RESTAuthenticationSuccessHandler getRESTAuthenticationSuccessHandler() {
return new RESTAuthenticationSuccessHandler();
}
#Bean
public RESTAuthenticationFailureHandler getRESTAuthenticationFailureHandler() {
return new RESTAuthenticationFailureHandler();
}
#Bean
public RESTLogoutSuccessHandler getRESTLogoutSuccessHandler() {
return new RESTLogoutSuccessHandler();
}
public class JsonConvertFilter extends HttpServletRequestWrapper {
private final Logger LOG = LoggerFactory.getLogger(JsonConvertFilter.class);
private UserDetails userDetails;
public JsonConvertFilter(HttpServletRequest request) {
super((HttpServletRequest)request);
userDetails = getJson();
}
public String getParameter(String key){
if(userDetails!=null){
if("username".equals(key)){
return userDetails.getUsername();
}
if("password".equals(key)){
return userDetails.getPassword();
}
}
System.out.println("Called wrapper");
return super.getParameter(key);
}
private UserDetails getJson() {
try {
final List<String> data = IOUtils.readLines(super.getReader());
final String jsonData = data.stream().collect(Collectors.joining());
LOG.info(jsonData);
UserDetails userDetails = objectMapper.readValue(jsonData, UserDetails.class);
return userDetails;
} catch (IOException e) {
LOG.warn("Failed to read data {}", e.getMessage(), e);
return null;
}
}
}
public class CstFilter implements Filter{
#Override
public void destroy() {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
chain.doFilter(new JsonConvertFilter((HttpServletRequest)request), response);
}
#Override
public void init(FilterConfig arg0) throws ServletException {
}
}
public class RESTLogoutSuccessHandler implements LogoutSuccessHandler{
#Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
String uri = request.getRequestURI();
if ("logout".equals(uri)) {
response.sendError(HttpServletResponse.SC_OK, "Succesfully Logged out");
}
}
}
public class RESTAuthenticationEntryPoint implements AuthenticationEntryPoint {
#Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().print("Unauthorizated....");
}
}
public class RESTAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
clearAuthenticationAttributes(request);
}
}
public class RESTAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
String uri = request.getRequestURI();
if ("logout".equals(uri)) {
response.sendError(HttpServletResponse.SC_OK, "Succesfully Logged out");
} else {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"Authentication Failed: " + exception.getMessage());
}
}
}
}
For any one want to test this using jquery ajax.
/* Alerts the results */
$.ajax({
url : "login",
type : "POST",
async : false,
contentType: "application/json",
data : "{ \"username\":\""+username+"\", \"password\":\"" + password + "\"}",
success : function(data, status, request) {
alert("Success");
authtokenKey = request.getResponseHeader('x-auth-token');
},
error : function(xhr, status, error) {
alert(error);
}
});

Why is this spring security configuration blocks all paths?

public class AuthenticationFilter extends GenericFilterBean {
SecureService secureService;
public AuthenticationFilter(SecureService secureService) {
this.secureService=secureService;
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest=(HttpServletRequest)servletRequest;
Authentication authentication=secureService.getAuthentication(httpServletRequest);
if(authentication!=null) {
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(servletRequest, servletResponse);
SecurityContextHolder.getContext().setAuthentication(null);
}
}
}
#Configuration
#EnableWebSecurity
public class AppSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
SecureService secureService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new AuthenticationFilter(secureService), BasicAuthenticationFilter.class)
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/businesses/**").permitAll()
.antMatchers(HttpMethod.GET, "/users/login").permitAll()
.antMatchers(HttpMethod.POST, "/users/").permitAll()
.antMatchers(HttpMethod.GET, "/reviews/").permitAll()
.antMatchers(HttpMethod.GET, "/reviews/search").permitAll()
.antMatchers(HttpMethod.GET, "/reviews/**").permitAll()
.antMatchers("/").permitAll().and()
.authorizeRequests().anyRequest().authenticated();
}
#Bean
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManagerBean();
}
}
what's wrong with this configuration? I followed with this link to write url authentications. But my app keeps blocking all requests, ignoring all the matchers specified in the code. I googled and someone said the order of rules matters. But even though I change the order, AuthenticationFilter gets invoked all the time and keeps blocking all requests.
The problem is that you interrupt the filter chain. do it as the following and it should work.
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
Authentication authentication = secureService.getAuthentication(httpServletRequest);
if (authentication != null) {
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(servletRequest, servletResponse);
SecurityContextHolder.getContext().setAuthentication(null);
}
Another thing is that you throw a UserNotFoundException inside your SecureService if the HttpServlerRequest does not contain an Authentication.
In the AuthenticationFilter you seem to expect null in this case? So return null in the SecureService if no Authentication exists:
public Authentication getAuthentication(HttpServletRequest httpServletRequest) {
final String token=httpServletRequest.getHeader(Headers.AUTH_HEADER_NAME);
if(token!=null){
final User user=parseToken(token);
if(user!=null){
return new UserAuthentication(user);
}
}
return null;
}
if you want to keep the UserNotFoundException then only change the doFilterMethod to the following:
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
try {
Authentication authentication = secureService.getAuthentication(httpServletRequest);
if (authentication != null) {
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}catch(UserNotFoundException e){
}finally {
filterChain.doFilter(servletRequest, servletResponse);
SecurityContextHolder.getContext().setAuthentication(null);
}
}

Gzip filter with Spring async

I am using the new Servlet 3 feature DefferedResult in my Spring-MVC application. I had a GZIP filter which I had to remove as DefferedResult did not work with it.
Can someone tell me if there is a GZipFilter that will work with the Spring async(DefferedResult)?
Try using the filter introduced in servlet 3 - asyncSupported
#WebFilter(servletNames = { "servletAsynFilter" }, asyncSupported=true)
public class Filter1 implements Filter {
public void init(FilterConfig fConfig) throws ServletException {}
public void destroy() {}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponseWrapper respWrap = new HttpServletResponseWrapper((HttpServletResponse)response);
chain.doFilter(request, respWrap);
}
}

Resources