Java的接口調用時的權限驗證功能的實現(xiàn)
提示:這里可以添加本文要記錄的大概內容:
例如:一般系統(tǒng)前端調用后臺相關功能接口時,需要驗證此時用戶的權限是否滿足調用該接口的條件,因此我們需要配置相應的驗證權限的功能。
提示:以下是本篇文章正文內容,下面案例可供參考
一、編寫的環(huán)境
工具: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.配置攔截路徑
代碼如下(示例):

在創(chuàng)建文件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.創(chuàng)建驗證文件
創(chuàng)建文件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 {
// 執(zhí)行認證
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里創(chuàng)建的,具體代碼加在用戶登陸的接口里:
String token = JwtUtils.createToken(topTeacher.getId(), RoleEnum.TOP_TEACHER,topTeacher.getName(),idNumber);
request.getSession().setAttribute("token",token);
4.創(chuàng)建注解@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;
}
總結
提示:這里對文章進行總結:
以上就是完整的編寫一個前端頁面調用控制器接口時,進行驗證判斷相應權限的代碼實現(xiàn)。主要是針對guns框架寫的,因為guns框架本來自帶接口權限驗證功能,只不過只是針對后臺而已,我在這里添加了針對前端的權限驗證,僅供參考。
到此這篇關于Java的接口調用時的權限驗證功能的實現(xiàn)的文章就介紹到這了,更多相關Java 接口調用時權限驗證內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
在Struts2中如何將父類屬性序列化為JSON格式的解決方法
本篇文章,小編將為大家介紹關于在Struts2中如何將父類屬性序列化為JSON格式的解決方法,有需要的朋友可以參考一下2013-04-04
基于SpringBoot的Dubbo泛化調用的實現(xiàn)代碼
這篇文章主要介紹了基于SpringBoot的Dubbo泛化調用的實現(xiàn),從泛化調用實現(xiàn)的過程來看,我們可以對自己提供所有服務進行測試,不需要引入調用的接口,減少代碼的侵入,需要的朋友可以參考下2022-04-04
Java異步判斷線程池所有任務是否執(zhí)行完成的操作方法
這篇文章主要介紹了Java異步判斷線程池所有任務是否執(zhí)行完成的方法,在這個示例中,我使用了傳統(tǒng)的匿名內部類來創(chuàng)建Callable任務(同時也提供了Lambda表達式的注釋),以便與各種Java版本兼容,需要的朋友可以參考下2024-07-07
詳解springboot+atomikos+druid?數據庫連接失效分析
本文主要介紹了springboot+atomikos+druid?數據庫連接失效分析,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02

