Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the core configurations of Spring Security

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the core configuration of Spring Security". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what the core configuration of Spring Security is.

Core configuration interpretation 3.1 function introduction

This is the configuration item in the Spring Security getting started Guide:

@ Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@ Override protected void configure (HttpSecurity http) throws Exception {http .authorizeRequests () .antMatrices ("/" "/ home") .permitAll () .anyRequest () .authenticated () .and () .formLogin () .loginPage ("/ login") .permitAll () .and () .logout () .permitAll () @ Autowired public void configureGlobal (AuthenticationManagerBuilder auth) throws Exception {auth .inMemoryAuthentication () .withUser ("admin") .password ("admin") .roles ("USER");}}

After configuring the above javaconfig, our application has the following features:

Except for "/", "/ home" (home page), "/ login" (login), "/ logout" (logout), all other paths require authentication.

Specify "/ login" the path as the login page, which jumps to "/ login" when an unauthenticated user attempts to access any protected resources.

By default, "/ logout" is specified as the logout page

Configure a user authenticator in memory, using admin/admin as the username and password, with the USER role

Prevent CSRF attacks

Session Fixation protection (please refer to my previous article on Spring Session to prevent others from tampering with sessionId)

Security Header (add a series of Header-related controls)

HTTP Strict Transport Security for secure requests

Integrated X-Content-Type-Options

Cache control

Integrated X-XSS-Protection

X-Frame-Options integration to help prevent Clickjacking (iframe is prohibited by default)

The following methods are integrated for Servlet API

HttpServletRequest#getRemoteUser ()

HttpServletRequest.html#getUserPrincipal ()

HttpServletRequest.html#isUserInRole (java.lang.String)

HttpServletRequest.html#login (java.lang.String, java.lang.String)

HttpServletRequest.html#logout ()

3.2 @ EnableWebSecurity

Our self-defined configuration class WebSecurityConfig adds the @ EnableWebSecurity annotation and inherits WebSecurityConfigurerAdapter. You may be wondering who plays a bigger role, but there is no doubt that @ EnableWebSecurity plays a decisive role in configuration, which is actually a combinatorial annotation.

Import ({WebSecurityConfiguration.class, / / SpringWebMvcImportSelector.class}) / / @ EnableGlobalAuthentication / / @ Configurationpublic @ interface EnableWebSecurity {boolean debug () default false;}

@ Import is an annotation provided by springboot to introduce external configurations, which can be understood as: the @ EnableWebSecurity annotation activates the configuration classes included in the @ Import annotation.

@ Import (AuthenticationConfiguration.class) @ Configurationpublic @ interface EnableGlobalAuthentication {}

Note also in @ Import, which actually activates a configuration class such as AuthenticationConfiguration, which is used to configure authentication-related core classes.

In other words, @ EnableWebSecurity loads the two core configuration classes, WebSecurityConfiguration,AuthenticationConfiguration, and divides the responsibility of spring security into two parts: configuring security information and configuring authentication information.

WebSecurityConfiguration

In this configuration class, a very important Bean is registered.

Configurationpublic class WebSecurityConfiguration {/ / DEFAULT_FILTER_NAME = "springSecurityFilterChain" @ Bean (name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME) public Filter springSecurityFilterChain () throws Exception {...}}

Before using springboot, most people should be familiar with the term "springSecurityFilterChain", which is the core filter of spring security and the entrance to the entire certification. In the previous XML configuration, to enable spring security, you need to configure the following in web.xml:

SpringSecurityFilterChain org.springframework.web.filter.DelegatingFilterProxy springSecurityFilterChain / *

After springboot integration, such XML is replaced by java configuration. The function of declaring springSecurityFilterChain in WebSecurityConfiguration is completed, and it is finally handed over to the proxy class DelegatingFilterProxy, which is responsible for intercepting requests (note that the class DelegatingFilterProxy is not in the spring security package, but exists in the web package, and spring uses the proxy pattern to decouple security filtering).

AuthenticationConfiguration@Configuration@Import (ObjectPostProcessorConfiguration.class) public class AuthenticationConfiguration {@ Bean public AuthenticationManagerBuilder authenticationManagerBuilder (ObjectPostProcessor objectPostProcessor) {return new AuthenticationManagerBuilder (objectPostProcessor);} public AuthenticationManager getAuthenticationManager () throws Exception {...}}

The main task of AuthenticationConfiguration is to generate a global authentication manager AuthenticationManager. I still remember that in "Spring Security (1)-Architecture Overview", the authentication system of Spring Security is introduced, and AuthenticationManager is the core identity authentication manager.

3.3 WebSecurityConfigurerAdapter

Adapter patterns are widely used in spring, and the advantage of using Adapter in configuration is that we can optionally configure the part of the configuration we want to modify without overwriting other irrelevant configurations. In WebSecurityConfigurerAdapter, we can choose what we want to modify to rewrite it, and it provides three configure overloading methods, which are our main concerns:

As can be known from the parameters, they are the personalized configuration of AuthenticationManagerBuilder,WebSecurity,HttpSecurity.

HttpSecurity common configuration @ Configuration@EnableWebSecuritypublic class CustomWebSecurityConfig extends WebSecurityConfigurerAdapter {@ Override protected void configure (HttpSecurity http) throws Exception {http .authorizeRequests () .antMatrices ("/ resources/**", "/ signup" "/ about"). PermitAll () .antMatrices ("/ admin/**"). HasRole ("ADMIN") .antMatrices ("/ db/**"). Access ("hasRole ('ADMIN') and hasRole (' DBA')") .anyRequest (). Authenticated () .and () .formLogin () .usernameParameter ("username") .passwordParameter ("password") .failureForwardUrl ("/ login?error") .loginPage ("/ login") .permitAll () .and () .logout () .logoutUrl ("/ logout") .logoutSuccessUrl ("/ index") ") .permitAll () .and () .httpBasic () .disable () }}

The above is a typical configuration that uses Java Configuration to configure HttpSecurity, where http is configured as the root, each and () corresponds to the configuration of a module (equivalent to the closing tag in the xml configuration), and and () returns the HttpSecurity itself, so it can be configured continuously. The meaning of their configuration is also very easy to speculate from the variables themselves.

AuthorizeRequests () configures path interception to indicate the permissions, roles, and authentication information corresponding to path access.

FormLogin () corresponds to the configuration related to form authentication

Logout () corresponds to the configuration related to logout

HttpBasic () can configure basic login

Etc

They represent the security configurations related to http requests. Without exception, these configuration items return the Configurer class, and all http-related configurations can be found by looking at the main methods of HttpSecurity:

Some knowledge of the http protocol is required to fully grasp all the configurations, but the automatic configuration of springboot and spring security is sufficient. Each of these Configurer (e.g.FormLoginConfigurer.CsrfConfigurer) is a detailed configuration item for HttpConfigurer.

WebSecurityBuilder@Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@ Override public void configure (WebSecurity web) throws Exception {web .i gnoring () .antMatrices ("/ resources/**");}}

In my experience, there is not much configuration information in this configuration.

AuthenticationManagerBuilder@Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@ Override protected void configure (AuthenticationManagerBuilder auth) throws Exception {auth .inMemoryAuthentication () .withUser ("admin") .password ("admin") .roles ("USER");}}

To make authentication-related configurations in WebSecurityConfigurerAdapter, you can use configure (AuthenticationManagerBuilder auth) to expose an AuthenticationManager builder: AuthenticationManagerBuilder. As shown above, we have completed the configuration of the users in memory.

Careful friends will find that when we configure users in memory in the previous article, it does not seem to be configured in this way, but rather:

@ Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@ Autowired public void configureGlobal (AuthenticationManagerBuilder auth) throws Exception {auth .inMemoryAuthentication () .withUser ("admin") .password ("admin") .roles ("USER");}}

If your application has only one WebSecurityConfigurerAdapter, then the gap between them can be ignored, and the difference can be seen from the method name: the AuthenticationManagerBuilder injected with @ Autowired is a global authenticator, the scope can span multiple WebSecurityConfigurerAdapter, and affect Method-based security control; while protectedconfigure () is similar to an anonymous inner class, its scope is limited to a WebSecurityConfigurerAdapter.

Thank you for your reading, the above is the content of "what is the core configuration of Spring Security". After the study of this article, I believe you have a deeper understanding of what the core configuration of Spring Security has, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report