Home > Net >  Not able to access static resources directory without logging in(I am using spring security)
Not able to access static resources directory without logging in(I am using spring security)

Time:10-13

Problem: I cannot access static resources like images, js or css files located under default resources folder of a spring boot project. I am using spring boot version (2.4.9). Now, after doing a lot of research I came up with a solution which I found on spring doc website, which is, use the following piece of code:

.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()

Now the funny thing is, after using this piece of code I am still not able to access any file or folder under the resources folder, but I can access a folder named images (I made it) under resources folder. Any solutions or helpful tip ?

The Directory structure of my project:

screenshot of project directory

SecurityConfiguration File:

package com.pisoft.informatics.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Configuration;
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;

@Configuration
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
     
    //bcrypt bean definition
    /*
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    */
      
    @Autowired
    private MeriCustomAuthenticationProvider authProvider;
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //auth.authenticationProvider(authenticationProvider());
        auth.authenticationProvider(authProvider);
    }
        
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
        http.authorizeRequests()    
            //.antMatchers("/resources/**").permitAll()         
            .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()           
            .anyRequest().authenticated()           
            
            .and()
            .formLogin()                
                .loginPage("/")
                .loginProcessingUrl("/authenticateTheUser")
                .successHandler(customAuthenticationSuccessHandler)
                .permitAll()
            .and()
            .logout()
            .permitAll()
                    
            .and()
            .csrf().disable();  
    }
}

CustomAuthenticationProvider File:

package com.pisoft.informatics.security;

import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import com.pisoft.informatics.entity.user.CrmUser;
import com.pisoft.informatics.misc.EncryptionUtil1;
import com.pisoft.informatics.service.user.CrmUserService;



@Component
public class MeriCustomAuthenticationProvider implements AuthenticationProvider{

    @Autowired
    private CrmUserService userService;
    
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
        
        //System.out.println("name :" name " password :" password);
        
            // use the credentials
            CrmUser user= userService.findByUserName(name);
            if(user!=null) {
                if(password.equalsIgnoreCase(EncryptionUtil1.decode(user.getPassword()))) {
                    if(user.getStatus().equalsIgnoreCase("Active")) {
                        return new UsernamePasswordAuthenticationToken(name, password, new ArrayList<>());
                    }
                    else {
                        return null;
                    }
                }
                else {
                    return null;
                }
            }
            else {
                return null;
            }                   
    }

    @Override
    public boolean supports(Class<?> authentication) {
        
         return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }   
}

SecurityWebApplicationInitializer File:

package com.pisoft.informatics.security;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{

}

CustomAuthenticationSuccessHandler File:

package com.pisoft.informatics.security;


import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import com.pisoft.informatics.misc.*;
import com.pisoft.informatics.entity.user.CrmUser;
import com.pisoft.informatics.service.sidebar.ServiceHeader;
import com.pisoft.informatics.service.user.CrmUserService;

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private CrmUserService crmUserService;
   
    @Autowired
    private ServiceHeader headerService;
    
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        
        String userName = authentication.getName();
        CrmUser theUser = crmUserService.findByUserName(userName);
        
        // now place in the session
        HttpSession session = request.getSession();
        session.setAttribute("CRMUserDetails", theUser);
        session.setAttribute("allMenus", headerService.getMeAllMainMenus());
        session.setAttribute("greetings", WishUtill.Wish());
        // forward to home page
        
        response.sendRedirect(request.getContextPath()   "/dashboard");
    }

}

CodePudding user response:

You have quite a few directories under /static that are not matched by PathRequest.toStaticResources().atCommonLocations(). The following locations are matched: /static/css/**, /static/js/**, /static/images/**, /static/webjars/**, /static/favicon.*, and /static/*/icon-*. This is why your images are accessible. You will need to add antMatchers for your custom locations with permitAll() (e.g. antMatchers("/build/**", "/delete-popup/**", ...).permitAll().

  • Related