Analysis of the principle of using spring security and (2)

Transfer from https://pjmike.github.io/2018/10/12/%E6%B5%85%E6%9E%90Spring-Security-%E6%A0%B8%E5%BF%83%E7%BB%84 % E4% BB% B6 /

Previous We mainly about how to take the project, here we have to simply explore what principle

 

Spring Security's core classes

Spring Security's core categories include the following:

  • The SecurityContextHolder : identity information stored containers
  • Authentication : abstract interface identity information
  • The AuthenticationManager : authentication device, certified core interface
  • UserDetailsService : generally used for loading the identity information from the database
  • UserDetails : Compared Authentication, more detailed status information

SecurityContextHolder、Securityontext和Authentication

SecurityContextHolderFor storing the security context (security context) information, i.e., a storage container identification information, authentication information and the like. SecurityContextHolderDefault ThreadLocalpolicy to store authentication information, a strategy that is bound with thread, you can obtain the security context of that thread (security context) each thread execution, each thread in the security context of each other. And if you want to clear the information security context after the request by the Spring Security policy can be easy to get.

Because identifiable information with thread-bound, so we can use the static method to obtain user information anywhere in the program, an example of the currently logged on user name acquisition as follows:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}
View Code

 

getAuthentication()Method returns the authentication information, accurate to say that a Authenticationinstance, Authenticationis Spring Security is an important interface directly inherited from the Principal class, the interface represents the abstract information on the identity of the user interface source code as follows:

public  interface Authentication the extends Principal, Serializable { 
     // authority information list, the default is some implementations GrantedAuthority interface 
    Collection <? the extends GrantedAuthority> getAuthorities (); 
     // will usually be removed after the password information, password string entered by the user, the authentication used to ensure the safety of 
    Object getCredentials ();
     // details, web applications typically interface for WebAuthenticationDetails, it records the value of the ip address of the visitor and sessionId 
    Object getDetails ();
     // identity, return an implementation of UserDetails class 
    Object getPrincipal ();
     // certification status, the default is false, the authentication is successful to true 
    boolean isAuthenticated ();
     // above information is through identity authentication 
    void setAuthenticated (boolean var1) throws IllegalArgumentException;
}
View Code

 

AuthenticationManager、ProviderManager 和 AuthenticationProvider

Framework used to implement functions to be registered

Be clear source

UserDetailsService 和 UserDetails

UserDetailsServiceIt is simply load the corresponding UserDetailsinterfaces (typically from a database), which UserDetailscontains more detailed information about the user , defined as follows:

public interface UserDetails extends Serializable {

   Collection<? extends GrantedAuthority> getAuthorities();

   String getPassword();

   String getUsername();

   boolean isAccountNonExpired();

   boolean isAccountNonLocked();

   boolean isCredentialsNonExpired();

   boolean isEnabled();
}
View Code

UserDetails similar interface Authentication interfaces, they have username, authorities. Their differences are as follows:

  • Authentication of getCredentials () and UserDetails in getPassword () is not the same, the former is password credentials submitted by the user, which is the correct user password (usually loaded from the database password), AuthenticationProviderwill be to compare the two .
  • Authentication in getAuthorities () actually () delivered by the getAuthorities UserDetails formed.
  • Authentication of getUserDetails passes UserDetails user details () is AuthenticationProviderthen filled with authentication.

Sample official certification process

public class SpringSecuriryTestDemo {
    private static AuthenticationManager am = new SampleAuthenticationManager();

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            System.out.println("Please enter your username:");
            String name = in.readLine();
            System.out.println("Please enter your password:");
            String password = in.readLine();
            try {
                Authentication request = new UsernamePasswordAuthenticationToken(name, password);
                Authentication result = am.authenticate(request);
                SecurityContextHolder.getContext().setAuthentication(request);
                break;
            } catch (AuthenticationException e) {
                System.out.println("Authentication failed: " + e.getMessage());
            }
        }
        System.out.println("Successfully authenticated. Security context contains: " + SecurityContextHolder.getContext().getAuthentication());
    }
    static class SampleAuthenticationManager implements AuthenticationManager {
        static final List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();
        static {
            AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
        }
        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            if (authentication.getName().equals(authentication.getCredentials())) {
                return new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials(), AUTHORITIES);
            }
            throw new BadCredentialsException("Bad Credentials");
        }
    }
}
View Code

 

result

Please enter your username:
pjmike
Please enter your password:
123
Authentication failed: Bad Credentials
Please enter your username:
pjmike
Please enter your password:
pjmike
Successfully authenticated. 
Security context contains: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@441d0230:
Principal: pjmike; 
Credentials: [PROTECTED];
Authenticated: true; Details: null; 
Granted Authorities: ROLE_USER
View Code

 

Learn a simple certification process, under a look at the filter chain spring security

Guess you like

Origin www.cnblogs.com/jiataoq/p/11073683.html
Recommended