SpringSecurity+Redis认证过程小结

 更新时间:2022年01月05日 17:03:44   作者:ME_._ME  
这篇文章主要介绍了SpringSecurity+Redis认证过程小结,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

由于今天用Security进行权限管理的时候出现了一些Bug,特此发这篇博客来补习一下对SpringSecurity的理解

前言引入

当今市面上用于权限管理的流行的技术栈组合是

  • ssm+shrio
  • SpringCloud+SpringBoot+SpringSecurity

这种搭配自然有其搭配的特点,由于SpringBoot的自动注入配置原理,在创建项目时就自动注入管理SpringSecurity的过滤器容器(DelegatingFilterProxy),而这个过滤器是整个SpringSercurity的核心。掌握着SpringSercurity整个权限认证过程,而SpringBoot很香的帮你将其自动注入了,而用ssm
去整合Security,将会耗用大量的配置文件,不易于开发,而Security的微服务权限方案,更是能和Cloud完美融合,于是Security比Shrio更强大,功能更齐全。

Security的核心配置文件

核心:Class SecurityConfig extends WebSecurityConfigurerAdapter

继承了WebSecurityConfigurerAdapter后我们关注于configure方法对于在整个安全认证的过程进行相关的配置,当然在配置之前我们先简单了解一下流程

简单的看了整个权限认证的流程,很轻易的总结得出,SpringSecurity核心的就是以下几种配置项了

  • 拦截器(Interceptor)
  • 过滤器(Filter)
  • 处理器(Handler,异常处理器,登录成功处理器)

那我们就首先通过配置来完成认证过程吧!!!!

Security的认证过程

假设我们要实现一下的认证功能

1. 是登录请求

  • 我们需要先判断验证码是否正确(验证码过滤器,通过addFilerbefore实现前置拦截)
  • 再判断用户名密码是否正确(使用自带的用户名密码过滤器,UsernamePasswordAuthenticationFilter
  • 配置异常处理器(Handler)通过IO流将异常信息写出

关于密码校验的流程:
UsernamePasswordAuthenticationFilter的密码校验规则是基于AuthenticationManagerBuilder(认证管理器)下的 UserDetailsService里的规则进行验证的:
其中的核心方法:

1.public UserDetails *loadUserByUsername(String username)
通过请求参数的用户名去数据库查询是否存在,存在则将其封装在UserDetails里面,而验证过程是通过AuthenticationManagerBuilder获取到UserDetail里的username和password来校验的,
这样我们就可以通过

  • 配置yaml文件设置账号密码
  • 通过数据库结合UserDetail来设置账号密码

(UserDetailsService中的方法,注意需要将UserDetailsService注入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()));
	}

通过了这个验证后,过滤器放行,不通过就用自定义或者默认的处理器处理

核心配置文件:

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);
	}
}

2. 不是登录请求

  • 通过JwtfFilter来查看是否为登录状态

使用Redis整合时的注意事项

本质上还是编写过滤器链:

  • 在登录请求前添加过滤器
  • 注意验证码存储在redis的失效时间,如果超过失效时间将会被验证码拦截器拦截下来
  • 需要准备一个生成验证码的接口,存储在Redis中
  • 使用完验证码需要将其删除
// 校验验证码逻辑
	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);
	}

到此这篇关于SpringSecurity+Redis认证过程总结的文章就介绍到这了,更多相关SpringSecurity Redis认证内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Spring手动生成web.xml配置文件过程详解

    Spring手动生成web.xml配置文件过程详解

    这篇文章主要介绍了Spring手动生成web.xml配置文件过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07
  • Java synchornized与ReentrantLock处理并发出现的错误

    Java synchornized与ReentrantLock处理并发出现的错误

    synchronized机制提供了对每个对象相关的隐式监视器锁,并强制所有锁的获取和释放都必须在同一个块结构中。当获取了多个锁时,必须以相反的顺序释放。即synchronized对于锁的释放是隐式的
    2023-01-01
  • java使用compareTo实现一个类的对象之间比较大小操作

    java使用compareTo实现一个类的对象之间比较大小操作

    这篇文章主要介绍了java使用compareTo实现一个类的对象之间比较大小操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • Java深入数据结构理解掌握抽象类与接口

    Java深入数据结构理解掌握抽象类与接口

    在类中没有包含足够的信息来描绘一个具体的对象,这样的类称为抽象类,接口是Java中最重要的概念之一,它可以被理解为一种特殊的类,不同的是接口的成员没有执行体,是由全局常量和公共的抽象方法所组成,本文给大家介绍Java抽象类和接口,感兴趣的朋友一起看看吧
    2022-05-05
  • Java基础之反射

    Java基础之反射

    JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;反射是框架设计的灵魂,感兴趣的小伙伴可以参考阅读
    2023-03-03
  • java模仿实现QQ登录界面

    java模仿实现QQ登录界面

    这篇文章主要为大家详细介绍了java模仿实现qq登录界面,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-05-05
  • 浅谈java泛型的作用及其基本概念

    浅谈java泛型的作用及其基本概念

    下面小编就为大家带来一篇浅谈java泛型的作用及其基本概念。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-08-08
  • SpringBoot启动流程之引导上下文DefaultBootstrapContext的过程

    SpringBoot启动流程之引导上下文DefaultBootstrapContext的过程

    本文详细介绍了SpringBoot版本2.7.18中SpringApplication的run方法,引导注册组件初始化器BootstrapRegistryInitializer是SpringBoot的第一个扩展点,负责应用启动早期阶段的初始化和配置,感兴趣的朋友跟随小编一起看看吧
    2024-11-11
  • SpringBoot部署在Weblogic的操作步骤

    SpringBoot部署在Weblogic的操作步骤

    这篇文章主要介绍了SpringBoot部署在Weblogic的操作步骤,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • JDK1.7中HashMap的死循环问题及解决方案

    JDK1.7中HashMap的死循环问题及解决方案

    这篇文章主要为大家介绍了JDK1.7中HashMap的死循环问题及解决方案,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-10-10

最新评论