• SpringBoot集成SpringSecurity从0到1搭建权限管理详细过程(认证+授权)


    前言

    最近工作需要给一个老系统搭建一套权限管理,选用的安全框架是SpringSecurity,基本上是结合业务从0到1搭建了一套权限管理,然后想着可以将一些核心逻辑抽取出来写一个权限通用Demo,特此记录下。


    1、SpringSecurity简介

    Spring Security是 Spring家族中的一个安全管理框架。相比与另外一个安全框架Shiro,它提供了更丰富的功能,社区资源也比Shiro丰富。

    一般来说中大型的项目都是使用Springsecurity 来做安全框架。小项目有Shiro的比较多,因为相比与SpringSecurity,Shiro的上手更加的简单。

    一般Web应用的需要进行认证和授权。

    认证: 验证当前访问系统的是不是本系统的用户,并且要确认具体是哪个用户

    授权: 经过认证后判断当前用户是否有权限进行某个操作

    而认证和授权也是SpringSecurity作为安全框架的核心功能。

    2、开始搭建

    2.1、准备工作

    1、先创建一个简单的SpringBoot工程
    2、创建一个测试请求

    @RestController
    public class HelloController {
    	@GetMapping("/hello")
    	public String hello(){
    	    return "Hello";
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3、运行项目,访问测试: localhost:8080/hello
    在这里插入图片描述

    2.2、引入SpringSecurity

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4

    2、重启项目访问测试接口:
    会发现需要登录才能访问了

    在这里插入图片描述

    账号默认是 user ,密码在控制台
    在这里插入图片描述
    登录成功后就能正常访问接口了

    补充:
    spring-security自带退出登录界面:http://127.0.0.1:8080/logout
    退出登录后再次访问接口需要重新登录才能访问了

    3、认证

    3.1、登录校验流程

    在这里插入图片描述

    3.2、准备工作

    1、添加依赖

    <!--redis依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!--fastjson依赖-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.33</version>
    </dependency>
    <!--jwt依赖-->
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.0</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    2、添加redis配置

    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;
     
    /**
     * Redis使用FastJson序列化
     *  防止存入数据到redis的时候乱码
     * 
     * @author sg
     */
    public class FastJsonRedisSerializer<T> implements RedisSerializer<T>
    {
     
        public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
     
        private Class<T> clazz;
     
        static
        {
            ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
        }
     
        public FastJsonRedisSerializer(Class<T> 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);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64

    3、响应类

    import com.fasterxml.jackson.annotation.JsonInclude;
     
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public class ResponseResult<T> {
        /**
         * 状态码
         */
        private Integer code;
        /**
         * 提示信息,如果有错误时,前端可以获取该字段进行提示
         */
        private String msg;
        /**
         * 查询到的结果数据,
         */
        private T data;
     
        public ResponseResult(Integer code, String msg) {
            this.code = code;
            this.msg = msg;
        }
     
        public ResponseResult(Integer code, T data) {
            this.code = code;
            this.data = data;
        }
     
        public Integer getCode() {
            return code;
        }
     
        public void setCode(Integer code) {
            this.code = code;
        }
     
        public String getMsg() {
            return msg;
        }
     
        public void setMsg(String msg) {
            this.msg = msg;
        }
     
        public T getData() {
            return data;
        }
     
        public void setData(T data) {
            this.data = data;
        }
     
        public ResponseResult(Integer code, String msg, T data) {
            this.code = code;
            this.msg = msg;
            this.data = data;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58

    4、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;
     
    /**
     * JWT工具类
     */
    public class JwtUtil {
     
        //有效期为
        public static final Long JWT_TTL = 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();
        }
     
     
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112

    6、Redis工具类

    import java.util.*;
    import java.util.concurrent.TimeUnit;
     
    /**
     * redis工具类
     */  
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    @Component
    public class RedisCache
    {
        @Autowired
        public RedisTemplate redisTemplate;
     
        /**
         * 缓存基本的对象,Integer、String、实体类等
         *
         * @param key 缓存的键值
         * @param value 缓存的值
         */
        public <T> void setCacheObject(final String key, final T value)
        {
            redisTemplate.opsForValue().set(key, value);
        }
     
        /**
         * 缓存基本的对象,Integer、String、实体类等
         *
         * @param key 缓存的键值
         * @param value 缓存的值
         * @param timeout 时间
         * @param timeUnit 时间颗粒度
         */
        public <T> 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> T getCacheObject(final String key)
        {
            ValueOperations<String, T> 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 <T> long setCacheList(final String key, final List<T> dataList)
        {
            Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
            return count == null ? 0 : count;
        }
     
        /**
         * 获得缓存的list对象
         *
         * @param key 缓存的键值
         * @return 缓存键值对应的数据
         */
        public <T> List<T> getCacheList(final String key)
        {
            return redisTemplate.opsForList().range(key, 0, -1);
        }
     
        /**
         * 缓存Set
         *
         * @param key 缓存键值
         * @param dataSet 缓存的数据
         * @return 缓存数据的对象
         */
        public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
        {
            BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
            Iterator<T> it = dataSet.iterator();
            while (it.hasNext())
            {
                setOperation.add(it.next());
            }
            return setOperation;
        }
     
        /**
         * 获得缓存的set
         *
         * @param key
         * @return
         */
        public <T> Set<T> getCacheSet(final String key)
        {
            return redisTemplate.opsForSet().members(key);
        }
     
        /**
         * 缓存Map
         *
         * @param key
         * @param dataMap
         */
        public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
        {
            if (dataMap != null) {
                redisTemplate.opsForHash().putAll(key, dataMap);
            }
        }
     
        /**
         * 获得缓存的Map
         *
         * @param key
         * @return
         */
        public <T> Map<String, T> getCacheMap(final String key)
        {
            return redisTemplate.opsForHash().entries(key);
        }
     
        /**
         * 往Hash中存入数据
         *
         * @param key Redis键
         * @param hKey Hash键
         * @param value 值
         */
        public <T> 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> T getCacheMapValue(final String key, final String hKey)
        {
            HashOperations<String, String, T> 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 <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
        {
            return redisTemplate.opsForHash().multiGet(key, hKeys);
        }
     
        /**
         * 获得缓存的基本对象列表
         *
         * @param pattern 字符串前缀
         * @return 对象列表
         */
        public Collection<String> keys(final String pattern)
        {
            return redisTemplate.keys(pattern);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233

    7、实体类

    import java.io.Serializable;
    import java.util.Date;
     
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User implements Serializable {
        private static final long serialVersionUID = -40356785423868312L;
        
        /**
        * 主键
        */
        private Long id;
        /**
        * 用户名
        */
        private String userName;
        /**
        * 昵称
        */
        private String nickName;
        /**
        * 密码
        */
        private String password;
        /**
        * 账号状态(0正常 1停用)
        */
        private String status;
        /**
        * 邮箱
        */
        private String email;
        /**
        * 手机号
        */
        private String phonenumber;
        /**
        * 用户性别(0男,1女,2未知)
        */
        private String sex;
        /**
        * 头像
        */
        private String avatar;
        /**
        * 用户类型(0管理员,1普通用户)
        */
        private String userType;
        /**
        * 创建人的用户id
        */
        private Long createBy;
        /**
        * 创建时间
        */
        private Date createTime;
        /**
        * 更新人
        */
        private Long updateBy;
        /**
        * 更新时间
        */
        private Date updateTime;
        /**
        * 删除标志(0代表未删除,1代表已删除)
        */
        private Integer delFlag;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71

    3.3、实现

    ①数据库校验用户

    从之前的分析我们可以知道,我们可以自定义一个 UserDetailsService, 让 SpringSecurity 使用我们的 UserDetailsService。我们自己的 UserDetailsService 可以从数据库中查询用户名和密码。

    1、创建数据库

    CREATE DATABASE /*!32312 IF NOT EXISTS*/`spring_security` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
    
    USE `spring_security`;
    
    CREATE TABLE `sys_user` (
      `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
      `user_name` VARCHAR(64) NOT NULL DEFAULT 'NULL' COMMENT '用户名',
      `nick_name` VARCHAR(64) NOT NULL DEFAULT 'NULL' COMMENT '昵称',
      `password` VARCHAR(64) NOT NULL DEFAULT 'NULL' COMMENT '密码',
      `status` CHAR(1) DEFAULT '0' COMMENT '账号状态(0正常 1停用)',
      `email` VARCHAR(64) DEFAULT NULL COMMENT '邮箱',
      `phonenumber` VARCHAR(32) DEFAULT NULL COMMENT '手机号',
      `sex` CHAR(1) DEFAULT NULL COMMENT '用户性别(0男,1女,2未知)',
      `avatar` VARCHAR(128) DEFAULT NULL COMMENT '头像',
      `user_type` CHAR(1) NOT NULL DEFAULT '1' COMMENT '用户类型(0管理员,1普通用户)',
      `create_by` BIGINT(20) DEFAULT NULL COMMENT '创建人的用户id',
      `create_time` DATETIME DEFAULT NULL COMMENT '创建时间',
      `update_by` BIGINT(20) DEFAULT NULL COMMENT '更新人',
      `update_time` DATETIME DEFAULT NULL COMMENT '更新时间',
      `del_flag` INT(11) DEFAULT '0' COMMENT '删除标志(0代表未删除,1代表已删除)',
      PRIMARY KEY (`id`)
    ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='用户表'
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    2、引入 MybatisPuls 和 mysql 驱动的依赖

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.3</version>
    </dependency>
    <!--mysql8.0需要-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    3、配置数据库信息

    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/spring_security?characterEncoding=utf-8&serverTimezone=UTC
        username: root
        password: root
        driver-class-name: com.mysql.cj.jdbc.Driver
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    4、定义 Mapper 接口

    public interface UserMapper extends BaseMapper<User> {
    }
    
    • 1
    • 2

    5、修改 User 实体类

    类名上加@TableName(value = "sys_user") ,id字段上加 @TableId
    
    • 1

    6、配置 Mapper 扫描

    @SpringBootApplication
    @MapperScan("com.eric.springsecurity.mapper")
    public class SpringSecurityApplication {
        public static void main(String[] args) {
            SpringApplication.run(SpringSecurityApplication.class, args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    7、添加 junit 依赖测试

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4

    8、测试 MP 是否能正常使用

    @SpringBootTest
    public class MapperTest {
     
        @Autowired
        private UserMapper userMapper;
     
        @Test
        public void testUserMapper(){
            List<User> users = userMapper.selectList(null);
            System.out.println(users);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    核心代码实现

    1、创建一个类实现 UserDetailsService 接口,重写其中的方法。更加用户名从数据库中查询用户信息

    /**
     * @author Eric
     * @date 2023-01-27 16:09
     */
    @Service
    public class UserDetailsServiceImpl implements UserDetailsService {
    
        @Autowired
        private UserMapper userMapper;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            //根据用户名查询用户信息
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUserName,username);
            User user = userMapper.selectOne(wrapper);
            //如果查询不到数据就通过抛出异常来给出提示
            if(Objects.isNull(user)){
                throw new RuntimeException("用户名或密码错误");
            }
            //TODO 根据用户查询权限信息 添加到LoginUser中
    
            //封装成UserDetails对象返回
            return new LoginUser(user);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    2、因为 UserDetailsService 方法的返回值是 UserDetails 类型,所以需要定义一个类,实现该接口,把用户信息封装在其中。

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class LoginUser implements UserDetails {
     
        private User user;
     
     
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            return null;
        }
     
        @Override
        public String getPassword() {
            return user.getPassword();
        }
     
        @Override
        public String getUsername() {
            return user.getUserName();
        }
     
        @Override
        public boolean isAccountNonExpired() {
            return true;
        }
     
        @Override
        public boolean isAccountNonLocked() {
            return true;
        }
     
        @Override
        public boolean isCredentialsNonExpired() {
            return true;
        }
     
        @Override
        public boolean isEnabled() {
            return true;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    3、此时因为重写了 UserDetailsService ,所以我们可以直接重启项目测试,访问:localhost:8080/hello需要登录,填写数据库账号密码发现会报错,
    需要往用户表中写入用户数据,并且如果你想让用户的密码是明文存储,需要在密码前加 {noop}。例如
    在这里插入图片描述

    再次登录发现成功。
    在这里插入图片描述

    ②密码加密存储

    实际项目中我们不会把密码明文存储在数据库中。
    默认使用的 PasswordEncoder 要求数据库中的密码格式为:{id}password 。它会根据 id 去判断密码的加密方式。但是我们一般不会采用这种方式。所以就需要替换 PasswordEncoder。

    我们一般使用 SpringSecurity 为我们提供的 BCryptPasswordEncoder
    我们只需要使用把 BCryptPasswordEncoder 对象注入 Spring 容器中,SpringSecurity 就会使用该 PasswordEncoder 来进行密码校验。

    我们可以定义一个 SpringSecurity 的配置类,SpringSecurity 要求这个配置类要继承 WebSecurityConfigurerAdapter。

    1、配置 spring-security的密码加密方式(对于某些项目来说,使用的加密方式可能不是这种,到时就需要自定义了)

    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
     
     
        @Bean
        public PasswordEncoder passwordEncoder(){
            return new BCryptPasswordEncoder();
        }
     
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2、随机生成一个密码为:123 的密钥,放入到数据库中

    @Test
    void contextLoads() {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode("123");
        System.out.println(encode);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    123对应密钥为:$2a 10 10 10B1L45gLlANgOPn4z10oL5O.3IIUzTUXknqrzsyAoTyIsXg.nzTayu
    在这里插入图片描述
    3、重启项目再次测试:localhost:8080/hello
    发现只有正确的账号和密码才能登录成功,也就是:eric 123

    ③登录接口

    接下我们需要自定义登陆接口,然后让 SpringSecurity 对这个接口放行, 让用户访问这个接口的时候不用登录也能访问

    在接口中我们通过 AuthenticationManager 的 authenticate 方法来进行用户认证, 所以需要在 SecurityConfig 中配置把 AuthenticationManager 注入容器

    认证成功的话要生成一个 jwt,放入响应中返回。并且为了让用户下回请求时能通过 jwt 识别出具体的是哪个用户,我们需要把用户信息存入 redis,可以把用户 id 作为 key。

    1、创建登录接口

    @RestController
    public class HelloController {
    
        @Autowired
        private LoginServcie loginServcie;
    
        @PostMapping("/user/login")
        public ResponseResult login(@RequestBody User user){
            return loginServcie.login(user);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2、修改security配置类,重写两个方法

    /**
     * @author Eric
     * @date 2023-01-27 16:32
     */
    @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()
                    //前后端分析项目,采用jwt,不通过Session获取SecurityContext
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .authorizeRequests()
                    // 对于登录接口 允许匿名访问
                    .antMatchers("/user/login").anonymous()
                    // 除上面外的所有请求全部需要鉴权认证
                    .anyRequest().authenticated();
        }
    
        @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    3、创建login实现类

    @Service
    public class LoginServiceImpl implements LoginServcie {
    
        @Autowired
        private AuthenticationManager authenticationManager;
        @Autowired
        private RedisCache redisCache;
    
        @Override
        public ResponseResult login(User user) {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
            Authentication authenticate = authenticationManager.authenticate(authenticationToken);
            if(Objects.isNull(authenticate)){
                throw new RuntimeException("用户名或密码错误");
            }
            //使用userid生成token
            LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
            String userId = loginUser.getUser().getId().toString();
            String jwt = JwtUtil.createJWT(userId);
            //authenticate存入redis
            redisCache.setCacheObject("login:"+userId,loginUser);
            //把token响应给前端
            HashMap<String,String> map = new HashMap<>();
            map.put("token",jwt);
            return new ResponseResult(200,"登陆成功",map);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    ④认证过滤器

    我们需要自定义一个过滤器(在每一个请求之前执行),这个过滤器会去获取请求头中的 token,对 token 进行解析取出其中的 userid
    然后使用 userid 去 redis 中获取对应的 LoginUser 对象。
    然后封装 Authentication 对象存入 SecurityContextHolder

    @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");
            if (!StringUtils.hasText(token)) {
                //放行
                filterChain.doFilter(request, response);
                return;
            }
            //解析token
            String userid;
            try {
                Claims claims = JwtUtil.parseJWT(token);
                userid = claims.getSubject();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("token非法");
            }
            //从redis中获取用户信息
            String redisKey = "login:" + userid;
            LoginUser loginUser = redisCache.getCacheObject(redisKey);
            if(Objects.isNull(loginUser)){
                throw new RuntimeException("用户未登录");
            }
            //存入SecurityContextHolder
            //TODO 获取权限信息封装到Authentication中
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUser,null,null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //放行
            filterChain.doFilter(request, response);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    同时将该过滤器添加到security中(修改 SecurityConfig)

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    
    
    //将 jwtAuthenticationTokenFilter过滤器添加到 UsernamePasswordAuthenticationFilter之前执行
    http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述

    此时可以重启测试,先使用postman拿到token,再将该token放到任意一个请求中,请求成功~
    在这里插入图片描述

    ⑤退出登录

    我们只需要定义一个登陆接口,然后获取 SecurityContextHolder 中的认证信息,删除 redis 中对应的数据即可。
    1、创建注销接口

    @GetMapping("/user/logout")
    public ResponseResult logout(){
        return loginServcie.logout();
    }
    
    • 1
    • 2
    • 3
    • 4

    2、创建service接口

    ResponseResult logout();
    
    • 1

    3、创建接口实现类

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+userid);
        return new ResponseResult(200,"退出成功");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    4、访问注销接口,然后再使用之前的token访问接口,发现403,没有权限或未登录,测试成功~


    4、授权

    4.1、权限系统的作用

    例如一个学校图书馆的管理系统,如果是普通学生登录就能看到借书还书相关的功能,不可能让他看到并且去使用添加书籍信息,删除书籍信息等功能。但是如果是一个图书馆管理员的账号登录了,应该就能看到并使用添加书籍信息,删除书籍信息等功能。

    总结起来就是不同的用户可以使用不同的功能。这就是权限系统要去实现的效果

    我们不能只依赖前端去判断用户的权限来选择显示哪些菜单哪些按钮。因为如果只是这样,如果有人知道了对应功能的接口地址就可以不通过前端,直接去发送请求来实现相关功能操作。

    所以我们还需要在后台进行用户权限的判断,判断当前用户是否有相应的权限,必须具有所需权限才能进行相应的操作。

    4.2、授权基本流程

    在 SpringSecurity 中,会使用默认的 FilterSecurityInterceptor 来进行权限校验。在 FilterSecurityInterceptor 中会从 SecurityContextHolder 获取其中的 Authentication,然后获取其中的权限信息。当前用户是否拥有访问当前资源所需的权限。

    所以我们在项目中只需要把当前登录用户的权限信息也存入 Authentication。
    然后设置我们的资源所需要的权限即可。

    4.3、授权实现

    ①限制访问资源所需权限

    SpringSecurity 为我们提供了基于注解的权限控制方案,这也是我们项目中主要采用的方式。我们可以使用注解去指定访问对应的资源所需的权限。
    但是要使用它我们需要先开启相关配置(在security配置类中添加如下配置)

    @EnableGlobalMethodSecurity(prePostEnabled = true)
    
    • 1

    然后就可以使用对应的注解。@PreAuthorize

    @RestController
    public class HelloController {
     
        @RequestMapping("/hello")
        @PreAuthorize("hasAuthority('test')")
        public String hello(){
            return "hello";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    和下面的一起配置好同时测试

    ②封装权限信息

    我们前面在写 UserDetailsServiceImpl 的时候说过,在查询出用户后还要获取对应的权限信息,封装到 UserDetails 中返回。
    我们先直接把权限信息写死封装到 UserDetails 中进行测试。
    1、我们之前定义了 UserDetails 的实现类 LoginUser,想要让其能封装权限信息就要对其进行修改。

    import com.alibaba.fastjson.annotation.JSONField;
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.core.userdetails.UserDetails;
     
    import java.util.Collection;
    import java.util.List;
    import java.util.stream.Collectors;
     
     
    @Data
    @NoArgsConstructor
    public class LoginUser implements UserDetails {
     
        private User user;
            
        //存储权限信息
        private List<String> permissions;
        
        
        public LoginUser(User user,List<String> permissions) {
            this.user = user;
            this.permissions = permissions;
        }
     
     
        //存储SpringSecurity所需要的权限信息的集合
        @JSONField(serialize = false)
        private List<GrantedAuthority> authorities;
     
        @Override
        public  Collection<? extends GrantedAuthority> getAuthorities() {
            if(authorities!=null){
                return authorities;
            }
            //把permissions中字符串类型的权限信息转换成GrantedAuthority对象存入authorities中
            authorities = permissions.stream().
                    map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
            return authorities;
        }
     
        @Override
        public String getPassword() {
            return user.getPassword();
        }
     
        @Override
        public String getUsername() {
            return user.getUserName();
        }
     
        @Override
        public boolean isAccountNonExpired() {
            return true;
        }
     
        @Override
        public boolean isAccountNonLocked() {
            return true;
        }
     
        @Override
        public boolean isCredentialsNonExpired() {
            return true;
        }
     
        @Override
        public boolean isEnabled() {
            return true;
        }
    }
     
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77

    2、LoginUser 修改完后我们就可以在 UserDetailsServiceImpl 中去把权限信息封装到 LoginUser 中了。我们先写死权限进行测试,后面我们再从数据库中查询权限信息。

    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.eric.springsecurity.entity.LoginUser;
    import com.eric.springsecurity.entity.User;
    import com.eric.springsecurity.mapper.UserMapper;
    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.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Objects;
    
    /**
     * 重写 UserDetailsService中的方法
     * @author Eric
     * @date 2023-01-27 16:09
     */
    @Service
    public class UserDetailsServiceImpl implements UserDetailsService {
    
        @Autowired
        private UserMapper userMapper;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            //根据用户名查询用户信息
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUserName,username);
            User user = userMapper.selectOne(wrapper);
            //如果查询不到数据就通过抛出异常来给出提示
            if(Objects.isNull(user)){
                throw new RuntimeException("用户名或密码错误");
            }
            //TODO 根据用户查询权限信息 添加到LoginUser中,先暂时写死
            List<String> list = new ArrayList<>(Arrays.asList("test"));
    
            //封装成UserDetails对象返回
            return new LoginUser(user,list);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    3、将查询到的权限放到UsernamePasswordAuthenticationToken中

    package com.eric.springsecurity.filter;
    
    import com.eric.springsecurity.entity.LoginUser;
    import com.eric.springsecurity.utils.JwtUtil;
    import com.eric.springsecurity.utils.RedisCache;
    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;
    
    /**
     * 该过滤器所有接口之前执行,判断是否携带了token和token是否正确
     */
    @Component
    public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    
        @Autowired
        private RedisCache redisCache;
    
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException, IOException {
            //获取token
            String token = request.getHeader("token");
            if (!StringUtils.hasText(token)) {
                //放行
                filterChain.doFilter(request, response);
                return;
            }
            //解析token
            String userid;
            try {
                Claims claims = JwtUtil.parseJWT(token);
                userid = claims.getSubject();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("token非法");
            }
            //从redis中获取用户信息
            String redisKey = "login:" + userid;
            LoginUser loginUser = redisCache.getCacheObject(redisKey);
            if(Objects.isNull(loginUser)){
                throw new RuntimeException("用户未登录");
            }
            //存入SecurityContextHolder
            //TODO 获取权限信息封装到Authentication中
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //放行
            filterChain.doFilter(request, response);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63

    在这里插入图片描述

    4、此时我们可以测试,注意,测试需要重新登录,然后拿着新token访问hello接口
    发现访问成功
    在这里插入图片描述

    此时我们再次修改hello接口的权限字符串,

    @GetMapping("/hello")
    @PreAuthorize("hasAuthority('test333')")
    public String hello(){
        return "Hello";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    然后重启项目测试,发现无权限,说明测试成功~

    ③从数据库查询权限信息

    1、RBAC 权限模型

    RBAC 权限模型(Role-Based Access Control)即:基于角色的权限控制。这是目前最常被开发者使用也是相对易用、通用权限模型。
    在这里插入图片描述

    2、准备工作

    CREATE DATABASE /*!32312 IF NOT EXISTS*/`sg_security` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
     
    USE `sg_security`;
     
    /*Table structure for table `sys_menu` */
     
    DROP TABLE IF EXISTS `sys_menu`;
     
    CREATE TABLE `sys_menu` (
      `id` bigint(20) NOT NULL AUTO_INCREMENT,
      `menu_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '菜单名',
      `path` varchar(200) DEFAULT NULL COMMENT '路由地址',
      `component` varchar(255) DEFAULT NULL COMMENT '组件路径',
      `visible` char(1) DEFAULT '0' COMMENT '菜单状态(0显示 1隐藏)',
      `status` char(1) DEFAULT '0' COMMENT '菜单状态(0正常 1停用)',
      `perms` varchar(100) DEFAULT NULL COMMENT '权限标识',
      `icon` varchar(100) DEFAULT '#' COMMENT '菜单图标',
      `create_by` bigint(20) DEFAULT NULL,
      `create_time` datetime DEFAULT NULL,
      `update_by` bigint(20) DEFAULT NULL,
      `update_time` datetime DEFAULT NULL,
      `del_flag` int(11) DEFAULT '0' COMMENT '是否删除(0未删除 1已删除)',
      `remark` varchar(500) DEFAULT NULL COMMENT '备注',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COMMENT='菜单表';
     
    /*Table structure for table `sys_role` */
     
    DROP TABLE IF EXISTS `sys_role`;
     
    CREATE TABLE `sys_role` (
      `id` bigint(20) NOT NULL AUTO_INCREMENT,
      `name` varchar(128) DEFAULT NULL,
      `role_key` varchar(100) DEFAULT NULL COMMENT '角色权限字符串',
      `status` char(1) DEFAULT '0' COMMENT '角色状态(0正常 1停用)',
      `del_flag` int(1) DEFAULT '0' COMMENT 'del_flag',
      `create_by` bigint(200) DEFAULT NULL,
      `create_time` datetime DEFAULT NULL,
      `update_by` bigint(200) DEFAULT NULL,
      `update_time` datetime DEFAULT NULL,
      `remark` varchar(500) DEFAULT NULL COMMENT '备注',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='角色表';
     
    /*Table structure for table `sys_role_menu` */
     
    DROP TABLE IF EXISTS `sys_role_menu`;
     
    CREATE TABLE `sys_role_menu` (
      `role_id` bigint(200) NOT NULL AUTO_INCREMENT COMMENT '角色ID',
      `menu_id` bigint(200) NOT NULL DEFAULT '0' COMMENT '菜单id',
      PRIMARY KEY (`role_id`,`menu_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
     
    /*Table structure for table `sys_user` */
     
    DROP TABLE IF EXISTS `sys_user`;
     
    CREATE TABLE `sys_user` (
      `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
      `user_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '用户名',
      `nick_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '昵称',
      `password` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '密码',
      `status` char(1) DEFAULT '0' COMMENT '账号状态(0正常 1停用)',
      `email` varchar(64) DEFAULT NULL COMMENT '邮箱',
      `phonenumber` varchar(32) DEFAULT NULL COMMENT '手机号',
      `sex` char(1) DEFAULT NULL COMMENT '用户性别(0男,1女,2未知)',
      `avatar` varchar(128) DEFAULT NULL COMMENT '头像',
      `user_type` char(1) NOT NULL DEFAULT '1' COMMENT '用户类型(0管理员,1普通用户)',
      `create_by` bigint(20) DEFAULT NULL COMMENT '创建人的用户id',
      `create_time` datetime DEFAULT NULL COMMENT '创建时间',
      `update_by` bigint(20) DEFAULT NULL COMMENT '更新人',
      `update_time` datetime DEFAULT NULL COMMENT '更新时间',
      `del_flag` int(11) DEFAULT '0' COMMENT '删除标志(0代表未删除,1代表已删除)',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='用户表';
     
    /*Table structure for table `sys_user_role` */
     
    DROP TABLE IF EXISTS `sys_user_role`;
     
    CREATE TABLE `sys_user_role` (
      `user_id` bigint(200) NOT NULL AUTO_INCREMENT COMMENT '用户id',
      `role_id` bigint(200) NOT NULL DEFAULT '0' COMMENT '角色id',
      PRIMARY KEY (`user_id`,`role_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
     
    
    insert  into `sys_menu`(`id`,`menu_name`,`path`,`component`,`visible`,`status`,`perms`,`icon`,`create_by`,`create_time`,`update_by`,`update_time`,`del_flag`,`remark`) values 
    (1,'部门管理','dept','system/dept/index','0','0','system:dept:list','#',NULL,NULL,NULL,NULL,0,NULL),
    (2,'测试','test','system/test/test','0','0','system:test:list','#',NULL,NULL,NULL,NULL,0,NULL);
    
    
    insert  into `sys_role`(`id`,`name`,`role_key`,`status`,`del_flag`,`create_by`,`create_time`,`update_by`,`update_time`,`remark`) values 
    (3,'ceo','ceo','0',0,NULL,NULL,NULL,NULL,NULL),
    (4,'code','code','0',0,NULL,NULL,NULL,NULL,NULL);
    
    
    insert  into `sys_role_menu`(`role_id`,`menu_id`) values 
    (3,1),
    (3,2);
    
    insert  into `sys_user`(`id`,`user_name`,`nick_name`,`password`,`status`,`email`,`phonenumber`,`sex`,`avatar`,`user_type`,`create_by`,`create_time`,`update_by`,`update_time`,`del_flag`) values 
    (3,'Eric','Eric','123456','0','2548928007@qq.com','18779579999','0',NULL,'1',NULL,NULL,NULL,NULL,0);
    
    insert  into `sys_user_role`(`user_id`,`role_id`) values 
    (3,3);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107

    3、实体类

    package com.eric.springsecurity.entity;
    
    import com.baomidou.mybatisplus.annotation.TableId;
    import com.baomidou.mybatisplus.annotation.TableName;
    import com.fasterxml.jackson.annotation.JsonInclude;
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.io.Serializable;
    import java.util.Date;
    
    /**
     * 菜单表(Menu)实体类
     *
     * @author Eric
     * @date 2023-02-02 16:12
     */
    @TableName(value = "sys_menu")
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @JsonInclude(JsonInclude.Include.NON_NULL)//属性为NULL 不序列化
    public class Menu implements Serializable {
        private static final long serialVersionUID = -54979041104113736L;
    
        @TableId
        private Long id;
        /**
         * 菜单名
         */
        private String menuName;
        /**
         * 路由地址
         */
        private String path;
        /**
         * 组件路径
         */
        private String component;
        /**
         * 菜单状态(0显示 1隐藏)
         */
        private String visible;
        /**
         * 菜单状态(0正常 1停用)
         */
        private String status;
        /**
         * 权限标识
         */
        private String perms;
        /**
         * 菜单图标
         */
        private String icon;
    
        private Long createBy;
    
        private Date createTime;
    
        private Long updateBy;
    
        private Date updateTime;
        /**
         * 是否删除(0未删除 1已删除)
         */
        private Integer delFlag;
        /**
         * 备注
         */
        private String remark;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74

    3、代码实现

    我们只需要根据用户 id 去查询到其所对应的权限信息即可。
    所以我们可以先定义个 mapper,其中提供一个方法可以根据 userid 查询权限信息。

    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import com.sangeng.domain.Menu;
     
    import java.util.List;
     
     
    public interface MenuMapper extends BaseMapper<Menu> {
        List<String> selectPermsByUserId(Long id);
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    由于是自定义方法,所以需要创建对应的 mapper 文件,定义对应的 sql 语句

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    <mapper namespace="com.eric.springsecurity.mapper.MenuMapper">
        
        <select id="selectPermsByUserId" resultType="java.lang.String">
            SELECT
                DISTINCT m.`perms`
            FROM
                sys_user_role ur
                    LEFT JOIN `sys_role` r ON ur.`role_id` = r.`id`
                    LEFT JOIN `sys_role_menu` rm ON ur.`role_id` = rm.`role_id`
                    LEFT JOIN `sys_menu` m ON m.`id` = rm.`menu_id`
            WHERE
                user_id = #{userid}
              AND r.`status` = 0
              AND m.`status` = 0
        </select>
        
    </mapper>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    然后我们可以在 UserDetailsServiceImpl 中去调用该 mapper 的方法查询权限信息封装到 LoginUser 对象中即可。

    @Service
    public class UserDetailsServiceImpl implements UserDetailsService {
     
        @Autowired
        private UserMapper userMapper;
     
        @Autowired
        private MenuMapper menuMapper;
     
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUserName,username);
            User user = userMapper.selectOne(wrapper);
            if(Objects.isNull(user)){
                throw new RuntimeException("用户名或密码错误");
            }
            List<String> permissionKeyList =  menuMapper.selectPermsByUserId(user.getId());
    //        //测试写法
    //        List<String> list = new ArrayList<>(Arrays.asList("test"));
            return new LoginUser(user,permissionKeyList);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    到这里,从数据库查询权限实现接口授权的功能就完成了,这里简单总结几点

    • 权限本质上是一个个字符串,例如:system:dept:list 这就是一个系统部门列表接口权限
    • 完整的权限最少拥有五张表:用户表,角色表、用户角色表、菜单表(可以理解为权限表)、角色菜单表

    说一下整体实现步骤:用户先登录,登录成功返回token给前端,同时将token和该用户信息及该用户对应的权限字符串存入redis,然后在每个接口上加上对应权限标识,使用注解 @PreAuthorize("hasAuthority('system:dept:list')")

    • 再访问接口的时候,判断该用户所拥有的权限是否包含该接口,如果包含,则能正常访问

    总结

    到这里基本上就OK了,需要的小伙伴其实可以将这一套作为一个项目的基本授权系统,或者做一个独立的权限管理系统,然后根据不同的业务场景集成到自己的项目中,基本上都是万变不离其宗,因为核心的步骤就那么几步。

    在这里再总结几个小点:

    • 整体实现流程:用户先登录,登录成功返回token给前端,同时将token和该用户信息及该用户对应的权限字符串存入redis,然后在每个接口上加上对应权限标识,使用注解@PreAuthorize来实现,这样每次访问接口的时候,都会判断该用户所拥有的权限是否包含该接口,如果包含,则能正常访问
    • 其实权限本质就是一个个的字符串
    • 像RBAC权限模型(角色权限控制)是我们日常中最常用的一个通用权限模式,但对于某些大型项目中,权限会分的更细致,例如可能每个客服跟进的订单类型不一样,那么像这种使用角色权限控制就不太合适了,最好是使用用户权限控制,也就是不区分角色,而是直接按照用户来进行功能授权

    认证其实就是判断用户是否处于登录状态
    授权其实就是判断用户是否拥有访问接口的权限
    而权限本质就是一个一个的字符串

    补充:其实还有一些细节需要补充,但由于每个项目业务场景不一样,就没有写进去。就比如我集成老项目的过程中使用的加密方式是Apache提供的,这个时候就需要自定义加密解密了。再比如可能需要配置认证失败、认证成功处理器等(但一般来说配置一个全局异常即可)。

    希望对你有帮助~

  • 相关阅读:
    TCP/UDP/Socket 通俗讲解
    【Realtek sdk-3.4.14b】RTL8197FH-VG和RTL8812F自适应认证失败问题分析及修改
    Appium混合页面点击方法tap的使用
    【LIN总线测试】——LIN从节点物理层测试
    中小企业转型数字化采购,快速实现经营效益
    从ObjectPool到CAS指令
    计算机网络的基础知识
    搅拌机出口欧洲需要做什么检测认证?
    &((type *)0)->member的用法
    Nginx学习(在 Docker 中使用 Nginx)
  • 原文地址:https://blog.csdn.net/weixin_47316183/article/details/130451744