0

Is it possible in the Spring Security to (well it is Java, of course possible, so quesiton is - is it possible in some relatively painless way) automatically authorize all requests from local host (OK, some given IP) as a request that belongs to a given test user.

For instance in some filter - take all requests, check IP and if it comes from local host say something like spring.authorizeAs("user")

Denis
  • 1,181
  • 2
  • 11
  • 18

2 Answers2

0

This answer for the similar question may help you. Based on your requirements you build principal and set it manually to Security Context.

humb1t
  • 87
  • 1
  • 4
0

In my case answer is following

@Component
public class LocalAuthFilter implements Filter {


    @Autowired
    private UserDetailsService mng;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        if (("127.0.0.1".equals(req.getRemoteAddr())) &&
                ("anonymousUser".equals(SecurityContextHolder.getContext().getAuthentication().getPrincipal()))) {
            UserDetails userDetails = mng.loadUserByUsername("user"); //my test user
            Authentication auth = new UsernamePasswordAuthenticationToken(
                    userDetails.getUsername(),
                    userDetails.getPassword(),
                    userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        filterChain.doFilter(req, resp);
    }

    @Override
    public void destroy() {

    }
}
Denis
  • 1,181
  • 2
  • 11
  • 18