Set cookie in every request - SPRING - spring

Im now developing simple spring boot web app..
Is there something in spring(filter) that check every request(headers)..
I want to check if there is cookie..
If there is cookie- nothing happend..
But if there is not it would create cookie...
Do i have to do this manually, so i put this in every function?
Or can i do something like global function, that got executed with every other request?
Thanks for help.

yes you have to use filters
you can try doing something like this
public class MyCookieFilter extends GenericFilterBean {
public static final String MY_COOKIE_NAME = "your-cookie-name";
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
checkCookie(httpServletRequest, httpServletResponse);
filterChain.doFilter(servletRequest, servletResponse);
}
private void checkCookie(HttpServletRequest request, HttpServletResponse servletResponse) {
boolean cookieExists = Arrays.stream(request.getCookies()).anyMatch(cookie -> cookie.getName().equalsIgnoreCase(MY_COOKIE_NAME));
if (!cookieExists) {
String cookieValue = "your-cookie-value";
Cookie newCookie = new Cookie(MY_COOKIE_NAME, cookieValue);
servletResponse.addCookie(newCookie);
}
}
}
then add it in your security config
#Override
public void configure(HttpSecurity http) throws Exception {
http
...
.addFilter(new MyCookieFilter())
...
}

Related

How to allow swagger ui in Spring Custom Filter along with validation

I have written the following code where I have created a Custom Filter in SpringBoot which is always passed as Request Header. Request header name licenseKey and some value. I have implemented and also allowed Swagger-UI to work. Please suggest me to follow better approach, my seniors say that it is not a good approach. I provide below the code. The task is to receive licenseKey while calling Rest end point and also we need to allow Swagger-UI without licenseKey that will be provided later as part of authorization in Swagger. Currently the code is working fine. I request for better approach. I provide below the code. I removed all import statements.
#Component
public class CustomURLFilter implements Filter {
#Autowired
private CustomUserDetailsService userDetailsService;
private static final Logger LOGGER = LoggerFactory.getLogger(CustomURLFilter.class);
#Override
public void init(FilterConfig filterConfig) throws ServletException {
LOGGER.info("########## Initiating CustomURLFilter filter ##########");
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String path = request.getRequestURI();
System.out.println("Path: "+path);
if(path.startsWith("/app-name-service/swagger-ui") || path.startsWith("/app-name-service/v3/api-docs")) {
filterChain.doFilter(request, response);
return;
} else {
String licenseKey = userDetailsService.getLicenseKey(request);
System.out.println("User License Key: "+licenseKey);
}
LOGGER.info("This Filter is only called when request is mapped for /customer resource");
//call next filter in the filter chain
filterChain.doFilter(request, response);
}
#Override
public void destroy() {
}
}

Filter for Url Pattern without authentification?

Help me please a little with setting up Spring Security.
I found something similar, but it somehow does not work very well for me ..
https://stackoverflow.com/a/36875726/1590594
The configuration specifies that each request must be authenticated.
It is necessary to do the following, that on the specified URL ("/ push") worked only one filter. The filter does the appropriate checking and skips the request further or rejecting. Without authentication.
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().
sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().
authorizeRequests()
.anyRequest().authenticated().
and().
anonymous().disable().
exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint());
http.addFilterBefore(new UserAuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class);
http.authorizeRequests().antMatchers(HttpMethod.POST, "/push").authenticated().and().addFilterBefore(new RPushFilter(),BasicAuthenticationFilter.class);
}
and filter
public class RPushFilter extends GenericFilterBean {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
//IF NOT httpResponse.sendError(HttpStatus.BAD_REQUEST.value(), "Access denied");
chain.doFilter(request, response);
}
}

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);
}
}

log http traffic in spring boot web application

I have a spring boot web application installed on tomcat7. I am looking for a way to log the http incoming and outcoming requests (header and body).I am looking for something similar to org.apache.cxf.interceptor.LoggingOutInterceptor.
Can you help?
You could implement your own filter like:
#Component
public class SimpleFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
// logic...
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
This is also a good solution for both of your requirements to intercept requests and response...

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