Java的接口调用时的权限验证功能的实现
作者:不给就捣乱 发布时间:2023-08-09 11:15:06
标签:Java,接口调用时,权限验证
提示:这里可以添加本文要记录的大概内容:
例如:一般系统前端调用后台相关功能接口时,需要验证此时用户的权限是否满足调用该接口的条件,因此我们需要配置相应的验证权限的功能。
提示:以下是本篇文章正文内容,下面案例可供参考
一、编写的环境
工具:IDEA
框架:GUNS框架(自带后台权限验证配置,我们这里需要编写前端权限验证配置)
二、使用步骤
1.配置前端调用的接口
代码如下(示例):
在WebSecurityConfig中:
// 登录接口放开过滤
.antMatchers("/login").permitAll()
// session登录失效之后的跳转
.antMatchers("/global/sessionError").permitAll()
// 图片预览 头像
.antMatchers("/system/preview/*").permitAll()
// 错误页面的接口
.antMatchers("/error").permitAll()
.antMatchers("/global/error").permitAll()
// 测试多数据源的接口,可以去掉
.antMatchers("/tran/**").permitAll()
//获取租户列表的接口
.antMatchers("/tenantInfo/listTenants").permitAll()
//微信公众号接入
.antMatchers("/weChat/**").permitAll()
//微信公众号接入
.antMatchers("/file/**").permitAll()
//前端调用接口
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated();
加入前端调用接口请求地址:
.antMatchers("/api/**").permitAll()
添加后前端所有/api的请求都会被拦截,不会直接调用相应接口
2.配置拦截路径
代码如下(示例):
在创建文件JwtlnterceptorConfig:
package cn.stylefeng.guns.sys.modular.bzjxjy.config.jwt;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class JwtInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//默认拦截所有路径
registry.addInterceptor(authenticationInterceptor())
.addPathPatterns("/api/**")
;
}
@Bean
public HandlerInterceptor authenticationInterceptor() {
return new JwtAuthenticationInterceptor();
}
}
3.创建验证文件
创建文件JwtAuthenticationInterceptor,代码如下(示例):
package cn.stylefeng.guns.sys.modular.bzjxjy.config.jwt;
import cn.stylefeng.guns.sys.modular.bzjxjy.entity.Student;
import cn.stylefeng.guns.sys.modular.bzjxjy.entity.TopTeacher;
import cn.stylefeng.guns.sys.modular.bzjxjy.enums.RoleEnum;
import cn.stylefeng.guns.sys.modular.bzjxjy.enums.StatusEnum;
import cn.stylefeng.guns.sys.modular.bzjxjy.exception.NeedToLogin;
import cn.stylefeng.guns.sys.modular.bzjxjy.exception.UserNotExist;
import cn.stylefeng.guns.sys.modular.bzjxjy.service.StudentService;
import cn.stylefeng.guns.sys.modular.bzjxjy.service.TopTeacherService;
import cn.stylefeng.guns.sys.modular.bzjxjy.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
/**
* jwt验证
* @author Administrator
*/
public class JwtAuthenticationInterceptor implements HandlerInterceptor {
@Autowired
private TopTeacherService topTeacherService;
@Autowired
private StudentService studentService;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
// 如果不是映射到方法直接通过
if (!(object instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) object;
Method method = handlerMethod.getMethod();
//检查是否有passtoken注释,有则跳过认证
if (method.isAnnotationPresent(PassToken.class)) {
PassToken passToken = method.getAnnotation(PassToken.class);
if (passToken.required()) {
return true;
}
}
//默认全部检查
else {
// 执行认证
Object token1 = httpServletRequest.getSession().getAttribute("token");
if (token1 == null) {
//这里其实是登录失效,没token了 这个错误也是我自定义的,读者需要自己修改
httpServletResponse.sendError(401,"未登录");
throw new NeedToLogin();
}
String token = token1.toString();
//获取载荷内容
String type = JwtUtils.getClaimByName(token, "type").asString();
String id = JwtUtils.getClaimByName(token, "id").asString();
String name = JwtUtils.getClaimByName(token, "name").asString();
String idNumber = JwtUtils.getClaimByName(token, "idNumber").asString();
//判断当前为名师
if (RoleEnum.TOP_TEACHER.equals(type)){
//检查用户是否存在
TopTeacher topTeacher = topTeacherService.getById(id);
if (topTeacher == null || topTeacher.getStatus().equals(StatusEnum.FORBIDDEN)) {
httpServletResponse.sendError(203,"非法操作");
//这个错误也是我自定义的
throw new UserNotExist();
}
//学生
}else {
//需要检查用户是否存在
Student user = studentService.getById(id);
if (user == null || user.getStatus().equals(StatusEnum.FORBIDDEN)) {
httpServletResponse.sendError(203,"非法操作");
//这个错误也是我自定义的
throw new UserNotExist();
}
}
// 验证 token
JwtUtils.verifyToken(token, id);
//放入attribute以便后面调用
httpServletRequest.setAttribute("type", type);
httpServletRequest.setAttribute("id", id);
httpServletRequest.setAttribute("name", name);
httpServletRequest.setAttribute("idNumber", idNumber);
return true;
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, Exception e) throws Exception {
}
}
文件中有个string类型的token,这个token是用户登录时在controller里创建的,具体代码加在用户登陆的接口里:
String token = JwtUtils.createToken(topTeacher.getId(), RoleEnum.TOP_TEACHER,topTeacher.getName(),idNumber);
request.getSession().setAttribute("token",token);
4.创建注解@PassToken
package cn.stylefeng.guns.sys.modular.bzjxjy.config.jwt;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 在方法上加入本注解 即可跳过登录验证 比如登录
* @author Administrator
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
boolean required() default true;
}
总结
提示:这里对文章进行总结:
以上就是完整的编写一个前端页面调用控制器接口时,进行验证判断相应权限的代码实现。主要是针对guns框架写的,因为guns框架本来自带接口权限验证功能,只不过只是针对后台而已,我在这里添加了针对前端的权限验证,仅供参考。
来源:https://blog.csdn.net/weixin_42632091/article/details/110069278


猜你喜欢
- 对于无.SVC文件的配置只需要指定以.svc结尾的相对地址和服务实现的完整名称即可。可问题恰恰出在这里,之前需要在<system.se
- 下面给大家分享一个有趣的动画:这里比较适合一张图片的翻转,如果是多张图片,可以参考APIDemo里的例子,就是加个ArrayAdapter,
- 调用方法:/** * 点击量/月(年)Callable */ public void yearlyClickCallable() { //
- 用 Environment 类: &
- 前言最近因为工作的需要,在写一个基于springmvc+spring+mybatis的项目,其中涉及用ajax向controller发送数据
- 前言Android 从 4.0 开始就提供了手机录屏方法,但是需要 root 权限,比较麻烦不容易实现。但是从 5.0 开始,系统提供给了
- 本文实例为大家分享了Android保存QQ密码功能的具体代码,供大家参考,具体内容如下技术要点:使用文件储存的方式保存数据实现步骤:①用户交
- 本文实例讲述了C#将Sql数据保存到Excel文件中的方法,非常有实用价值。分享给大家供大家参考借鉴之用。具体功能代码如下:public s
- 之前学习oracle,简单的认为数据库只存在服务器端,学习安卓之后才发现原来android和Ios本身是“携带”数据库的——SQ
- 给对象中的包装类设置默认值处理方法如下主要适用于,对象中使用了包装类,但是不能给null需要有默认值的情况/**
- 本文实例讲述了C#基于委托实现多线程之间操作的方法。分享给大家供大家参考,具体如下:有的时候我们要起多个线程,更多的时候可能会有某个线程会去
- 简单工厂简单工厂模式是属于创建型模式,是工厂模式的一种。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。定义了一个创建对象的类,由
- 本文实例讲述了C#封装的Sqlite访问类。分享给大家供大家参考。具体分析如下:C#封装的Sqlite访问类,要访问Sqlite这下简单了,
- 面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,就对对象进行存储,集合就是存储对象最常用的一种方式。数组虽然也可以存
- 本文实例为大家分享了Android实现文字下方加横线的具体代码,供大家参考,具体内容如下public class WhiteTextview
- 本文实例讲述了Android编程开发中的正则匹配操作。分享给大家供大家参考,具体如下:在Android开发中,可能也会遇到一下输入框的合法性
- 本文实例为大家分享了Android实现签名涂鸦手写板的具体代码,供大家参考,具体内容如下布局文件<?xml version="
- Android 处理OnItemClickListener时关于焦点颜色的设置问题  
- Executor接口基于以下方法可以完成增,删,改查以及事务处理等操作。事实上,mybatis中的所有数据库操作是通过调用这些方法实现的。p
- using System;using System.Collections.Generic;using System.ComponentMo