栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot + SpringSecurity(一)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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()这个方法主要是通过内存里查询用户的信息。

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

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

在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
        

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

各个配置类的包路径

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;


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;



@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;


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;
    }
    
    
    public static String createJWT(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间
        return builder.compact();
    }

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

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

    
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
    
    
    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;


@Component
public class RedisCache
{
    @Autowired
    public RedisTemplate redisTemplate;

    
    public  void setCacheObject(final String key, final T value)
    {
        redisTemplate.opsForValue().set(key, value);
    }

    
    public  void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    
    public boolean expire(final String key, final long timeout)
    {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    
    public boolean expire(final String key, final long timeout, final TimeUnit unit)
    {
        return redisTemplate.expire(key, timeout, unit);
    }

    
    public  T getCacheObject(final String key)
    {
        ValueOperations operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    
    public boolean deleteObject(final String key)
    {
        return redisTemplate.delete(key);
    }

    
    public long deleteObject(final Collection collection)
    {
        return redisTemplate.delete(collection);
    }

    
    public  long setCacheList(final String key, final List dataList)
    {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    
    public  List getCacheList(final String key)
    {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

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

    
    public  Set getCacheSet(final String key)
    {
        return redisTemplate.opsForSet().members(key);
    }

    
    public  void setCacheMap(final String key, final Map dataMap)
    {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    
    public  Map getCacheMap(final String key)
    {
        return redisTemplate.opsForHash().entries(key);
    }

    
    public  void setCacheMapValue(final String key, final String hKey, final T value)
    {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    
    public  T getCacheMapValue(final String key, final String hKey)
    {
        HashOperations opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    
    public void delCacheMapValue(final String key, final String hkey)
    {
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, hkey);
    }

    
    public  List getMultiCacheMapValue(final String key, final Collection hKeys)
    {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    
    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;


public class WebUtils
{
    
    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的实现类

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;


@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;


@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

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;


@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;


@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;


@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.*;


@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;


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;


@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;


@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;


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

八、最后测试

一些踩过的坑

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

特别说明:

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

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号