Spring Security application practice

summary

Spring Security is a framework launched by spring in terms of security. It adopts the design pattern of responsibility chain and is implemented based on Spring AOP and Servlet filter. This article documents some concepts of authentication authorization and how to use it to extend and protect our applications.

Concept of authentication and authorization

  • Certification: who am I
  • Authorization: what access rights do you have

In terms of system security, we are faced with two problems:

1. How do I protect resources that require access?

In Java, we usually use filters to protect our resources and interceptors to control the access of methods.

2. How to transfer the user's login status?

How to make the server aware that the user has logged in to the system? One is to use Session for authentication, and the other is to use Token for authentication.

Session authentication

The disadvantages of this authentication method are: first, it cannot be used for mobile terminal authentication; second, once the client disables the browser Cookie, it will fail to authenticate. The following is the process based on Session authentication:

User password login --> The server passes the authentication and creates a Session(A small area of memory in a server),Store login user information 
--> return SessionID,Write user Cookie --> Cookie Will be sent with each subsequent request --> take SessionID Compare with the information in the server

Token authentication

  • Custom Token

We can generate a user-defined token after successful user authentication, save it in Redis or memory and return it to the front end. Each subsequent request of the user carries the token in the request header Authorization instead of storing the authentication information in the request header Cookie. Then we compare the token in the request header with the token stored by the server to verify the user's login status.

  • JWT(JSON Web Tokens):

Another option is to use JWT.
Advantages: 1. There is no need to store the Token. It can be verified directly through calculation and change time for space. 2. 2. User related information can be stored in the Token
Disadvantages: tokens cannot be discarded at any time.

Spring Security configuration

Spring Security is a highly configurable framework. We can inherit or implement relevant classes to realize customization functions. The following is an example of a configuration:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@RequiredArgsConstructor
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final AuthSuccessHandler authSuccessHandler;

    private final AuthFailureHandler authFailureHandler;

    private final SimpleAccessDeniedHandler accessDeniedHandler;

    private final SimpleAuthenticationEntryPoint authenticationEntryPoint;

    private final JwtProperties jwtProperties;

    /**
     * Configure interfaces that do not require authentication
     */
    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
                .antMatchers(HttpMethod.OPTIONS, "/**")
                .antMatchers("/css/**")
                .antMatchers("/signUp.html")
                .antMatchers("/user/**")
                .antMatchers("/common/test")
                .antMatchers("/test");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/login")
                .successHandler(authSuccessHandler)
                .failureHandler(authFailureHandler)
                .permitAll()
                .and()
                .headers()
                .frameOptions()
                .disable()
                .and()
                .authorizeRequests()
                .antMatchers("/login.html").permitAll()
                //Turn on authentication
                .anyRequest().authenticated()
                .and().csrf().disable()
                //JWT is used for front and rear end separation, and session is not required
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                //Add custom permission filter
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler)
                .and()
                .addFilter(new JwtAuthorizationFilter(authenticationManager(), jwtProperties.getSecretKey()));
    }
}

In a brief summary, we can see from the above code that we can make the following configurations:
1. Configure paths that do not require authentication
2. By adding a filter, you can customize the Token authentication logic, mainly by overriding the authentication method through inheritance: BasicAuthenticationFilter
3. Customize some processors:

  • Successful authentication processor: what subsequent processing is required after successful authentication? For example, JSON data is returned to the front end mainly by implementing the AuthenticationSuccessHandler interface
  • Authentication failure processor: what should I do when authentication fails? For example, the user-defined authentication failure information is returned. When the front and back ends are separated, the JSON data of authentication failure can be returned to the front end, mainly through the implementation of the AuthenticationFailureHandler interface

4. How do you handle exceptions when you are not authorized to access resources that require permission? Some more friendly tips can be thrown: main implementation: AuthenticationEntryPoint interface
5. Exception handling for insufficient permissions. For example, when the front and back ends are separated, you can customize the return of JSON data, mainly through the implementation of the SimpleAccessDeniedHandler interface
6. Where to get user information? We can implement the UserDetailsService interface and the loadUserByUsername method to let the program get our data from the database.

last

The code involved can be clicked here

Reference link

Personal blog: https://www.kangpeiqin.cn/#/index

Keywords: Java Spring Back-end

Added by mausie on Thu, 20 Jan 2022 13:48:10 +0200