Springboot + SpringSecurity(一)

        基于springboot的脚手架已经搭建完成的基础,即mybatis、数据库逆向工程构建好了的基础上,用Springbot+SpringSecurity来进行的用户登录认证与权限控制(认证与授权)。

目录

前言

一、 对SpringSecurity的理解

二、在项目中总体实现流程思路

具体实现

一、引入spring security依赖(pom)

二、准备工作(各种工具配置类)

1. FastJsonRedisSerializer

2. RedisConfig

3.JWT工具类

4.RedisCache

5.WebUtils

三、UserDetailsService的实现类

1.LoginUser重写UserDetail

2.UserDetailsServiceImpl重写UserDetailsService

四、密码加密存储SecurityConfig

五、逻辑代码的编写

1.配置类SecurityConfig

2.封装返回的用户信息UserVo

3.编写用户登录Controller层

4.编写用户登录接口Service层

5.编写Service实现类

六、登录校验过滤器

1.定义JwtAuthenticationTokenFilter过滤器,并把它放到spring容器中

2.将token校验过滤器配置到springsecurity的过滤器链中(springsecurity中的配置一般是在SecurityConfig中)

八、最后测试

一些踩过的坑


前言


一、 对SpringSecurity的理解

        SpringSecurity的原理就是一个过滤器链,只要你的项目整合的了SpringSecurity,就相当于它帮你做了一系列过滤的工作,但是在实际的开发中,我们想要过滤的东西是要根据项目的需求来的,每个项目的需求都不一样,所以需要在SpringSecurity的基础上进行改进。

        SpringSecurity的用户认证流程是通过UsernamePasswordAuthentication来做的,首先UsernamePasswordAuthentication将我们登录的信息封装成一个Authentication对象,->调用AuthenticationManager接口的authenticate()方法来进行认证,->进而再调用AbstractDetailsAuthenticationProvider接口中的DaoAuthenticationProvider()方法来进行认证,->最后调用UserDetailServer接口的loadUserByUsername()方法来进行验证,而loadUserByUsername()这个方法主要是通过内存里查询用户的信息。

        结合下面的流程图来看实现用户认证流程

Springboot + SpringSecurity(一)_第1张图片

二、在项目中总体实现流程思路

在SpringSecurity原有的基础上改写登录用户认证
1.自己写一个登录的流程
这个登录首先是要在SpringConfig的白名单里的,在登录的流程里我们做以下这些事情:
    ① 获取AuthenticationManager 进行用户认证
        a 将用户登录的用户名、密码 封装成一个authentication对象
        b authenticationManager来进行认证
    ② 判断认证结果
        a 如果认证不通过则抛出异常
        b 如果认证通过 利用userid生成jwt

2.自定义一个过滤器(JwtAuthenticationTokenFilter)将其放在UsernamePasswordAuthentication之前。
而我们自定义的过滤器要进行判断请求携没携带token:
    ① 如果没有携带token就放行,让后面SpringSecurity的拦截器做相应的操作(如果请求在SpringConfig的白名单里,就放行,反之则拦截。)
    ② 如果携带token,我们就解析token,并将信息存在SecurityContextHolder中。(SecurityContextHolder是贯穿整个SpringSecurity的过滤器链的,大家都可以取到里面的信息。)

具体实现


一、引入spring security依赖(pom)

		
        
            org.springframework.boot
            spring-boot-starter-security
        

		
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
        
            com.alibaba
            fastjson
            1.2.33
        
        
        
            io.jsonwebtoken
            jjwt
            0.9.0
        

		
		
        
            javax.xml.bind
            jaxb-api
            2.3.0
        
        
            com.sun.xml.bind
            jaxb-impl
            2.3.0
        
        
            com.sun.xml.bind
            jaxb-core
            2.3.0
        
        
            javax.activation
            activation
            1.1.1
        

二、准备工作(各种工具配置类)

各个配置类的包路径

Springboot + SpringSecurity(一)_第2张图片

1. FastJsonRedisSerializer

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import com.alibaba.fastjson.parser.ParserConfig;
import org.springframework.util.Assert;
import java.nio.charset.Charset;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName RedisConfig
 * @Description TODO
 * @Author Flechazo_lalala
 * @Date 2022-05-29 10:39
 * @Version 1.0
 **/
public class FastJsonRedisSerializer implements RedisSerializer
{

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Class clazz;

    static
    {
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }

    public FastJsonRedisSerializer(Class clazz)
    {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException
    {
        if (t == null)
        {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException
    {
        if (bytes == null || bytes.length <= 0)
        {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);

        return JSON.parseObject(str, clazz);
    }


    protected JavaType getJavaType(Class clazz)
    {
        return TypeFactory.defaultInstance().constructType(clazz);
    }
}

2. RedisConfig

import com.placename.general.common.util.FastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName RedisConfig
 * @Description TODO
 * @Author Flechazo_lalala
 * @Date 2022-05-29 10:43
 * @Version 1.0
 **/
@Configuration
public class RedisConfig {

    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory)
    {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }
}

3.JWT工具类

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName JwtUtil
 * @Description TODO
 * @Author Flechazo_lalala
 * @Date 2022-05-29 10:50
 * @Version 1.0
 **/
public class JwtUtil {

    //有效期为
    public static final Long JWT_TTL = 24*60 * 60 *1000L;// 60 * 60 *1000  一个小时
    //设置秘钥明文
    public static final String JWT_KEY = "sangeng";

    public static String getUUID(){
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        return token;
    }
    
    /**
     * 生成jtw
     * @param subject token中要存放的数据(json格式)
     * @return
     */
    public static String createJWT(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间
        return builder.compact();
    }

    /**
     * 生成jtw
     * @param subject token中要存放的数据(json格式)
     * @param ttlMillis token超时时间
     * @return
     */
    public static String createJWT(String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
        return builder.compact();
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttlMillis==null){
            ttlMillis=JwtUtil.JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)              //唯一的ID
                .setSubject(subject)   // 主题  可以是JSON数据
                .setIssuer("sg")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
                .setExpiration(expDate);
    }

    /**
     * 创建token
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createJWT(String id, String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
        return builder.compact();
    }

    public static void main(String[] args) throws Exception {
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJjYWM2ZDVhZi1mNjVlLTQ0MDAtYjcxMi0zYWEwOGIyOTIwYjQiLCJzdWIiOiJzZyIsImlzcyI6InNnIiwiaWF0IjoxNjM4MTA2NzEyLCJleHAiOjE2MzgxMTAzMTJ9.JVsSbkP94wuczb4QryQbAke3ysBDIL5ou8fWsbt_ebg";
        Claims claims = parseJWT(token);
        System.out.println(claims);
    }

    /**
     * 生成加密后的秘钥 secretKey
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
    
    /**
     * 解析
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }


}

4.RedisCache

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName RedisCache
 * @Description TODO
 * @Author Flechazo_lalala
 * @Date 2022-05-29 10:53
 * @Version 1.0
 **/
@Component
public class RedisCache
{
    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public  void setCacheObject(final String key, final T value)
    {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public  void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout)
    {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit)
    {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public  T getCacheObject(final String key)
    {
        ValueOperations operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key)
    {
        return redisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection)
    {
        return redisTemplate.delete(collection);
    }

    /**
     * 缓存List数据
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public  long setCacheList(final String key, final List dataList)
    {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public  List getCacheList(final String key)
    {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public  BoundSetOperations setCacheSet(final String key, final Set dataSet)
    {
        BoundSetOperations setOperation = redisTemplate.boundSetOps(key);
        Iterator it = dataSet.iterator();
        while (it.hasNext())
        {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public  Set getCacheSet(final String key)
    {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public  void setCacheMap(final String key, final Map dataMap)
    {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public  Map getCacheMap(final String key)
    {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @param value 值
     */
    public  void setCacheMapValue(final String key, final String hKey, final T value)
    {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public  T getCacheMapValue(final String key, final String hKey)
    {
        HashOperations opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 删除Hash中的数据
     * 
     * @param key
     * @param hkey
     */
    public void delCacheMapValue(final String key, final String hkey)
    {
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, hkey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public  List getMultiCacheMapValue(final String key, final Collection hKeys)
    {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection keys(final String pattern)
    {
        return redisTemplate.keys(pattern);
    }
}

5.WebUtils

import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName WebUtils
 * @Description TODO
 * @Author Flechazo_lalala
 * @Date 2022-05-29 10:57
 * @Version 1.0
 **/
public class WebUtils
{
    /**
     * 将字符串渲染到客户端
     * 
     * @param response 渲染对象
     * @param string 待渲染的字符串
     * @return null
     */
    public static void renderString(HttpServletResponse response, String string) {
        try
        {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }


    public static void setDownLoadHeader(String filename, ServletContext context, HttpServletResponse response) throws UnsupportedEncodingException {
        String mimeType = context.getMimeType(filename);//获取文件的mime类型
        response.setHeader("content-type",mimeType);
        String fname= URLEncoder.encode(filename,"UTF-8");
        response.setHeader("Content-disposition","attachment; filename="+fname);

//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setCharacterEncoding("utf-8");
    }
}

三、UserDetailsService的实现类

Springboot + SpringSecurity(一)_第3张图片

Springboot + SpringSecurity(一)_第4张图片

1.LoginUser重写UserDetail

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName LoginUser
 * @Description TODO
 * @Author Flechazo_lalala
 * @Date 2022-05-29 11:44
 * @Version 1.0
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginUser implements UserDetails {

    //  自己封装用户的信息
    private PogUser pogUser;

    // 获取权限信息
    @Override
    public Collection getAuthorities() {
        return null;
    }

    // 返回用户的密码
    @Override
    public String getPassword() {
        return pogUser.getPassword();
    }

    // 返回用户名
    @Override
    public String getUsername() {
        return pogUser.getPassword();
    }

    // 判断是否没有过期, 改为true
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    //改为true
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    //改为true
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    //改为true
    @Override
    public boolean isEnabled() {
        return true;
    }
}

2.UserDetailsServiceImpl重写UserDetailsService

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.placename.general.mapper.PogUserMapper;
import com.placename.general.model.domain.LoginUser;
import com.placename.general.model.domain.PogUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName UserDetailsServiceImpl
 * @Description TODO
 * @Author Flechazo_lalala
 * @Date 2022-05-29 11:20
 * @Version 1.0
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService{

    @Autowired
    private PogUserMapper pogUserMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 根据用户名查询用户信息
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PogUser::getUsername, username);
        PogUser pogUser = pogUserMapper.selectOne(queryWrapper);
        if(Objects.isNull(pogUser)){
            throw new RuntimeException("用户不存在");
        }
//        PogUser pogUser = pogUserMapper.selectByUserNanme(username);
//        System.out.println(pogUser);
//        if(Objects.isNull(pogUser)){
//            throw new RuntimeException("用户不存在");
//        }

        //TODO 查询对应的权限信息


        return new LoginUser(pogUser);
    }
}

四、密码加密存储SecurityConfig

Springboot + SpringSecurity(一)_第5张图片

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName SecurityConfig
 * @Description TODO
 * @Author Flechazo_lalala
 * @Date 2022-05-29 14:13
 * @Version 1.0
 **/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

五、逻辑代码的编写

1.配置类SecurityConfig

// 在刚刚密码加密存储的SecurityConfig里添加新的信息

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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.crypto.password.PasswordEncoder;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName SecurityConfig
 * @Description TODO
 * @Author Flechazo_lalala
 * @Date 2022-05-29 14:13
 * @Version 1.0
 **/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/login").anonymous()
                // 除上面外的所有请求全部需要认证即可访问
                .anyRequest().authenticated();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


}

2.封装返回的用户信息UserVo

import com.placename.general.model.domain.PogUser;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName UserVo
 * @Description TODO
 * @Author Flechazo_lalala
 * @Date 2022-05-29 15:40
 * @Version 1.0
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserVo {
    private String token;
    private PogUser pogUser;
}

3.编写用户登录Controller层

import com.placename.general.common.JsonResponse;
import com.placename.general.model.domain.PogUser;
import com.placename.general.service.PogUserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName LoginController
 * @Description TODO
 * @Author Flechazo_lalala
 * @Date 2022-05-29 14:58
 * @Version 1.0
 **/
@RestController
@Api(tags = "用户管理")
@RequestMapping("/api/user")
public class LoginController {
    @Autowired
    private PogUserService pogUserService;

    @PostMapping("/login")
    public JsonResponse login(@RequestBody PogUser pogUser){
        return JsonResponse.success(pogUserService.login(pogUser));
    }
}

4.编写用户登录接口Service层

import com.placename.general.model.domain.PogUser;
import com.baomidou.mybatisplus.extension.service.IService;
import com.placename.general.model.vo.UserVo;

/**
 * 

* 服务类 *

* * @author Flechazo_lalala * @since 2022-05-27 */ public interface PogUserService extends IService { UserVo login(PogUser pogUser); }

5.编写Service实现类

import com.placename.general.common.util.JwtUtil;
import com.placename.general.model.domain.LoginUser;
import com.placename.general.model.domain.PogUser;
import com.placename.general.mapper.PogUserMapper;
import com.placename.general.model.vo.UserVo;
import com.placename.general.service.PogUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 

* 服务实现类 *

* * @author Flechazo_lalala * @since 2022-05-27 */ @Service public class PogUserServiceImpl extends ServiceImpl implements PogUserService { @Autowired private PogUserMapper pogUserMapper; @Autowired private PasswordEncoder passwordEncoder; @Autowired private AuthenticationManager authenticationManager; @Autowired private RedisCache redisCache; @Override public UserVo login(PogUser pogUser) { // 获取AuthenticationManager 进行用户认证 // 1.将用户登录的用户名、密码 封装成一个authentication对象 UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(pogUser.getUsername(), pogUser.getPassword()); // 2.authenticationManager来进行认证, Authentication authentication = authenticationManager.authenticate(authenticationToken); // 判断认证结果 // 1.如果认证不通过则抛出异常; if(Objects.isNull(authentication)){ throw new RuntimeException("登录失败"); } // 2.如果认证通过 利用userid生成应该jwt LoginUser loginUser = (LoginUser) authentication.getPrincipal(); String userid = loginUser.getPogUser().getId().toString(); String jwt = JwtUtil.createJWT(userid); // 把完整的用户信息存入redis中 redisCache.setCacheObject("bloglogin:"+userId,loginUser); UserVo userVo = new UserVo(jwt, pogUser); return userVo; } }

六、登录校验过滤器

1.定义JwtAuthenticationTokenFilter过滤器,并把它放到spring容器中

import com.alibaba.fastjson.JSON;
import com.placename.general.common.util.JwtUtil;
import com.placename.general.common.util.RedisCache;
import com.placename.general.common.util.WebUtils;
import com.placename.general.model.domain.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName JwtAuthenticationTokenFilter
 * @Description TODO
 * @Author Flechazo_lalala
 * @Date 2022-05-30 9:02
 * @Version 1.0
 **/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 获取token
        String token = request.getHeader("token");

        // 1.如果没有获取到token,直接放行,后面会有拦截器拦截它的, 即表明用户未登录过
        if(!StringUtils.hasText(token)){
            filterChain.doFilter(request, response);
            return;
        }

        // 2. 如果获取到token后才进行以下操作,即表明已经登录过了
        // 2.1 解析token
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //token超时  token非法
            //响应告诉前端需要重新登录
            throw new RuntimeException("token非法");
        }

        // 2.2根据token解析的用户id去redis中获取用户信息 TODO
        String userId = claims.getSubject();
        LoginUser loginUser = redisCache.getCacheObject("bloglogin:" + userId);

        // 2.2.1 如果获取不到,说明登录过期  提示重新登录
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户登录过期");
        }

        //2.2.2 存入SecurityContextHolder
        // TODO 获取权限信息封装到 authenticationToken
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // token存在且解析完了,则放行
        filterChain.doFilter(request, response);
    }

}

2.将token校验过滤器配置到springsecurity的过滤器链中(springsecurity中的配置一般是在SecurityConfig中)

import com.placename.general.common.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName SecurityConfig
 * @Description TODO
 * @Author Flechazo_lalala
 * @Date 2022-05-29 14:13
 * @Version 1.0
 **/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/login").anonymous()

                // 除上面外的所有请求全部需要认证即可访问
                .anyRequest().authenticated();


        //把jwtAuthenticationTokenFilter添加到SpringSecurity的过滤器链中
        // 将jwtAuthenticationTokenFilter放在UsernamePasswordAuthenticationFilter之前
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

八、最后测试

Springboot + SpringSecurity(一)_第6张图片

Springboot + SpringSecurity(一)_第7张图片

一些踩过的坑

        一开始我想着为了测试方便,就在拦截器的白名单上加上了 /**, 然后后面我发请求的时候我又带上了token,然后就一直被拦截,我当时想我不是所以路径都不拦截了吗,还一直拦截我, 然后我就把token去掉,欸,不拦截了。 原来是要不在白名单里的路径才要带上token,在白名单里带上token就一直被拦截,当时真的不知道为什么,后面才发现是JwtAuthenticationTokenFilter里面判断的问题,我在原有的基础上加上了token内容判空。

Springboot + SpringSecurity(一)_第8张图片

        还有一个在SecurityConfig里.antMatchers的anoymous()方法和permitAll()的区别

1.  anonymous() :匿名访问,仅允许匿名用户访问,如果登录认证后,带有token信息再去请求,这个anonymous()关联的资源就不能被访问(就相当于登陆之后不允许访问,只允许匿名的用户)

2.  permitAll() 登录能访问,不登录也能访问,一般用于静态资源js等

特别说明:

        本篇文章是跟着哔哩哔哩的up主三更草堂的视频来做的,个人觉得他讲得很通俗易懂,逻辑也很清晰,通过他的视频我才大概了解SpringSecurity整个的工作流程,并能够将SpringSecurity整合到自己的项目中,感恩。

你可能感兴趣的:(spring,boot,java,后端)