This article has participated in the call for good writing activities, click to view: back end, big front end double track submission, 20,000 yuan prize pool waiting for you to challenge

Springsecurity access to logged-in user data

Retrieves user information from the current request object

@RequestMapping("/authentication")
public void authentication(Authentication authentication) {
    System.out.println("authentication = " + authentication);
}
@RequestMapping("/principal")
public void principal(Principal principal, HttpServletRequest req) {
    System.out.println("req.getClass() = " + req.getClass());
    System.out.println("principal = " + principal);
}
@RequestMapping("/info")
public void info(HttpServletRequest req) {
    String remoteUser = req.getRemoteUser();
    Authentication auth = ((Authentication) req.getUserPrincipal());
    boolean admin = req.isUserInRole("admin");
    System.out.println("remoteUser = " + remoteUser);
    System.out.println("auth.getName() = " + auth.getName());
    System.out.println("admin = " + admin);
}
Copy the code

The request parameters of Controller in SpringMVC are all brought by the current request HttpServletRequest, and the Authentication Principal is also brought by HttpServletRequest. We got it in the Controller layer instance is Servlet3SecurityContextHolderAwareRequestWrapper

Servlet3SecurityContextHolderAwareRequestWrapper

Servlet3SecurityContextHolderAwareRequestWrapper inheritance SecurityContextHolderAwareRequestWrapper The main see SecurityContextHolderAwareRequestWrapper

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.security.web.servletapi;

import java.security.Principal;
import java.util.Collection;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;

public class SecurityContextHolderAwareRequestWrapper extends HttpServletRequestWrapper {
    private final AuthenticationTrustResolver trustResolver;
    private final String rolePrefix;

    public SecurityContextHolderAwareRequestWrapper(HttpServletRequest request, String rolePrefix) {
        this(request, new AuthenticationTrustResolverImpl(), rolePrefix);
    }

    public SecurityContextHolderAwareRequestWrapper(HttpServletRequest request, AuthenticationTrustResolver trustResolver, String rolePrefix) {
        super(request);
        Assert.notNull(trustResolver, "trustResolver cannot be null");
        this.rolePrefix = rolePrefix;
        this.trustResolver = trustResolver;
    }

    private Authentication getAuthentication(a) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return !this.trustResolver.isAnonymous(auth) ? auth : null;
    }

    public String getRemoteUser(a) {
        Authentication auth = this.getAuthentication();
        if(auth ! =null&& auth.getPrincipal() ! =null) {
            return auth.getPrincipal() instanceof UserDetails ? ((UserDetails)auth.getPrincipal()).getUsername() : auth.getPrincipal().toString();
        } else {
            return null; }}public Principal getUserPrincipal(a) {
        Authentication auth = this.getAuthentication();
        returnauth ! =null&& auth.getPrincipal() ! =null ? auth : null;
    }

    private boolean isGranted(String role) {
        Authentication auth = this.getAuthentication();
        if (this.rolePrefix ! =null&& role ! =null && !role.startsWith(this.rolePrefix)) {
            role = this.rolePrefix + role;
        }

        if(auth ! =null&& auth.getPrincipal() ! =null) {
            Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
            if (authorities == null) {
                return false;
            } else {
                Iterator var4 = authorities.iterator();

                GrantedAuthority grantedAuthority;
                do {
                    if(! var4.hasNext()) {return false;
                    }

                    grantedAuthority = (GrantedAuthority)var4.next();
                } while(! role.equals(grantedAuthority.getAuthority()));return true; }}else {
            return false; }}public boolean isUserInRole(String role) {
        return this.isGranted(role);
    }

    public String toString(a) {
        return "SecurityContextHolderAwareRequestWrapper[ " + this.getRequest() + "]"; }}Copy the code
  • GetAuthentication: Gets the current login object Authentication Is not anonymous Yes Anonymous returns NULL
  • GetRemoteUser: returns the Principal information of the current login user name in Authentication
  • GetUserPrincipal: Returns the current login object
  • IsGranted: Checks whether the role is specified
  • IsUserInRole: calls isGranted

SecurityContextHolderAwareRequestFilter

So how Security will be the default request into Servlet3SecurityContextHolderAwareRequestWrapper?

Are implemented in the filter chain SecurityContextHolderAwareRequestFilter, SecurityContextHolderAwareRequestFilter main role is to repackaging it request, rewrite it and safety management related methods.

SecurityContextHolderAwareRequestFilter source code:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.security.web.servletapi;

import java.io.IOException;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.Assert;
import org.springframework.web.filter.GenericFilterBean;

public class SecurityContextHolderAwareRequestFilter extends GenericFilterBean {
    private String rolePrefix = "ROLE_";
    private HttpServletRequestFactory requestFactory;
    private AuthenticationEntryPoint authenticationEntryPoint;
    private AuthenticationManager authenticationManager;
    private List<LogoutHandler> logoutHandlers;
    private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();

    public SecurityContextHolderAwareRequestFilter(a) {}public void setRolePrefix(String rolePrefix) {
        Assert.notNull(rolePrefix, "Role prefix must not be null");
        this.rolePrefix = rolePrefix;
        this.updateFactory();
    }

    public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {
        this.authenticationEntryPoint = authenticationEntryPoint;
    }

    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    public void setLogoutHandlers(List<LogoutHandler> logoutHandlers) {
        this.logoutHandlers = logoutHandlers;
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(this.requestFactory.create((HttpServletRequest)req, (HttpServletResponse)res), res);
    }

    public void afterPropertiesSet(a) throws ServletException {
        super.afterPropertiesSet();
        this.updateFactory();
    }

    private void updateFactory(a) {
        String rolePrefix = this.rolePrefix;
        this.requestFactory = this.createServlet3Factory(rolePrefix);
    }

    public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
        Assert.notNull(trustResolver, "trustResolver cannot be null");
        this.trustResolver = trustResolver;
        this.updateFactory();
    }

    private HttpServletRequestFactory createServlet3Factory(String rolePrefix) {
        HttpServlet3RequestFactory factory = new HttpServlet3RequestFactory(rolePrefix);
        factory.setTrustResolver(this.trustResolver);
        factory.setAuthenticationEntryPoint(this.authenticationEntryPoint);
        factory.setAuthenticationManager(this.authenticationManager);
        factory.setLogoutHandlers(this.logoutHandlers);
        returnfactory; }}Copy the code

DoFilter method called requestFactory. The create method this method directly created Servlet3SecurityContextHolderAwareRequestWrapper instance. Then, the SpringMVC ServletRequestMethodArgumentResolver resolveArgument parsing out the Principal object Authentication object.