这篇文章主要介绍了mall大型企业项目:4,权限验证加redis缓存(上)。security+jwt+redis的讲解,通过具体代码实例进行16454 讲解,并且分析了mall大型企业项目:4,权限验证加redis缓存(上)。security+jwt+redis的详细步骤与相关技巧,需要的朋友可以参考下https://www.b2bchain.cn/?p=16454
本文实例讲述了2、树莓派设置连接WiFi,开启VNC等等的讲解。分享给大家供大家参考文章查询地址https://www.b2bchain.cn/7039.html。具体如下:
security+jwt+redis
- 代码部分
-
- 1,pom.xml新增部分
- 2,完整版pom.xml
- 3,application.yml新增部分
- 4,application.yml完整版
- 5,dao
- 6,dao.xml
- 7,mapper
- 8,mapper.xml
- 9,model
- 10,exception
SpringSecurity
SpringSecurity是一个强大的可高度定制的认证和授权框架,对于Spring应用来说它是一套Web安全标准。SpringSecurity注重于为Java应用提供认证和授权功能,像所有的Spring项目一样,它对自定义需求具有强大的扩展性。
JWT
JWT是JSON WEB TOKEN的缩写,它是基于 RFC 7519 标准定义的一种可以安全传输的的JSON对象,由于使用了数字签名,所以是可信任和安全的。
JWT的组成
{"alg": "HS512"}
{"sub":"admin","created":1489079981393,"exp":1489684781}
//secret为加密算法的** String signature = HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
***生成的token可以直接去这个网站,将token复制在左边点执行按钮
token查看jwt官网
jwt实现认证和搜权的原理
用户调用登录接口,登录成功后获取到JWT的token;
之后用户每次调用接口都在http的header中添加一个叫Authorization的头,值为JWT的token;
后台程序通过对Authorization头中信息的解码及数字签名校验来获取其中的用户信息,从而实现认证和授权。
并且做了升级。在调登录接口时候会返回一个tokenHeader。将tokenHeader的值加空格与Authorization拼接才算一个完整的鉴权
##涉及的数据表
ums_admin:后台用户表
ums_role:后台用户角色表
ums_permission:后台用户权限表
ums_admin_role_relation:后台用户和角色关系表,用户与角色是多对多关系
ums_role_permission_relation:后台用户角色和权限关系表,角色与权限是多对多关系
ums_admin_permission_relation:后台用户和权限关系表(除角色中定义的权限以外的加减权限),加权限是指用户比角色多出的权限,减权限是指用户比角色少的权限
代码部分
1,pom.xml新增部分
<!--SpringSecurity依赖配置--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!--Hutool Java工具包--> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>4.5.7</version> </dependency> <!--JWT(Json Web Token)登录支持--> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.0</version> </dependency> <!--javax.validation.constraints--> <dependency> <groupId>jakarta.validation</groupId> <artifactId>jakarta.validation-api</artifactId> <version>2.0.2</version> </dependency> <!--redis--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>2.3.0.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.3.0</version> </dependency> <!-- redis依赖commons-pool 这个依赖一定要添加 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <!--引入原common模块的--> <dependency> <groupId>net.logstash.logback</groupId> <artifactId>logstash-logback-encoder</artifactId> <version>5.3</version> </dependency>
2,完整版pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.mall</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mall2</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <swagger2.version>2.9.2</swagger2.version> <swagger-models.version>1.6.0</swagger-models.version> <swagger-annotations.version>1.6.0</swagger-annotations.version> </properties> <dependencies> <!--SpringBoot通用依赖模块--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--MyBatis分页插件--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.10</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.2.0</version> </dependency> <!--SpringData工具包--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-commons</artifactId> <version>2.3.0.RELEASE</version> </dependency> <!--集成druid连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <!-- MyBatis 生成器 --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.3</version> </dependency> <!--Mysql数据库驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.15</version> </dependency> <!--Swagger-UI API文档生产工具--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger2.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${swagger2.version}</version> </dependency> <!--解决Swagger 2.9.2版本NumberFormatException--> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> <version>${swagger-models.version}</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>${swagger-annotations.version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--SpringSecurity依赖配置--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!--Hutool Java工具包--> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>4.5.7</version> </dependency> <!--JWT(Json Web Token)登录支持--> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.0</version> </dependency> <!--javax.validation.constraints--> <dependency> <groupId>jakarta.validation</groupId> <artifactId>jakarta.validation-api</artifactId> <version>2.0.2</version> </dependency> <!--redis--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>2.3.0.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.3.0</version> </dependency> <!-- redis依赖commons-pool 这个依赖一定要添加 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <!--引入原common模块的--> <dependency> <groupId>net.logstash.logback</groupId> <artifactId>logstash-logback-encoder</artifactId> <version>5.3</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
3,application.yml新增部分
redis: database: 0 # redis服务器地址(默认为loaclhost) host: xxxx # redis端口(默认为6379) post: 6379 # redis连接超时时间(单位毫秒) timeout: 0 # redis连接池配置 pool: # 最大可用连接数(默认为8,负数表示无限) max-active: 8 # 最大空闲连接数(默认为8,负数表示无限) max-idle: 8 # 最小空闲连接数(默认为0,该值只有为正数才有用) min-idle: 0 # 从连接池中获取连接最大等待时间(默认为-1,单位为毫秒,负数表示无限) max-wait: -1 jwt: tokenHeader: Authorization #JWT存储的请求头 secret: mall-admin-secret #JWT加解密使用的** expiration: 604800 #JWT的超期限时间(60*60*24*7) tokenHead: 'Bearer ' #JWT负载中拿到开头 redis: database: mall key: admin: 'ums:admin' resourceList: 'ums:resourceList' expire: common: 86400 # 24小时 secure: ignored: urls: #安全路径白名单 - /swagger-ui.html - /swagger-resources/** - /swagger/** - /**/v2/api-docs - /**/*.js - /**/*.css - /**/*.png - /**/*.ico - /webjars/springfox-swagger-ui/** - /actuator/** - /druid/** - /admin/login - /admin/register - /admin/info - /admin/logout - /minio/upload
4,application.yml完整版
spring: datasource: url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: ljs druid: initial-size: 5 #���ӳس�ʼ����С min-idle: 10 #��С���������� max-active: 20 #��������� web-stat-filter: exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" #��ͳ����Щ�������� stat-view-servlet: #���ʼ����ҳ�ĵ�¼�û��������� login-username: druid login-password: druid redis: database: 0 # redis服务器地址(默认为loaclhost) host: 47.115.93.213 # redis端口(默认为6379) post: 6379 # redis连接超时时间(单位毫秒) timeout: 0 # redis连接池配置 pool: # 最大可用连接数(默认为8,负数表示无限) max-active: 8 # 最大空闲连接数(默认为8,负数表示无限) max-idle: 8 # 最小空闲连接数(默认为0,该值只有为正数才有用) min-idle: 0 # 从连接池中获取连接最大等待时间(默认为-1,单位为毫秒,负数表示无限) max-wait: -1 mybatis: mapper-locations: classpath:mapper/*Mapper.xml,classpath*:dao/*Dao.xml type-aliases-package: com.mall.plu.model logging: level: com.mall.plu.mapper: debug jwt: tokenHeader: Authorization #JWT存储的请求头 secret: mall-admin-secret #JWT加解密使用的** expiration: 604800 #JWT的超期限时间(60*60*24*7) tokenHead: 'Bearer ' #JWT负载中拿到开头 redis: database: mall key: admin: 'ums:admin' resourceList: 'ums:resourceList' expire: common: 86400 # 24小时 secure: ignored: urls: #安全路径白名单 - /swagger-ui.html - /swagger-resources/** - /swagger/** - /**/v2/api-docs - /**/*.js - /**/*.css - /**/*.png - /**/*.ico - /webjars/springfox-swagger-ui/** - /actuator/** - /druid/** - /admin/login - /admin/register - /admin/info - /admin/logout - /minio/upload
5,dao
package com.mall.plu.dao; import com.mall.plu.model.UmsAdminRoleRelation; import com.mall.plu.model.UmsResource; import com.mall.plu.model.UmsRole; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 自定义后台用户与角色管理Dao * Created by macro on 2018/10/8. */ public interface UmsAdminRoleRelationDao { /** * 批量插入用户角色关系 */ int insertList(@Param("list") List<UmsAdminRoleRelation> adminRoleRelationList); /** * 获取用于所有角色 */ List<UmsRole> getRoleList(@Param("adminId") Long adminId); /** * 获取用户所有可访问资源 */ List<UmsResource> getResourceList(@Param("adminId") Long adminId); /** * 获取资源相关用户ID列表 */ List<Long> getAdminIdList(@Param("resourceId") Long resourceId); }
6,dao.xml
<?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.mall.plu.dao.UmsAdminRoleRelationDao"> <!--批量新增回写主键支持--> <insert id="insertList"> INSERT INTO ums_admin_role_relation (admin_id, role_id) VALUES <foreach collection="list" separator="," item="item" index="index"> (#{item.adminId,jdbcType=BIGINT}, #{item.roleId,jdbcType=BIGINT}) </foreach> </insert> <select id="getRoleList" resultMap="com.mall.plu.mapper.UmsRoleMapper.BaseResultMap"> select r.* from ums_admin_role_relation ar left join ums_role r on ar.role_id = r.id where ar.admin_id = #{adminId} </select> <select id="getResourceList" resultType="com.mall.plu.model.UmsResource"> SELECT ur.id id, ur.create_time createTime, ur.`name` `name`, ur.url url, ur.description description, ur.category_id categoryId FROM ums_admin_role_relation ar LEFT JOIN ums_role r ON ar.role_id = r.id LEFT JOIN ums_role_resource_relation rrr ON r.id = rrr.role_id LEFT JOIN ums_resource ur ON ur.id = rrr.resource_id WHERE ar.admin_id = #{adminId} AND ur.id IS NOT NULL GROUP BY ur.id </select> <select id="getAdminIdList" resultType="java.lang.Long"> SELECT DISTINCT ar.admin_id FROM ums_role_resource_relation rr LEFT JOIN ums_admin_role_relation ar ON rr.role_id = ar.role_id WHERE rr.resource_id=#{resourceId} </select> </mapper>
7,mapper
package com.mall.plu.mapper; import java.util.List; import com.mall.plu.model.UmsAdminRoleRelation; import com.mall.plu.model.UmsAdminRoleRelationExample; import org.apache.ibatis.annotations.Param; public interface UmsAdminRoleRelationMapper { long countByExample(UmsAdminRoleRelationExample example); int deleteByExample(UmsAdminRoleRelationExample example); int deleteByPrimaryKey(Long id); int insert(UmsAdminRoleRelation record); int insertSelective(UmsAdminRoleRelation record); List<UmsAdminRoleRelation> selectByExample(UmsAdminRoleRelationExample example); UmsAdminRoleRelation selectByPrimaryKey(Long id); int updateByExampleSelective(@Param("record") UmsAdminRoleRelation record, @Param("example") UmsAdminRoleRelationExample example); int updateByExample(@Param("record") UmsAdminRoleRelation record, @Param("example") UmsAdminRoleRelationExample example); int updateByPrimaryKeySelective(UmsAdminRoleRelation record); int updateByPrimaryKey(UmsAdminRoleRelation record); }
8,mapper.xml
<?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.mall.plu.mapper.UmsAdminRoleRelationMapper"> <resultMap id="BaseResultMap" type="com.mall.plu.model.UmsAdminRoleRelation"> <id column="id" jdbcType="BIGINT" property="id" /> <result column="admin_id" jdbcType="BIGINT" property="adminId" /> <result column="role_id" jdbcType="BIGINT" property="roleId" /> </resultMap> <sql id="Example_Where_Clause"> <where> <foreach collection="oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <foreach collection="criteria.criteria" item="criterion"> <choose> <when test="criterion.noValue"> and ${criterion.condition} </when> <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Update_By_Example_Where_Clause"> <where> <foreach collection="example.oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <foreach collection="criteria.criteria" item="criterion"> <choose> <when test="criterion.noValue"> and ${criterion.condition} </when> <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Base_Column_List"> id, admin_id, role_id </sql> <select id="selectByExample" parameterType="com.mall.plu.model.UmsAdminRoleRelationExample" resultMap="BaseResultMap"> select <if test="distinct"> distinct </if> <include refid="Base_Column_List" /> from ums_admin_role_relation <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null"> order by ${orderByClause} </if> </select> <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from ums_admin_role_relation where id = #{id,jdbcType=BIGINT} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Long"> delete from ums_admin_role_relation where id = #{id,jdbcType=BIGINT} </delete> <delete id="deleteByExample" parameterType="com.mall.plu.model.UmsAdminRoleRelationExample"> delete from ums_admin_role_relation <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </delete> <insert id="insert" parameterType="com.mall.plu.model.UmsAdminRoleRelation"> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long"> SELECT LAST_INSERT_ID() </selectKey> insert into ums_admin_role_relation (admin_id, role_id) values (#{adminId,jdbcType=BIGINT}, #{roleId,jdbcType=BIGINT}) </insert> <insert id="insertSelective" parameterType="com.mall.plu.model.UmsAdminRoleRelation"> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long"> SELECT LAST_INSERT_ID() </selectKey> insert into ums_admin_role_relation <trim prefix="(" suffix=")" suffixOverrides=","> <if test="adminId != null"> admin_id, </if> <if test="roleId != null"> role_id, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="adminId != null"> #{adminId,jdbcType=BIGINT}, </if> <if test="roleId != null"> #{roleId,jdbcType=BIGINT}, </if> </trim> </insert> <select id="countByExample" parameterType="com.mall.plu.model.UmsAdminRoleRelationExample" resultType="java.lang.Long"> select count(*) from ums_admin_role_relation <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </select> <update id="updateByExampleSelective" parameterType="map"> update ums_admin_role_relation <set> <if test="record.id != null"> id = #{record.id,jdbcType=BIGINT}, </if> <if test="record.adminId != null"> admin_id = #{record.adminId,jdbcType=BIGINT}, </if> <if test="record.roleId != null"> role_id = #{record.roleId,jdbcType=BIGINT}, </if> </set> <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByExample" parameterType="map"> update ums_admin_role_relation set id = #{record.id,jdbcType=BIGINT}, admin_id = #{record.adminId,jdbcType=BIGINT}, role_id = #{record.roleId,jdbcType=BIGINT} <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByPrimaryKeySelective" parameterType="com.mall.plu.model.UmsAdminRoleRelation"> update ums_admin_role_relation <set> <if test="adminId != null"> admin_id = #{adminId,jdbcType=BIGINT}, </if> <if test="roleId != null"> role_id = #{roleId,jdbcType=BIGINT}, </if> </set> where id = #{id,jdbcType=BIGINT} </update> <update id="updateByPrimaryKey" parameterType="com.mall.plu.model.UmsAdminRoleRelation"> update ums_admin_role_relation set admin_id = #{adminId,jdbcType=BIGINT}, role_id = #{roleId,jdbcType=BIGINT} where id = #{id,jdbcType=BIGINT} </update> </mapper>
9,model
package com.mall.plu.model; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; /** * 用户登录参数 * Created by macro on 2018/4/26. */ @Getter @Setter public class UmsAdminParam { @NotEmpty @ApiModelProperty(value = "用户名", required = true) private String username; @NotEmpty @ApiModelProperty(value = "密码", required = true) private String password; @ApiModelProperty(value = "用户头像") private String icon; @Email @ApiModelProperty(value = "邮箱") private String email; @ApiModelProperty(value = "用户昵称") private String nickName; @ApiModelProperty(value = "备注") private String note; }
package com.mall.plu.model; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; import javax.validation.constraints.NotEmpty; /** * 修改用户名密码参数 * Created by macro on 2019/10/9. */ @Getter @Setter public class UpdateAdminPasswordParam { @NotEmpty @ApiModelProperty(value = "用户名", required = true) private String username; @NotEmpty @ApiModelProperty(value = "旧密码", required = true) private String oldPassword; @NotEmpty @ApiModelProperty(value = "新密码", required = true) private String newPassword; }
10,exception
package com.mall.plu.exception; import com.mall.plu.config.IErrorCode; /** * 自定义API异常 * Created by macro on 2020/2/27. */ public class ApiException extends RuntimeException { private IErrorCode errorCode; public ApiException(IErrorCode errorCode) { super(errorCode.getMessage()); this.errorCode = errorCode; } public ApiException(String message) { super(message); } public ApiException(Throwable cause) { super(cause); } public ApiException(String message, Throwable cause) { super(message, cause); } public IErrorCode getErrorCode() { return errorCode; } }
本文转自互联网,侵权联系删除mall大型企业项目:4,权限验证加redis缓存(上)。security+jwt+redis
最新评论