Preparing for Spring Professional Certification. Spring security

This article is a translation of the Spring Professional Certification Prep article.







It will cover the topic of Spring Security and its main questions.







It can also be used to prepare for an interview.







↓ Other articles are available at the links in the table of contents ↓







Table of contents
  1. Dependency injection, container, IoC, beans
  2. AOP (aspect-oriented programming)
  3. JDBC, Transactions, JPA, Spring Data
  4. Spring boot
  5. Spring mvc
  6. Spring security
  7. REST
  8. Testing











Questions themselves:







What is authentication and authorization?

Authentication is the process of verifying the user of a computer system.

This is how it happens in Spring:







  1. The resulting password and username is converted to an instance of UsernamePasswordAuthenticationToken . It implements the Authentication interface.
  2. The token is passed to the AuthenticationManager



    object for verification
  3. If successful, AM returns a populated Authentication



    object
  4. The security context is set by calling SecurityContextHolder.getContext().setAuthentication(...)





Authorization is the process of verifying that the user has the role required to take an action. During authorization, it is checked whether you have the appropriate rights to access the resource.







Process:







  1. By the principal (principal) of the user, his role is displayed
  2. User role checked against resource role


First, authentication takes place, and then authentication.







How does security work internally?
  • Using Spring AOP proxies that inherit from the AbstractSecurityInterceptor class.







    It is used for methods that call authorization.







  • Security web infrastructure is based on servlet filters.









The first step is to configure the DelegatingFilterProxy



filter. He delegates the request to FilterChainProxy



.







FilterChainProxy



is a bean that accepts one or more SecurityFilterChain



in the constructor.







SeccurityFilterChain



compares the URL in the request with a list of filters.













Key Features Involved in Spring Security

SecurityContextHolder



- contains and provides access to the SecurityContext in the application.







SecurityContext



- the default implementation of Spring Security containing the Authentication object.







Authentication



- provides a token for an authentication request or for a principal who has authenticated. It also contains a list of powers that the principal has access to.







GrantedAuthority



- Contains the authority granted to the GrantedAuthority



principal.







UserDetails



- contains information about the user: password, login, permissions. This information is used to create an Authentication object after successful authentication.







UserDetailsService



- this service extracts information about the user from the repository (program memory, database, etc.) and puts it in UserDetails.







What is a delegate proxy filter?

The DelegatingFilterProxy



class is a class that implements the javax.Servlet.Filter



interface.







This is a special filter that delegates the work to other beans, which are also filters.







What is security filter chain?

The filter chain implements the SecurityFilterChain



interface. The implementation provided by Spring Security is DefaultSecurityFilterChain.







The DSFC constructor accepts several parameters. The first parameter is request matcher. The remaining parameters are filters that implement the servlet.Filter interface. Here are all the filters accepted by DSFC:







  • ChannelProcessingFilter



  • SecurityContextPersistenceFilter



  • ConcurrentSessionFilter



  • Any auth. filter: UserNamePasswordAuthenticationFilter



    / CasAythenticationFilter



    / BasicAuthenticationFilter



  • SecurityContextHolderAwareRequestFilter



  • JaasApiIntegrationFilter



  • RemeberMeAuthenticationFilter



  • AnonymusAuthenticationFilter



  • ExceptionTranslationFilter



  • FilterSecurityInterceptor





What is a security context?

The primary object is a SecurityContextHolder



. This is the place where details about the current security context are stored, for example, details of the principal who is currently using the application. By default, ThreadLocal



used for storage.







 // SecurityContext SecurityHolderContext.getContext()
      
      





The object returned by the getContext()



method is SecurityContext



. It allows you to receive and set up an Authentication



object.







Authentication



represents the following properties:







  • The collection of powers granted to the principal
  • Data for user identification (login, password)
  • Details - add. information, if needed. May be null
  • Principal
  • Authentication flag - boolean variable that indicates whether the principal passed the test successfully


How to set interception of transition of the user to certain URLs?
 @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() //    /resources .antMatchers("/resources/**").permitAll() //      2  .antMatchers("/").hasAnyRole("ANONYMOUS", "USER") .antMatchers("/login)*").hasAnyRole("ANONYMOUS", "USER") .antMatchers("/logoutr").hasAnyRole("ANONYMOUS", "USER") //      ADMIN .antMatchers("iadmin/*").hasRole("ADMIN") .antMatchers("/events/").hasRole("ADMIN") }
      
      





What does * mean in antMatchers and mvcMatchers () methods?

This expression means “any.”







There are 2 types:







  • *



    - intercepts only at the level at which it is used.







    For example, the pattern “/ orders / *” will check the user’s rights if the user follows







    / orders / aliens or / orders / 1, but not / orders / alien / 1.







  • **



    - intercepts at all levels.

    Any requests will be checked, / orders / aliens, / orders / 1, / orders / alien / 1.









Why is mvcMatcher more secure than antMatcher?

Because antMatcher(“/service”)



maps the request path only to “/service”



, while mvcMatcher(“/service”)



maps to “/service”



, “/service.html”



, “/service.abc” .







Does Spring support password hashing? What is salt?

Yes, it does. There is a PasswordEncoder



interface for hashing, which contains only one method:







static PasswordEncoder createDelegatingPasswordEncoder()



, which returns the default DelegatePasswordEncoder



.







Salt is used to calculate the password hash value. This is a sequence of random numbers that are used to convert a text password to a hash. The salt is stored in clear form next to the hash password and can be used later when converting a clean password to a hash with a new user login.







Why do you need protection for methods? How to install it?

Spring Security supports the protection of individual methods in beans (for example, in controllers). This is an additional layer of protection for the application.







It must be specified explicitly using the @EnableGlobalMethodSecurity



annotation.







What does the @RolesAllowed annotation do?

This annotation is based on the JSR-250.

@RolesAllowed



allows you to configure access to methods (for example, in a controller class) using roles.

Example: @RolesAllowed(“ADMIN”)



will only allow users with the ADMIN



role







To use, you need to set @EnableGlobalMethodSecurity(jsr250Enabled=true)



on the @Configuration class + you need this annotation to be in the classpath.







Tell us about @PreAuthorize

@PreAuthorize



allows you to configure access to the method using SpEL.

To use, you need to set @EnableGlobalMethodSecurity(prePostEnabled=true)









How are all these annotations implemented?

End-to-end functionality is used using Spring AOP (proxy objects).








All Articles