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 is the SpringSecurity+Redis certification process?

2025-01-14 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 SpringSecurity+Redis certification process". Interested friends may wish to take a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how the SpringSecurity+Redis certification process is.

Introduction of preface

The popular combination of technology stacks for rights management on the market today is

Ssm+shrio

SpringCloud+SpringBoot+SpringSecurity

This collocation naturally has its own characteristics, due to the automatic injection configuration principle of SpringBoot, the filter container (DelegatingFilterProxy) for managing SpringSecurity is automatically injected when the project is created, and this filter is the core of the entire SpringSercurity. Master the whole authorization process of SpringSercurity, and SpringBoot helps you to inject it automatically, and use ssm

To integrate Security will consume a lot of configuration files and is not easy to develop, and Security's micro-service permission scheme can be perfectly integrated with Cloud, so Security is more powerful and more functional than Shrio.

Core configuration file for Security

Core: Class SecurityConfig extends WebSecurityConfigurerAdapter

After inheriting WebSecurityConfigurerAdapter, we focus on the configure method to configure the entire security authentication process. Of course, let's take a brief look at the process before configuring.

After simply looking at the whole process of permission authentication, it is easy to conclude that the core of SpringSecurity is the following configuration items.

Interceptor (Interceptor)

Filter (Filter)

Processor (Handler, exception handler, login success handler)

Then let's first complete the authentication process through configuration!

Authentication process of Security

Suppose we are going to implement the authentication function

1. Is a login request

We need to determine whether the CAPTCHA is correct first (CAPTCHA filter, pre-intercept through addFilerbefore)

Then determine whether the username password is correct (use the built-in username password filter, UsernamePasswordAuthenticationFilter)

Configure the exception handler (Handler) to write the exception information through the IO stream

About the process of password verification:

The password verification rules of UsernamePasswordAuthenticationFilter are verified based on the rules in UserDetailsService under AuthenticationManagerBuilder (Authentication Manager):

The core method is:

1.public UserDetails * loadUserByUsername (String username)

Query whether it exists in the database by requesting the user name of the parameter, which is encapsulated in UserDetails, and the verification process is verified by obtaining the username and password in UserDetail through AuthenticationManagerBuilder.

So that we can pass through

Configure yaml file to set account password

Set the account password through database and UserDetail

(method in UserDetailsService, note that UserDetailsService needs to be injected into AuthenticationManagerBuilder)

@ Override public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException {SysUser sysUser = sysUserService.getByUsername (username); if (sysUser = = null) {throw new UsernameNotFoundException ("incorrect username or password") } / / pay attention to the matching parameters, the former is plaintext and the latter is dark stripe System.out.println ("correct" + bCryptPasswordEncoder.matches ("111111", sysUser.getPassword ()); return new AccountUser (sysUser.getId (), sysUser.getUsername (), sysUser.getPassword (), getUserAuthority (sysUser.getId ();}

After passing this verification, the filter is released and processed with a custom or default processor.

Core profile:

Package com.markerhub.config;import com.markerhub.security.*;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity Import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity (prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter {@ Autowired LoginFailureHandler loginFailureHandler; @ Autowired LoginSuccessHandler loginSuccessHandler; @ Autowired CaptchaFilter captchaFilter; @ Autowired JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint @ Autowired JwtAccessDeniedHandler jwtAccessDeniedHandler; @ Autowired UserDetailServiceImpl userDetailService; @ Autowired JwtLogoutSuccessHandler jwtLogoutSuccessHandler; @ Bean JwtAuthenticationFilter jwtAuthenticationFilter () throws Exception {JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter (authenticationManager ()); return jwtAuthenticationFilter;} @ Bean BCryptPasswordEncoder bCryptPasswordEncoder () {return new BCryptPasswordEncoder () } private static final String [] URL_WHITELIST = {"/ login", "/ logout", "/ captcha", "/ favicon.ico",} Protected void configure (HttpSecurity http) throws Exception {http.cors () .and () .csrf () .disable () / login configuration .formLogin () .roomHandler (loginSuccessHandler). FailureHandler (loginFailureHandler) .and () .logout () .logoutSuccessHandler (jwtLogoutSuccessHandler) / / disable session .and () .sessionManagement () .sessionCreationPolicy (SessionCreationPolicy.STATELESS) / / configure the interception rule .and () .authorizeRequests () .antMatching (URL_WHITELIST) .permitAll () .anyRequest () .authenticated () / exception handler .and () .authenticationEntryPoint (jwtAuthenticationEntryPoint) .accessDeniedHandler (jwtAccessDeniedHandler) / / configure a custom filter .and () .addFilter (jwtAuthenticationFilter ()) .addFilterBefore (captchaFilter UsernamePasswordAuthenticationFilter.class) } @ Override protected void configure (AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService (userDetailService);} 2. Not a login request

Check whether it is a login status through JwtfFilter

Considerations when using Redis consolidation

Essentially write a filter chain:

Add a filter before a login request

Note that the expiration time of the CAPTCHA stored in redis will be intercepted by the CAPTCHA interceptor if the expiration time is exceeded.

You need to prepare an interface to generate CAPTCHA, which is stored in Redis.

After using the verification code, you need to delete it.

/ / private void validate (HttpServletRequest httpServletRequest) {String code = httpServletRequest.getParameter ("code"); String key = httpServletRequest.getParameter ("token"); if (StringUtils.isBlank (code) | | StringUtils.isBlank (key)) {System.out.println ("CAPTCHA failed 2") Throw new CaptchaException ("CAPTCHA error");} System.out.println ("CAPTCHA:" + redisUtil.hget (Const.CAPTCHA_KEY, key)); if (! code.equals (redisUtil.hget (Const.CAPTCHA_KEY, key) {System.out.println ("CAPTCHA failed 3") Throw new CaptchaException ("CAPTCHA error");} / / disposable redisUtil.hdel (Const.CAPTCHA_KEY, key);} at this point, I believe you have a deeper understanding of "what the SpringSecurity+Redis authentication process is like". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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