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í)用戶的權(quán)限是否滿足調(diào)用該接口的條件,因此我們需要配置相應(yīng)的驗(yàn)證權(quán)限的功能。
提示:以下是本篇文章正文內(nèi)容,下面案例可供參考
一、編寫的環(huán)境
工具:IDEA
框架:GUNS框架(自帶后臺(tái)權(quán)限驗(yàn)證配置,我們這里需要編寫前端權(quán)限驗(yàn)證配置)
二、使用步驟
1.配置前端調(diào)用的接口
代碼如下(示例):

在WebSecurityConfig中:
// 登錄接口放開過濾
.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()
//獲取租戶列表的接口
.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 {
// 如果不是映射到方法直接通過
if (!(object instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) object;
Method method = handlerMethod.getMethod();
//檢查是否有passtoken注釋,有則跳過認(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í)是登錄失效,沒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)){
//檢查用戶是否存在
TopTeacher topTeacher = topTeacherService.getById(id);
if (topTeacher == null || topTeacher.getStatus().equals(StatusEnum.FORBIDDEN)) {
httpServletResponse.sendError(203,"非法操作");
//這個(gè)錯(cuò)誤也是我自定義的
throw new UserNotExist();
}
//學(xué)生
}else {
//需要檢查用戶是否存在
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類型的token,這個(gè)token是用戶登錄時(shí)在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;
/**
* 在方法上加入本注解 即可跳過登錄驗(yàn)證 比如登錄
* @author Administrator
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
boolean required() default true;
}
總結(jié)
提示:這里對(duì)文章進(jìn)行總結(jié):
以上就是完整的編寫一個(gè)前端頁(yè)面調(diào)用控制器接口時(shí),進(jìn)行驗(yàn)證判斷相應(yīng)權(quán)限的代碼實(shí)現(xiàn)。主要是針對(duì)guns框架寫的,因?yàn)間uns框架本來自帶接口權(quán)限驗(yàn)證功能,只不過只是針對(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)文章
MyBatis 動(dòng)態(tài)SQL和緩存機(jī)制實(shí)例詳解
這篇文章主要介紹了MyBatis 動(dòng)態(tài)SQL和緩存機(jī)制實(shí)例詳解,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-09-09
SpringBoot注解@ConditionalOnClass底層源碼實(shí)現(xiàn)
這篇文章主要為大家介紹了SpringBoot注解@ConditionalOnClass底層源碼實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
基于Retrofit+Rxjava實(shí)現(xiàn)帶進(jìn)度顯示的下載文件
這篇文章主要為大家詳細(xì)介紹了基于Retrofit+Rxjava實(shí)現(xiàn)帶進(jìn)度顯示的下載文件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05
學(xué)習(xí)Java之如何正確地跳出循環(huán)結(jié)構(gòu)
我們?cè)诶醚h(huán)執(zhí)行重復(fù)操作的過程中,存在著一個(gè)需求:如何中止,或者說提前結(jié)束一個(gè)循環(huán),所以就給大家講解一下,如何在java代碼中返回一個(gè)結(jié)果,如何結(jié)束和跳出一個(gè)循環(huán),需要的朋友可以參考下2023-05-05
mybatis?plus樂觀鎖及實(shí)現(xiàn)詳解
這篇文章主要為大家介紹了mybatis?plus樂觀鎖及實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05

