1

I want to authenticate a server. I want to make sure the user is giving a header key, I am not checking for login or anything.

I want the header key to check with my hardcoded one, If its equal pass it, Else no

I wrote two filters.

SecurityConfig.java

package com.company.framework.filter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig{

    @Autowired private AuthFilter filtet;

    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        System.out.println("reaching here3 ");
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/api/v1/open/**").permitAll()
                .and()
            .exceptionHandling()
                .authenticationEntryPoint(
         (request, response,     authException) ->
                                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Error here")
                    )
                .and()
            .sessionManagement()
                .and()
            .httpBasic().disable();

        http
            .addFilter(filtet);
        return http.build();
    }
}

Authfilter.java

package com.company.framework.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

@Component
public class AuthFilter extends OncePerRequestFilter{

    @Override
    protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain) throws ServletException, IOException {
    
        String authHeader = request.getHeader("Authorization");
        System.out.println("here ");
        System.out.println(authHeader+"1");
        if (authHeader != null && authHeader.length() == 0 && authHeader.startsWith("Bearer ")) {
            String jwt = authHeader.substring(7);
            System.out.println(authHeader+"2");
            if (jwt == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid JWT Token in Bearer Header");
            } else {
                String rev = "bfrek";
                if (jwt.equals(rev)) {
                    response.setStatus(200);
                } else {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid JWT Token");
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}

But, after all days of try and error, I am still getting 401 unauthorised. I have seen articles telling how to connect it with users database but I just want to check for header token and pass it through. (Using filter)

Edit 1: Now after reading many articles and documentation, I understand that there are 15 filters, But how do I make sure that the system just checks for my header key and ignore everything else.

Anubhav Sinha
  • 150
  • 2
  • 16
  • Your filter needs to be in the right place to be relevant, if other filters before already return a 401, it won't reach your code. https://stackoverflow.com/questions/41480102/how-spring-security-filter-chain-works/58580849#58580849 there should be a `http.addBefore` method where you can set the target and there's an annotation to put on filters iirc. – zapl Oct 01 '22 at 03:14
  • You forgot "to `@Bean`" `SecurityFilterChain`!? ...https://spring.io/guides/gs/securing-web/ ..i am not sure, whether it is "mandatory", but sample shows "with bean annotation".. – xerx593 Oct 01 '22 at 09:36
  • Hey xerx, I had add Bean earlier but It was giving me Autowiring error for long time, So i removed it. – Anubhav Sinha Oct 01 '22 at 09:39
  • ..sounds suspect/very different .. please re-add `@Bean`, and let's analyse the auto-wiring error!(?) ..[edit] – xerx593 Oct 01 '22 at 09:49
  • 1
    This is the error its giving, Description: Parameter 0 of method filterChain in com.company.framework.Security.SecurityConfig required a bean of type 'org.springframework.security.config.annotation.web.builders.HttpSecurity' that could not be found. Action: Consider defining a bean of type 'org.springframework.security.config.annotation.web.builders.HttpSecurity' in your configuration. – Anubhav Sinha Oct 01 '22 at 10:22
  • this sounds, like you have a conflicting config!?!? What is `com.company.framework.Security.SecurityConfig` ? In OP, you show: `com.company.framework.filter.SecurityConfig`!! – xerx593 Oct 02 '22 at 14:48

1 Answers1

0

Seems you missed overriding the configure method of WebSecurityConfigurerAdapter class. This is the main logic to override the default spring security logic. This is the main problem i guess. try to extend that class(WebSecurityConfigurerAdapter) and override that method(configure) in SecurityConfig.java.

SecurityConfig.java

package com.company.framework.filter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurer{


    @Autowired private AuthFilter filtet;

    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        System.out.println("reaching here3 ");
        http
        .csrf().disable()
        .authorizeRequests()
        .antMatchers("/api/v1/open/**").permitAll()
         .and()
         .exceptionHandling()
            .authenticationEntryPoint(
         (request, response,     authException) ->
                                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Error here")
                    )
                .and()
                .sessionManagement()
                .and()
                .httpBasic().disable();

        http.addFilter(filtet);
        return http.build();
    }
}
  • That is the old deprecated way. OP used the new way. See: https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter.html – dur Oct 01 '22 at 09:19