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 common SpringSecurity problems?

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the relevant knowledge of "what are the common SpringSecurity problems". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Login and login handling issues

We already know that the DefaultLoginPageGeneratingFilter of SpringSecurity will generate the login page by default, and this path is login.

But what is the path we use to deal with login?

We can see that the login page is also login.

This is strange, why the same path has a different effect?

Because: HTTP method is different, the login page is a GET request, and the login operation is a POST request.

The operation is so coquettish that countless people flicker.

So, when you do a front-end separation project and the front end uses get ('/ login',optioin) to find that it is 404, don't be surprised, don't cry, maybe change it to post.

How does such a coquettish operation come true?

The answer is in UsernamePasswordAuthenticationFilter:

We can see that UsernamePasswordAuthenticationFilter only matches the login of post, and we can also see why the authentication parameters for UsernamePasswordAuthenticationFilter must be username and password.

In fact, the operation is done in its parent class AbstractAuthenticationProcessingFilter, since Filter must look at the doFilter method and call requiresAuthentication.

2 times login:

First of all, the (login,get) UsernamePasswordAuthenticationFilter skips without processing. If it is a url that needs authorization, then it goes to ExceptionTranslationFilter. Because authentication and authorization are needed, it is redirected to the login page.

Then (login,post) matches, and the authentication operation is completed through UsernamePasswordAuthenticationFilter.

Of course, the above parameters can be configured, for example, login page url, url to handle login, user name parameters, password parameters, what to do without authentication, and what to do if authentication succeeds:

@ Overrideprotected void configure (HttpSecurity http) throws Exception {http.formLogin () .loginPage ("/ login") / / login page .loginProcessingUrl ("/ do-login") / / process login logic .passwordParameter ("username") / / username parameter .p asswordParameter ("password") / / password parameter / / one of the three configurations is fine. .defaultSuccessUrl ("/ loginsucess"). SuccessForwardUrl ("/ sucess") .failureForwardUrl ("/ fail"). FailureUrl ("/ failure") .failureHandler (loginAuthenticationFailureHandler) .permitAll () }

DefaultSuccessUrl and successForwardUrl, preferably using defaultSuccessUrl, can redirect the url,defaultSuccessUrl before the login page also receives a boolean parameter, which, if set to true, is equivalent to successForwardUrl.

If you want to understand exactly how login and UsernamePasswordAuthenticationFilter relate, you have to look at http.formLogin ():

Public FormLoginConfigurer formLogin () throws Exception {return getOrApply (new FormLoginConfigurer ();}

By looking at the name of FormLoginConfigurer, we know that it is a Configurer configuration class, which has been introduced in the previous article. You can take a look at it or simply take a look at the following important SecurityBuilder tips:

If you are interested, you can take a look at this class for yourself, so we won't expand it in detail here.

Redirect infinite loop problem

If there is an infinite loop problem as shown in the figure above, there is probably a configuration similar to the following:

@ Overridepublic void configure (WebSecurity web) {web.ignoring () .antMatchers ("/ login");} @ Overrideprotected void configure (HttpSecurity http) throws Exception {http.authorizeRequests () .antMatchers ("/ index.html") .permitAll () .anyRequest () .authenticated (); http.formLogin ();}

Knowing the previous login process, it is much easier to understand this infinite loop, because login does not need to be authenticated, but login needs to be authorized, so ExceptionTranslationFilter is directed to the default login page login, and then enters infinite nesting doll mode.

About authorization @ Overrideprotected void configure (HttpSecurity http) throws Exception {http.authorizeRequests () .antMatchers ("/ index.html") .permitAll () .anyRequest () .authenticated (); http.formLogin ();}

For authorization, you can see the http.authorizeRequests () method:

Public ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry authorizeRequests () throws Exception {ApplicationContext context = getContext (); return getOrApply (new ExpressionUrlAuthorizationConfigurer (context)) .getRegistry ();} across the problem import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;import org.springframework.web.filter.CorsFilter;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer @ Configurationpublic class CorsConfig implements WebMvcConfigurer {private CorsConfiguration buildConfig () {CorsConfiguration corsConfiguration = new CorsConfiguration (); corsConfiguration.addAllowedOrigin ("*"); corsConfiguration.addAllowedHeader ("*"); corsConfiguration.addAllowedMethod ("*"); corsConfiguration.addExposedHeader ("Authorization"); return corsConfiguration } @ Bean public CorsFilter corsFilter () {UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource (); source.registerCorsConfiguration ("/ * *", buildConfig ()); return new CorsFilter (source) } @ Override public void addCorsMappings (CorsRegistry registry) {registry.addMapping ("/ * *") .allowedOrigins ("*") / / .allowCredentials (true) .allowedMethods ("GET", "POST", "DELETE" "PUT") .maxAge (3600) }}

In addition to the above configuration, you also need to:

Protected void configure (HttpSecurity http) throws Exception {http.cors ();}

Testing by yourself often disables csrf, otherwise, use post, but the request for parameters in url will be intercepted.

Protected void configure (HttpSecurity http) throws Exception {http.cors () .and () .csrf () .disable ();} important SecurityBuilder prompt WebSecurity

WebSecurity is a SecurityBuilder, so one of its main responsibilities is to create Filter, focusing on its build method, which inherits AbstractSecurityBuilder's build, and the specific logic is in AbstractConfiguredSecurityBuilder's doBuild method.

Overrideprotected final O doBuild () throws Exception {synchronized (this.configurers) {this.buildState = BuildState.INITIALIZING; beforeInit (); init (); this.buildState = BuildState.CONFIGURING; beforeConfigure (); configure (); this.buildState = BuildState.BUILDING; O result = performBuild (); this.buildState = BuildState.BUILT; return result;}}

A very standard template method pattern.

The logic that actually performs the build is in the performBuild method, which creates the FilterChainProxy in WebSecurity and the DefaultSecurityFilterChain in HttpSecurity.

HttpSecurity

As analyzed earlier, the purpose of HttpSecurity is to create a DefaultSecurityFilterChain, and pay attention to its performBuild method.

This is the end of the content of "what are the common SpringSecurity problems"? thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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