How to run two Websecurity classes in Spring

Asked

Viewed 75 times

0

I have a project that performs authentications through JWT Token, and it uses Swagger, so I made a login and registration page to authenticate before entering Swagger, but I did not want to authenticate through tokens, so I decided to create another configuration class to do so authentication, but they are giving conflict, someone has some idea of how to use two Websecurity configuration classes in the same spring project?

Springsecurityconfig

package br.com.sinergico.security;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

@Configuration
@EnableWebSecurity
@Component
@EnableGlobalMethodSecurity(securedEnabled=true)
@Order(1)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenAuthenticationService tokenAuthenticationService;

    private TokenAuthenticationPortadorService tokenAuthenticationPortadorService;

    private PortadorService portadorService;

    private TokenAuthenticationEstabelecimentoService tokenAuthenticationEstabelecimentoService;

    @Autowired
    private UserEstabelecimentoService userEstabelecimentoService;

    public SpringSecurityConfig() {
        super(true);
    }

    @PostConstruct
    public void teste() {
        tokenAuthenticationService = new TokenAuthenticationService(userService);
        portadorService = new PortadorService();
        tokenAuthenticationPortadorService = new TokenAuthenticationPortadorService(portadorService);
        tokenAuthenticationEstabelecimentoService = new TokenAuthenticationEstabelecimentoService(userEstabelecimentoService);
    }

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

        http.exceptionHandling().and().anonymous().and().servletApi().and()
                // .headers().cacheControl().and().
                .authorizeRequests()

                //Paths necessários para o Swagger
                .antMatchers("/v2/api-docs").permitAll()
                .antMatchers("/swagger-resources/configuration/ui").permitAll()
                .antMatchers("/swagger-resources").permitAll()
                .antMatchers("/swagger-resources/configuration/security").permitAll()
                .antMatchers("/webjars/**").permitAll()

                // All other request need to be authenticated
                .anyRequest().authenticated().and()

                // Custom Token based authentication based on the header
                // previously given to the client
                .addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService,tokenAuthenticationPortadorService, tokenAuthenticationEstabelecimentoService),
                        UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/v2/api-docs")
                  .antMatchers("/swagger-resources/configuration/ui")
                  .antMatchers("/swagger-resources")
                  .antMatchers("/webjars/**")
                  .antMatchers("/swagger-resources/configuration/security");
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    @Override
    public UserService userDetailsService() {
        return userService;
    }

    @Bean
    public TokenAuthenticationService tokenAuthenticationService() {
        return tokenAuthenticationService;
    }

    @Bean
    public TokenAuthenticationPortadorService tokenAuthenticationPortadorService(){
        return tokenAuthenticationPortadorService;
    }

    @Bean
    public TokenAuthenticationEstabelecimentoService tokenAuthenticationEstabelecimentoService(){
        return tokenAuthenticationEstabelecimentoService;
    }

}

Swaggersecurityconfig

package br.com.sinergico.security;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
@Order(2)
public class SwaggerSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private DataSource dataSource;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder;
    }

    private final String SWAGGER_ACESSO_QUERY = "select login, senha, status from suporte.swagger_acesso where login=?";
    private final String ROLE_ACESSO_QUERY = "select u.login, r.role from suporte.swagger_acesso u inner join suporte.swagger_acesso_role ur "
            + "on (u.id_usuario = ur.id_usuario) inner join suporte.swagger_role r on (ur.role_id=r.role_id) where u.login=?";

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests()
          .antMatchers("/").permitAll()
          .antMatchers("/login").permitAll()
          .antMatchers("/signup").permitAll()
          .antMatchers("/swagger-ui.html").authenticated()
          .and().csrf().disable()
          .formLogin().loginPage("/login").failureUrl("/login?error=true")
          .defaultSuccessUrl("/swagger-ui.html")
          .usernameParameter("login")
          .passwordParameter("senha")
          .and().rememberMe();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
          .jdbcAuthentication()
          .usersByUsernameQuery(SWAGGER_ACESSO_QUERY)
          .authoritiesByUsernameQuery(ROLE_ACESSO_QUERY)
          .dataSource(dataSource)
          .passwordEncoder(bCryptPasswordEncoder);

     }
}

You are making the mistake that one conflicts with the other, when I put in "Springsecurityconfig" = @Order(1) and in the other @Order(2), Springsecurityconfig blocks all methods that are allowed in Swaggersecurityconfig and if it is contrary to the same thing.

  • Puts what you’ve implemented so far, and the error presented.

  • @Giulianabezerra Edited

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.