R-Sandor / FindFirst

Organizing the information that matters to you and your teams. The knowledge of your world.
https://findfirst.dev
Apache License 2.0
10 stars 17 forks source link

Configure Signup to only be allowed from same origin #186

Open R-Sandor opened 2 months ago

R-Sandor commented 2 months ago

Sample code from research on the topic:

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class DomainAndUserAgentFilter extends HttpFilter {

    private static final String ALLOWED_DOMAIN = "mywebsite.com";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Initialization code, if needed
    }

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String referer = request.getHeader("Referer");
        String origin = request.getHeader("Origin");
        String userAgent = request.getHeader("User-Agent");

        if ((referer != null && referer.contains(ALLOWED_DOMAIN)) || 
            (origin != null && origin.contains(ALLOWED_DOMAIN)) ||
            (userAgent != null && isBrowser(userAgent))) {
            chain.doFilter(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access denied");
        }
    }

    private boolean isBrowser(String userAgent) {
        // Simple check for common browser user agents
        return userAgent.contains("Mozilla") || userAgent.contains("Chrome") || userAgent.contains("Safari");
    }

    @Override
    public void destroy() {
        // Cleanup code, if needed
    }
}
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean<DomainAndUserAgentFilter> domainAndUserAgentFilter() {
        FilterRegistrationBean<DomainAndUserAgentFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new DomainAndUserAgentFilter());
        registrationBean.addUrlPatterns("/your-endpoint/*"); // Specify the endpoints you want to protect
        return registrationBean;
    }
}