Java的接口調(diào)用時(shí)的權(quán)限驗(yàn)證功能的實(shí)現(xiàn)
提示:這里可以添加本文要記錄的大概內(nèi)容:
例如:一般系統(tǒng)前端調(diào)用后臺(tái)相關(guān)功能接口時(shí),需要驗(yàn)證此時(shí)用戶(hù)的權(quán)限是否滿足調(diào)用該接口的條件,因此我們需要配置相應(yīng)的驗(yàn)證權(quán)限的功能。
提示:以下是本篇文章正文內(nèi)容,下面案例可供參考
一、編寫(xiě)的環(huán)境
工具:IDEA
框架:GUNS框架(自帶后臺(tái)權(quán)限驗(yàn)證配置,我們這里需要編寫(xiě)前端權(quán)限驗(yàn)證配置)
二、使用步驟
1.配置前端調(diào)用的接口
代碼如下(示例):
在WebSecurityConfig中:
// 登錄接口放開(kāi)過(guò)濾 .antMatchers("/login").permitAll() // session登錄失效之后的跳轉(zhuǎn) .antMatchers("/global/sessionError").permitAll() // 圖片預(yù)覽 頭像 .antMatchers("/system/preview/*").permitAll() // 錯(cuò)誤頁(yè)面的接口 .antMatchers("/error").permitAll() .antMatchers("/global/error").permitAll() // 測(cè)試多數(shù)據(jù)源的接口,可以去掉 .antMatchers("/tran/**").permitAll() //獲取租戶(hù)列表的接口 .antMatchers("/tenantInfo/listTenants").permitAll() //微信公眾號(hào)接入 .antMatchers("/weChat/**").permitAll() //微信公眾號(hào)接入 .antMatchers("/file/**").permitAll() //前端調(diào)用接口 .antMatchers("/api/**").permitAll() .anyRequest().authenticated();
加入前端調(diào)用接口請(qǐng)求地址:
.antMatchers("/api/**").permitAll()
添加后前端所有/api的請(qǐng)求都會(huì)被攔截,不會(huì)直接調(diào)用相應(yīng)接口
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) { //默認(rèn)攔截所有路徑 registry.addInterceptor(authenticationInterceptor()) .addPathPatterns("/api/**") ; } @Bean public HandlerInterceptor authenticationInterceptor() { return new JwtAuthenticationInterceptor(); } }
3.創(chuàng)建驗(yàn)證文件
創(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驗(yàn)證 * @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 { // 如果不是映射到方法直接通過(guò) if (!(object instanceof HandlerMethod)) { return true; } HandlerMethod handlerMethod = (HandlerMethod) object; Method method = handlerMethod.getMethod(); //檢查是否有passtoken注釋?zhuān)袆t跳過(guò)認(rèn)證 if (method.isAnnotationPresent(PassToken.class)) { PassToken passToken = method.getAnnotation(PassToken.class); if (passToken.required()) { return true; } } //默認(rèn)全部檢查 else { // 執(zhí)行認(rèn)證 Object token1 = httpServletRequest.getSession().getAttribute("token"); if (token1 == null) { //這里其實(shí)是登錄失效,沒(méi)token了 這個(gè)錯(cuò)誤也是我自定義的,讀者需要自己修改 httpServletResponse.sendError(401,"未登錄"); throw new NeedToLogin(); } String token = token1.toString(); //獲取載荷內(nèi)容 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(); //判斷當(dāng)前為名師 if (RoleEnum.TOP_TEACHER.equals(type)){ //檢查用戶(hù)是否存在 TopTeacher topTeacher = topTeacherService.getById(id); if (topTeacher == null || topTeacher.getStatus().equals(StatusEnum.FORBIDDEN)) { httpServletResponse.sendError(203,"非法操作"); //這個(gè)錯(cuò)誤也是我自定義的 throw new UserNotExist(); } //學(xué)生 }else { //需要檢查用戶(hù)是否存在 Student user = studentService.getById(id); if (user == null || user.getStatus().equals(StatusEnum.FORBIDDEN)) { httpServletResponse.sendError(203,"非法操作"); //這個(gè)錯(cuò)誤也是我自定義的 throw new UserNotExist(); } } // 驗(yàn)證 token JwtUtils.verifyToken(token, id); //放入attribute以便后面調(diào)用 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 { } }
文件中有個(gè)string類(lèi)型的token,這個(gè)token是用戶(hù)登錄時(shí)在controller里創(chuàng)建的,具體代碼加在用戶(hù)登陸的接口里:
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; /** * 在方法上加入本注解 即可跳過(guò)登錄驗(yàn)證 比如登錄 * @author Administrator */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface PassToken { boolean required() default true; }
總結(jié)
提示:這里對(duì)文章進(jìn)行總結(jié):
以上就是完整的編寫(xiě)一個(gè)前端頁(yè)面調(diào)用控制器接口時(shí),進(jìn)行驗(yàn)證判斷相應(yīng)權(quán)限的代碼實(shí)現(xiàn)。主要是針對(duì)guns框架寫(xiě)的,因?yàn)間uns框架本來(lái)自帶接口權(quán)限驗(yàn)證功能,只不過(guò)只是針對(duì)后臺(tái)而已,我在這里添加了針對(duì)前端的權(quán)限驗(yàn)證,僅供參考。
到此這篇關(guān)于Java的接口調(diào)用時(shí)的權(quán)限驗(yàn)證功能的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Java 接口調(diào)用時(shí)權(quán)限驗(yàn)證內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在Struts2中如何將父類(lèi)屬性序列化為JSON格式的解決方法
本篇文章,小編將為大家介紹關(guān)于在Struts2中如何將父類(lèi)屬性序列化為JSON格式的解決方法,有需要的朋友可以參考一下2013-04-04使用Jmeter進(jìn)行http接口測(cè)試的實(shí)踐
本文主要針對(duì)http接口進(jìn)行測(cè)試,使用Jmeter工具實(shí)現(xiàn)。文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11JVM對(duì)象創(chuàng)建和內(nèi)存分配原理解析
這篇文章主要介紹了JVM對(duì)象創(chuàng)建和內(nèi)存分配原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02基于SpringBoot的Dubbo泛化調(diào)用的實(shí)現(xiàn)代碼
這篇文章主要介紹了基于SpringBoot的Dubbo泛化調(diào)用的實(shí)現(xiàn),從泛化調(diào)用實(shí)現(xiàn)的過(guò)程來(lái)看,我們可以對(duì)自己提供所有服務(wù)進(jìn)行測(cè)試,不需要引入調(diào)用的接口,減少代碼的侵入,需要的朋友可以參考下2022-04-04Java異步判斷線程池所有任務(wù)是否執(zhí)行完成的操作方法
這篇文章主要介紹了Java異步判斷線程池所有任務(wù)是否執(zhí)行完成的方法,在這個(gè)示例中,我使用了傳統(tǒng)的匿名內(nèi)部類(lèi)來(lái)創(chuàng)建Callable任務(wù)(同時(shí)也提供了Lambda表達(dá)式的注釋?zhuān)?以便與各種Java版本兼容,需要的朋友可以參考下2024-07-07JavaWeb Session失效時(shí)間設(shè)置方法
這篇文章主要介紹了JavaWeb Session失效時(shí)間設(shè)置方法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-12-12詳解springboot+atomikos+druid?數(shù)據(jù)庫(kù)連接失效分析
本文主要介紹了springboot+atomikos+druid?數(shù)據(jù)庫(kù)連接失效分析,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02