1. This article comes from Silicon Valley and is not suitable for beginners.
2. Come back with a certain foundation.
Part I
1, Understanding part
1. Introduction to spring security
Let's put it this way. It's a very boastful security framework. It mainly does two things: Authentication and Authorization
2. History
Its history, you can search and have a look, no more
3. Advantages
SpringSecurity features:
- Seamless integration with Spring.
- Comprehensive authority control.
- Designed specifically for Web development.
- The old version cannot be used away from the Web environment.
- The new version extracts the whole framework hierarchically, which is divided into core module and Web module. alone
The introduction of core modules can be separated from the Web environment.
- Heavyweight.
4. Same level framework
shiro, this is also the article I will publish later
5. Match
shiro + ssm is better
SpringSecurity + SpringBoot/Spring Cloud
6. Core module
2, Case
1. Write class
Be sure to remember the following categories, which will probably accompany our article
- WebSecurityConfigurerAdapter: custom Security policy
- AuthenticationManagerBuilder: custom authentication policy
- @Enable WebSecurity: enable WebSecurity mode
@Configuration public class SecurityConfigextends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() // Form login .and() .authorizeRequests() // Authentication configuration .anyRequest() // Any request .authenticated(); // All require authentication } }
2. Important words
1. principal: principal
Users who use the system or equipment or other systems, users who log in to the remote system, etc. It is roughly the subject who uses the system.
2. authentication
The permission management system confirms the identity of an entity and allows the entity to enter the system. Simply put, it means that you can log in after authentication.
3. Authorization: authorization
Is what kind of role you have, and then what rights you will have
3. How spring security works
Spring security is essentially a filter chain:
The filter chain can be obtained from startup:
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFil ter org.springframework.security.web.context.SecurityContextPersistenceFilter org.springframework.security.web.header.HeaderWriterFilter org.springframework.security.web.csrf.CsrfFilter org.springframework.security.web.authentication.logout.LogoutFilter org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter org.springframework.security.web.savedrequest.RequestCacheAwareFilter org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter org.springframework.security.web.authentication.AnonymousAuthenticationFilter org.springframework.security.web.session.SessionManagementFilter org.springframework.security.web.access.ExceptionTranslationFilter org.springframework.security.web.access.intercept.FilterSecurityInterceptor
There are three key points:
(1)FilterSecurityInterceptor
-
FilterSecurityInterceptor: it is a method level permission filter, which is basically located at the bottom of the filter chain.
-
Kangkang this
- super.beforeInvocation(fi) means to check whether the previous filter has passed.
- fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); Represents the real call to the background service.
(2)ExceptionTranslationFilter
- Is an exception filter used to handle exceptions thrown during authentication and authorization
- Look at this
(3)UsernamePasswordAuthenticationFilter
- : intercept the POST request of / login and verify the user name and password in the form
- Look at this
- There is a method: the return is UserDetails, which is the default user of the system (i.e. pincipal). Of course, we will also write classes inherited from this class
(4) Let's talk about UserDetailsService alone
This class provides a method that will work with us
principal is related to UserDetails. Just know this here. We usually write a User to implement UserDetails and configure spring security to implement security management
public class User implements UserDetails { @Override public Collection<? extends GrantedAuthority> getAuthorities() { return null; } @Override public String getPassword() { return null; } @Override public String getUsername() { return null; } @Override public boolean isAccountNonExpired() { return false; } @Override public boolean isAccountNonLocked() { return false; } @Override public boolean isCredentialsNonExpired() { return false; } @Override public boolean isEnabled() { return false; } }
(5) PasswordEncoder interface explanation
1. Interface Overview
public interface PasswordEncoder { // It means to parse parameters according to specific parsing rules String encode(CharSequence var1); // Means to verify whether the encoded password obtained from the store matches the original password submitted after encoding. If the password matches If not, return true;If not, returns false. The first parameter represents the password that needs to be resolved. the second Parameter represents the stored password. boolean matches(CharSequence var1, String var2); // Indicates that if the parsed password can be parsed again and achieve more secure results, it returns true; otherwise, it returns true false. Default return false. default boolean upgradeEncoding(String encodedPassword) { return false; } }
2. Implementation class
There are several classes that implement the above interface, but the best is the following class
- BCryptPasswordEncoder is a password parser officially recommended by Spring Security. It is usually used
Device. - BCryptPasswordEncoder is a concrete implementation of bcrypt strong Hash method. It is based on Hash algorithm
Encryption to. You can control the encryption strength through strength. The default value is 10
3. Testing
@Test public void test01(){ // Create password parser BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); // Encrypt password String atguigu = bCryptPasswordEncoder.encode("atguigu"); // Print encrypted data System.out.println("Data after encryption:\t"+atguigu); //Judge whether the original characters match after encryption and before encryption boolean result = bCryptPasswordEncoder.matches("atguigu", atguigu); // Print comparison results System.out.println("Comparison results:\t"+result); }