The popular technology stack combination used for permission management on the market today is
ssm shrio
SpringCloud SpringBoot SpringSecurity
This combination naturally has its own matching characteristics. Due to SpringBoot's automatic injection configuration principle, it is automatically injected when the project is created. Manage SpringSecurity's filter container (DelegatingFilterProxy), and this filter is the core of the entire SpringSercurity. Masters the entire permission authentication process of SpringSercurity, and SpringBoot helps you automatically inject it into . Using ssm
to integrate Security will consume a lot of configuration files and is not easy to develop. Security's microservice permission scheme can be perfectly integrated with Cloud, so Security is more powerful and more complete than Shrio.
Core: Class SecurityConfig extends WebSecurityConfigurerAdapter
After inheriting WebSecurityConfigurerAdapter, we focus on the configure method For related configurations in the entire security authentication process, of course, before configuring, we will briefly understand the process
After briefly looking at the entire authority authentication process, it is easy to conclude that the core of SpringSecurity is as follows Several configuration items
Interceptor
Filter
Handler (Handler, exception handler, login success handler)
Then let’s complete the authentication process through configuration first! ! ! !
Suppose we want to implement the following authentication function
We need to first determine whether the verification code is correct (verification code filter, implement pre-interception through addFilerbefore)
, and then determine whether the username and password are correct (use the built-in username and password filter , UsernamePasswordAuthenticationFilter)
Configure the exception handler (Handler) to write out the exception information through the IO stream
About password Verification process:
The password verification rules of UsernamePasswordAuthenticationFilter are verified based on the rules in UserDetailsService under AuthenticationManagerBuilder (Authentication Manager):
The core method:
1.public UserDetails *loadUserByUsername(String username)
Go to the database to query whether it exists through the username of the request parameter. If it exists, it will be encapsulated in UserDetails, and the verification process is to obtain the username and password in UserDetail through AuthenticationManagerBuilder To verify,
so that we can configure the yaml file to set the account password through
Set the account through the database combined with UserDetail Password
(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("用户名或密码不正确"); } // 注意匹配参数,前者是明文后者是暗纹 System.out.println("是否正确"+bCryptPasswordEncoder.matches("111111",sysUser.getPassword())); return new AccountUser(sysUser.getId(), sysUser.getUsername(), sysUser.getPassword(), getUserAuthority(sysUser.getId())); }
After passing this verification, the filter will be allowed, otherwise use custom Or the default processor handles
Core configuration file:
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() // 登录配置 .formLogin() .successHandler(loginSuccessHandler) .failureHandler(loginFailureHandler) .and() .logout() .logoutSuccessHandler(jwtLogoutSuccessHandler) // 禁用session .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 配置拦截规则 .and() .authorizeRequests() .antMatchers(URL_WHITELIST).permitAll() .anyRequest().authenticated() // 异常处理器 .and() .exceptionHandling() .authenticationEntryPoint(jwtAuthenticationEntryPoint) .accessDeniedHandler(jwtAccessDeniedHandler) // 配置自定义的过滤器 .and() .addFilter(jwtAuthenticationFilter()) .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class) ; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailService); } }
View through JwtfFilter Whether it is logged in status
Essentially, it is still writing a filter chain:
In Add a filter before the login request
Pay attention to the expiration time of the verification code stored in redis. If the expiration time exceeds, it will be intercepted by the verification code interceptor
You need to prepare an interface for generating verification codes and store them in Redis
You need to delete the verification code after using 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("验证码校验失败2"); throw new CaptchaException("验证码错误"); } System.out.println("验证码:"+redisUtil.hget(Const.CAPTCHA_KEY, key)); if (!code.equals(redisUtil.hget(Const.CAPTCHA_KEY, key))) { System.out.println("验证码校验失败3"); throw new CaptchaException("验证码错误"); } // 一次性使用 redisUtil.hdel(Const.CAPTCHA_KEY, key); }
The above is the detailed content of What is the SpringSecurity+Redis authentication process?. For more information, please follow other related articles on the PHP Chinese website!