Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用

这篇具有很好参考价值的文章主要介绍了Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

引出


1.认证鉴权服务,注册中心,认证中心,鉴权中心;
2.用户,角色,权限表设计,数据库视图的使用;
3.项目中的应用,使用自定义注解+拦截器;
4.枚举类型的json化, @JsonFormat(shape = JsonFormat.Shape.OBJECT) @Getter

https://gitee.com/pet365/springboot-privs-token

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

使用token的权限验证方法

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

流程

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

用户、角色、权限表设计

用户和权限之间关系(多对多)

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

中间内容: 角色

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

(本系统中: user—》角色(one-to-Many)

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

权限表

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

角色表

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

角色-权限关联表

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

用户表

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

查询用户的权限(四表联查)

-- 用户角色-权限模型

SELECT 
user_owner.username,privs_role_tab.role_name,privs_tab.privs_name
FROM user_owner
LEFT JOIN privs_role_tab ON user_owner.user_role = privs_role_tab.role_id
LEFT JOIN privs_relationship_tab ON privs_relationship_tab.rp_role = privs_role_tab.role_id
LEFT JOIN privs_tab ON privs_tab.privs_id=privs_relationship_tab.rp_privs

数据库的视图

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

项目中的应用

https://gitee.com/pet365/springboot-privs-token

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

自定义注解

PrivsCheck.java文件

package com.tianju.auth.util;

import java.lang.annotation.*;

/**
 * 定义注解
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PrivsCheck {
    String value() default "";
}

拦截器

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

AuthInterceptor.java文件

package com.tianju.auth.interceptor;

import cn.hutool.json.JSONUtil;
import com.tianju.auth.dto.HttpResp;
import com.tianju.auth.dto.ResultCode;
import com.tianju.auth.util.JwtUtil;
import com.tianju.auth.util.PrivsCheck;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Date;

@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    /**
     *
     * @param request 请求
     * @param response 响应
     * @param handler =====>handler====>:class org.springframework.web.method.HandlerMethod
     *                com.tianju.auth.controller.UserController#findAllUsernames()
     *                类 的 findAllUsernames() 方法
     *                Method method = handlerMethod.getMethod();// controller里面的方法findAllUsernames 对象
     *                Annotation[] annotations = method.getDeclaredAnnotations();// 可以获得该方法上的所有注解
     * @return 是否拦截
     * @throws Exception token过期异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        response.setContentType("text/html;charset=utf-8");
        if (token==null){ // 如果没有token,返回false
            response.getWriter().write(
                    JSONUtil.toJsonStr(
                            HttpResp.results(
                                    ResultCode.USER_NOT_LOGIN_ERROR, new Date(),"用户没有登陆异常"
                            )));
            return false;
        }
        // 存在的用户,检验token是否过期

        try {
            // 正常情况
            String username = JwtUtil.getClaim(token, "username");
            String privs = JwtUtil.getClaim(token, "privs");
            // 判断是否能够访问当前的方法
            log.info("用户权限{}",privs);
            // handler:com.tianju.auth.controller.UserController#findAllUsernames()
            log.debug("handler:{}",handler);
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();// controller里面的方法findAllUsernames 对象
            Annotation[] annotations = method.getDeclaredAnnotations();// 可以获得该方法上的所有注解
            /**
                 * @org.springframework.web.bind.annotation.GetMapping(path=[], headers=[], name=, produces=[], params=[], value=[/findAllUsernames], consumes=[])
                 * @io.swagger.annotations.ApiOperation(code=200, notes=, hidden=false, authorizations=[@io.swagger.annotations.Authorization(scopes=[@io.swagger.annotations.AuthorizationScope(scope=, description=)], value=)], httpMethod=, tags=[查询所有用户名], extensions=[@io.swagger.annotations.Extension(name=, properties=[@io.swagger.annotations.ExtensionProperty(parseValue=false, name=, value=)])], responseHeaders=[@io.swagger.annotations.ResponseHeader(name=, responseContainer=, description=, response=class java.lang.Void)], response=class java.lang.Void, responseReference=, responseContainer=, produces=, nickname=, ignoreJsonView=false, position=0, protocols=, consumes=, value=findAllUsernames)
                 * @com.tianju.auth.util.PrivsCheck(value=findAllUsernames)
             */
//            for (Annotation annotation: annotations) {
//                /**
//                 * @org.springframework.web.bind.annotation.GetMapping(path=[], headers=[], name=, produces=[], params=[], value=[/findAllUsernames], consumes=[])
//                 * @io.swagger.annotations.ApiOperation(code=200, notes=, hidden=false, authorizations=[@io.swagger.annotations.Authorization(scopes=[@io.swagger.annotations.AuthorizationScope(scope=, description=)], value=)], httpMethod=, tags=[查询所有用户名], extensions=[@io.swagger.annotations.Extension(name=, properties=[@io.swagger.annotations.ExtensionProperty(parseValue=false, name=, value=)])], responseHeaders=[@io.swagger.annotations.ResponseHeader(name=, responseContainer=, description=, response=class java.lang.Void)], response=class java.lang.Void, responseReference=, responseContainer=, produces=, nickname=, ignoreJsonView=false, position=0, protocols=, consumes=, value=findAllUsernames)
//                 * @com.tianju.auth.util.PrivsCheck(value=findAllUsernames)
//                 */
//            }
            PrivsCheck annotation = method.getDeclaredAnnotation(PrivsCheck.class);
            System.out.println(annotation.value());
            if (privs.contains(annotation.value())){ // 有此权限
                return true;
            }else {
                response.getWriter().write(
                        JSONUtil.toJsonStr(
                                HttpResp.results(
                                        ResultCode.USER_ACCESS_ERROR, new Date(),"对不起权限不足"
                                )));
                return false;
            }


        }catch (ExpiredJwtException e){
            // token过期
            response.getWriter().write(
                    JSONUtil.toJsonStr(
                            HttpResp.results(
                                    ResultCode.USER_LOGIN_TOKEN_EXPIRED_ERROR, new Date(),"token过期"
                            )));
            return false;

        }

    }
}

拦截器的配置AuthConfig.java文件

package com.tianju.auth.config;

import com.tianju.auth.interceptor.AuthInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class AuthConfig implements WebMvcConfigurer {

    @Autowired
    private AuthInterceptor authInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor)
                .addPathPatterns("/api/**")
                .excludePathPatterns("/api/user/login");
    }
}

controller层

package com.tianju.auth.controller;

import com.tianju.auth.dto.HttpResp;
import com.tianju.auth.dto.ResultCode;
import com.tianju.auth.entity.UserPrivs;
import com.tianju.auth.service.IUserService;
import com.tianju.auth.util.JwtUtil;
import com.tianju.auth.util.PrivsCheck;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/user")
@Api(tags = "用户api接口")
public class UserController {

    @Autowired
    private IUserService userService;

    @ApiOperation(value = "login",tags = "用户登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username",value = "用户名",required = true),
            @ApiImplicitParam(name = "password",value = "密码",required = true)

    })
    @GetMapping("/login")
    public HttpResp login(String username, String password, HttpServletResponse response){
        List<UserPrivs> users = userService.login(username, password);
        StringBuilder privs = new StringBuilder();
        users.forEach(userPrivs -> privs.append(userPrivs.getPrivsName()+","));
        System.out.println("用户权限:"+privs);
        privs.deleteCharAt(privs.length()-1);
        String token = JwtUtil.createToken(username, privs.toString(), 1000 * 60);
        response.addHeader("token", token);
        return HttpResp.results(ResultCode.USER_LOGIN_SUCCESS,new Date(),username);
    }

    @GetMapping("/findAllUsernames")
    @ApiOperation(value = "findAllUsernames",tags = "查询所有用户名")
//    @PrivsCheck("findAllUsernames")
    @PrivsCheck("findX") // 设置一个没有的权限
    public HttpResp findAllUsernames(){
        List<String> allUsernames = userService.findAllUsernames();
        return HttpResp.results(ResultCode.USER_QUERY_SUCCESS,new Date(),allUsernames);
    }
}

DTO返回给前端

枚举类型的json化

Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用,SpringBoot,Java,spring boot,json,前端

@JsonFormat(shape = JsonFormat.Shape.OBJECT)

package com.tianju.auth.dto;

import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;


/**
 * 枚举类型,http请求的返回值
 */
// 枚举类型的json化,需要有get方法
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
@Getter
public enum ResultCode {
    BOOK_RUSH_SUCCESS(20010,"图书抢购成功"),
    BOOK_RUSH_ERROR(3001,"图书抢购失败"),
    LUA_SCRIPT_ERROR(3002,"Lua脚本操作失败"),
    USER_FIND_ERROR(40010,"非法请求,布隆过滤器不通过"),
    USER_FIND_SUCCESS(20010,"查询用户名成功"),
    USER_QUERY_SUCCESS(25010,"查询所有用户名成功"),
    USER_LOGIN_ERROR(40030,"用户登陆失败"),
    USER_NOT_LOGIN_ERROR(40040,"用户没有登陆异常"),
    USER_LOGIN_TOKEN_EXPIRED_ERROR(42040,"token已过期异常"),
    USER_ACCESS_ERROR(45040,"用户权限异常"),
    USER_LOGIN_SUCCESS(20020,"用户登陆成功"),
    ;

    @ApiModelProperty("状态码")
    private Integer code;

    @ApiModelProperty("提示信息")
    private String msg;

    private ResultCode(Integer code,String msg){
        this.code =code;
        this.msg = msg;
    }
}

日期json问题

@JsonFormat(timezone = “GMT+8”)

package com.tianju.auth.dto;

import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Date;

/**
 * 返回给前端的响应
 * @param <T>
 */
@ApiModel("DTO返回数据")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class HttpResp<T> implements Serializable {
    private ResultCode resultCode;
    @ApiModelProperty("time")
    @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss",timezone = "GMT+8")
    private Date time;
    @ApiModelProperty("results")
    private T result;

    public static <T> HttpResp <T> results(
            ResultCode resultCode,
            Date time,
            T results){

        HttpResp httpResp = new HttpResp();
        httpResp.setResultCode(resultCode);
        httpResp.setTime(time);
        httpResp.setResult(results);
        return httpResp;
    }
}

实体类-DAO

package com.tianju.auth.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("user_privs_view")
public class UserPrivs {
    @TableField("username")
    private String username;
    @TableField("password")
    private String password;
    @TableField("role_name")
    private String roleName;
    @TableField("privs_name")
    private String privsName;
}

dao

package com.tianju.auth.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.tianju.auth.entity.UserPrivs;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<UserPrivs> {
}


总结

1.认证鉴权服务,注册中心,认证中心,鉴权中心;
2.用户,角色,权限表设计,数据库视图的使用;
3.项目中的应用,使用自定义注解+拦截器;
4.枚举类型的json化, @JsonFormat(shape = JsonFormat.Shape.OBJECT) @Getter文章来源地址https://www.toymoban.com/news/detail-634079.html

到了这里,关于Jwt(Json web token)——使用token的权限验证方法 & 用户+角色+权限表设计 & SpringBoot项目应用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Json Web Token(JWT)

    JSON Web Token (JWT) 是一个开放标准 ( RFC 7519 ),它定义了一种紧凑且自包含的方式,用于在各方之间以 JSON 对象的形式安全传输信息。此信息可以验证和信任,因为它是数字签名的。JWT 可以使用密钥(使用HMAC算法)或使用RSA或ECDSA的公钥/私钥对进行签名。 1.Authorization(授权):

    2024年02月19日
    浏览(31)
  • JWT(Json Web Token)简介

    一般的Token认证流程是这样的:         1. 用户输入用户名和密码,发送给服务器。          2. 服务器验证用户名和密码,正确的话就返回一个签名过的token(token 可以认为就是个长长的字符串),浏览器客户端拿到这个token。          3. 后续每次请求中,浏览器

    2023年04月08日
    浏览(21)
  • 什么是JWT(JSON Web Token)?

    JWT(JSON Web Token)是一种开放标准(RFC 7519),用于在网络应用间传递信息的安全传输方式。它通过数字签名来验证信息的合法性,并且具有自包含性,即它包含了足够的信息以供验证和识别。 JWT通常由三部分组成:头部(Header)、载荷(Payload)和签名(Signature)。 1. 头部(

    2024年02月12日
    浏览(33)
  • JWT(JSON Web Token )详解及实例

    目录 一、什么是 JWT ? 二、什么时候使用 JWT ? 三、JWT 格式 1、Header 2、Payload 3、Signature 4、 JWT实现: 官网 JSON Web Tokens - jwt.io RFC 7519文档 RFC 7519: JSON Web Token (JWT) JSON Web Token(JWT)是一种开放标准(RFC 7519),它定义了一种紧凑且自包含的方式,用于在各方之间作为JSON对象安全

    2024年02月06日
    浏览(34)
  • JWT(Json Web Token)的原理、渗透与防御

    (关于JWT kid安全部分后期整理完毕再进行更新~2023.05.16) JWT全称为Json web token,是为了在网络应用环境间传递声明而执行的一中基于JSON的开放标准。常用于分布式站点的单点登录。 JWT的声明一般被用在客户端与服务端之间传递身份认证信息,便于向服务端请求资源。 (我理

    2024年02月05日
    浏览(27)
  • 04 动力云客之登录后获取用户信息+JWT存进Redis+Filter验证Token + token续期

    非常好实现. 只要新建一个controller, 并调用SS提供的Authentication对象即可 未登录状态下可以直接访问 api/login/info吗? 不可以. 因为在安全配置类已经写明了, 仅登陆界面允许任何人访问, 其他所有界面都需要认证 由于未写JWT, 默认使用Session 保存会话, ???好像不对 因此只要我们先

    2024年02月21日
    浏览(35)
  • 深入解析 JWT(JSON Web Tokens):原理、应用场景与安全实践

    JWT(JSON Web Tokens)是一种开放标准(RFC 7519),用于在各方之间安全地传输信息作为 JSON 对象。由于其小巧和自包含的特性,它在 Web 应用程序和服务之间尤其流行用于身份验证和信息交换。JWT 的主要优点和特性包括: 自包含(Self-contained): JWT 本身包含了所有必要的信息。

    2024年02月04日
    浏览(37)
  • 解锁互联网安全的新钥匙:JWT(JSON Web Token)

    目录 前言 一、JWT简介 1. 什么是JWT? ​编辑 2. JWT的工作原理 3.JWT如何工作的 4. JWT的优势 5. 在实际应用中使用JWT 6.传统Session和JWT认证的区别 6.1.session认证方式 6.2.JWT认证方式 7.基于Token的身份认证 与 基于服务器的身份认证  二、JWT的结构 (1) Header (2) Payload (3) Signature  三、

    2024年02月08日
    浏览(31)
  • spring boot中常用的安全框架 Security框架 利用Security框架实现用户登录验证token和用户授权(接口权限控制)

    spring boot中常用的安全框架 Security 和 Shiro 框架 Security 两大核心功能 认证 和 授权 重量级 Shiro 轻量级框架 不限于web 开发 在不使用安全框架的时候 一般我们利用过滤器和 aop自己实现 权限验证 用户登录 Security 实现逻辑 输入用户名和密码 提交 把提交用户名和密码封装对象

    2024年02月06日
    浏览(35)
  • 如何使用 NestJS 集成 Passort 和 JWT Token 实现 HTTP 接口的权限管理

    💡 如果你不希望其他人可以随意进出你的房子,那么你需要给你的房子上个锁。 开发一个接口很容易,开发一个具有安全性的接口却不容易。成熟的后端服务项目最注重的一点就是如何保护系统的数据安全,不能让用户无脑的访问操作所有的数据,这是不合理更是极度危险

    2024年01月22日
    浏览(34)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包