'Setting User Principal in filter

I have an authentication filter that implements filter.

by typcasting ServletRequest to HTTPServletRequest i can get the userPrincipal.

public void doFilter(ServletRequest request, ServletResponse response, 
FilterChain chain)
        throws IOException, ServletException {



    HttpServletRequest httpServletRequest = (HttpServletRequest) request;

 // code to resolve user name from apikey

    Principal principal = httpServletRequest.getUserPrincipal();

My question is how do i set the Principal? so that i can pass in the authenticated users name;

or should i just pass the name as an additional parameter using HttpServletRequestWrapper?



Solution 1:[1]

Actually i didn't realise HttpServletRequestWrapper had getUserPrincipal() method that i could just override

Solution 2:[2]

Assuming you need principal in request to be present while you disabled spring security. please refer following link for security disable https://stackoverflow.com/a/61120549/6459098

we need interceptor and UserDetailsService as below to have custom principal for each request.

@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if(request.getUserPrincipal()==null)//initially no principal found
            request.login("uname", "pwd");//add principal to request
        return true;
    }

Then

@Component
class UserDetailsServiceTools implements UserDetailsService {
    @Override
        public UserDetails loadUserByUsername(String username){
            // TODO Auto-generated method stub
                return User.withUsername(username).password("{noop}pwd").roles("User").build();
        }
}

Solution 3:[3]

  1. Create a custom class extending HttpServletRequestWrapper
import java.security.Principal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class UserPrincipalHttpServletRequest extends HttpServletRequestWrapper {

  private final Principal principal;

  public UserPrincipalHttpServletRequest(HttpServletRequest request, Principal principal) {
    super(request);
    this.principal = principal;
  }

  @Override
  public Principal getUserPrincipal() {
    return principal;
  }
}
  1. In your filter, add the
protected void doFilterInternal(HttpServletRequest request){
    
    . . . 

    // create user details, roles are required
    Set<GrantedAuthority> authorities = new HashSet<>();
    authorities.add(new SimpleGrantedAuthority("SOME ROLE"));
    UserDetails userDetails = new User("SOME USERNAME", "SOME PASSWORD", authorities);

    // Create an authentication token
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
    usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

    // follow the filter chain, using the new wrapped UserPrincipalHtppServletRequest
    chain.doFilter(new UserPrincipalHttpServletRequest(request, usernamePasswordAuthenticationToken), response);
    // all filters coming up, will be able to run request.getUserPrincipal()
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Claudiga
Solution 2 U_R_Naveen UR_Naveen
Solution 3 ozzi-