我有一个使用 Quarkus 的 REST API,我想在其中编写一个拦截器,它为 API 中的每个端点获取不同的参数。基本上我想提供字符串并查看它们是否位于请求附带的 JWT 中。我很难根据需要获取参数(作为字符串)。
这是注释:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import javax.enterprise.util.Nonbinding;
import javax.interceptor.InterceptorBinding;
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface ScopesAllowed {
@Nonbinding
String[] value();
}
Run Code Online (Sandbox Code Playgroud)
这是使用它的一个端点:
import javax.ws.rs.GET;
import java.util.List;
public class TenantResource {
@GET
@ScopesAllowed({"MyScope", "AnotherScope"})
public List<Tenant> getTenants() {
}
}
Run Code Online (Sandbox Code Playgroud)
这是我对拦截器的尝试:
@Interceptor
@Priority(3000)
@ScopesAllowed({})
public class ScopesAllowedInterceptor {
@Inject
JsonWebToken jwt;
@AroundInvoke
public Object validate(InvocationContext ctx) throws Exception {
// get annotation parameters and check JWT
return ctx.proceed(); …Run Code Online (Sandbox Code Playgroud) 在我们的 JEE 应用程序中,我们创建了一个新注释@MyAnnotation,并将其设置在 CDI beans ( @ApplicationScoped ) 上。
然后我们有一个拦截器,它拦截所有带有@MyAnnotation注释的 bean 。
问题是它不适用于由@Produces方法创建的 bean。
这意味着拦截器没有被调用。
所以如果我们有这个类:
@ApplicationScoped
public class OtherClass
{
@Inject
private MyBean myBean;
public void f()
{
myBean.g();
}
}
Run Code Online (Sandbox Code Playgroud)
然后以下将起作用:
@ApplicationScoped
@MyAnnotation
public class MyBean
{
public void g() {}
}
Run Code Online (Sandbox Code Playgroud)
但下面的不会:
@ApplicationScoped
public class MyBeanProducer
{
@Produces
public MyBean create()
{
return new MyBean();
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法让拦截器拦截使用 @Produces 创建的 CDI bean?
我正在使用 "axios": "^0.23.0" 以及 ReactJs 和 Typescript。
我想拦截请求和响应并添加用户的令牌。
当我尝试使用请求拦截器时,出现以下错误:
Object is possibly 'undefined'. TS2532
(property) AxiosRequestConfig<any>.headers?: AxiosRequestHeaders | undefined
(config) => {
const user = getUserLocalStorage();
config.headers.Authorization = user?.token;
^
return config;
},
(error) => {
Run Code Online (Sandbox Code Playgroud)
当我将 .Authorization 添加到时,会发生此错误
config.headers.Authorization = user?.token;
Run Code Online (Sandbox Code Playgroud)
我应该怎么做才能修复这个错误?
这些是我正在使用的方法:
api.ts
import axios from "axios";
import { getUserLocalStorage } from "../context/AuthProvider/util";
export const Api = axios.create({
baseURL: "http://localhost:8000/",
});
Api.interceptors.request.use(
(config) => {
const user = getUserLocalStorage();
config.headers.Authorization = user?.token;
return config;
},
(error) => { …Run Code Online (Sandbox Code Playgroud) React 路由器 v6 如何使用navigate. axios拦截器
互联网上有很多例子。但怎样做才是正确的呢?如果可以的话,请提供详细的描述。谢谢!
import axios from 'axios'
export const HTTP = axios.create({
baseURL: "http://URL.ru/",
headers: {
"content-type": "application/json",
},
})
HTTP.interceptors.response.use(response => response, error => {
if (error.response.status === 401) {
//navigate('/login')
}
return Promise.reject(error)
})
Run Code Online (Sandbox Code Playgroud) 我有一个在大多数操作之前运行的LoginInterceptor,并检查该成员是否已登录.如果是,则显示页面,否则重定向到登录页面.
但是我只是注意到拦截器"阻止"所有URL参数.基本上,如果在操作之前存在拦截器,则此操作的URL参数将不会传递给setter.
这是我的拦截器:
public class LoginInterceptor extends AbstractInterceptor {
public String intercept(final ActionInvocation invocation) throws Exception {
final String REDIR = "loginRedirect";
AuthenticationService auth = new AuthenticationService();
if (auth.isMemberLoggedIn()) {
return invocation.invoke();
} else {
return REDIR;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我怀疑invocation.invoke()调用动作,但没有参数.
我能做些什么呢?
更新:
AuthenticationService.isMemberLoggedIn()
public boolean isMemberLoggedIn() {
Map<String, Object> session = ActionContext.getContext().getSession();
String username = (String) session.get("username");
if (username != null) {
return true;
} else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
在struts.xml
<package name="global" extends="struts-default">
<interceptors>
<interceptor …Run Code Online (Sandbox Code Playgroud) 我是JSF-2和CDI的新手(我来自Spring世界).
我想从@ManagedBean拦截一个方法,但我的Interceptor类永远不会被调用.有可能吗?
LogInterceptor.java
@Interceptor
public class LogInterceptor {
@AroundInvoke
public Object log(InvocationContext ctx) throws Exception {
System.out.println("begin method interceptor");
Object methodReturn = ctx.proceed();
System.out.println("end method interceptor");
return methodReturn;
}
}
Run Code Online (Sandbox Code Playgroud)
RoleMB
@ManagedBean
@ViewScoped
public class RoleMB extends BaseMB {
@Interceptors(LogInterceptor.class)
public void preEditRole(Role role) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
beans.xml中
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
<interceptors>
<class>br.com.preventsenior.services.log.LogInterceptor</class>
</interceptors>
</beans>
Run Code Online (Sandbox Code Playgroud)
将log(InvocationContext ctx)永远不会被调用.
我正在使用拦截器限制对应用程序中某些用户的访问.例如:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
Logger.logRequest(request);
return list.contains(user);
}
Run Code Online (Sandbox Code Playgroud)
如果列表包含用户,则完成请求.否则,它什么都不做.
如果用户无权访问,如何显示自定义页面?现在,如果它是假的,它只显示一个空白页面,这对用户体验不太好.
我使用spring boot和freemarker创建了一个Web应用程序,并实现了拦截器(HandlerInterceptorAdapter).
在拦截器内部,当用户未登录时,它将重定向到登录页面.这很好用.但问题是控制器在重定向到登录页面之前首先被执行.
我的拦截器代码:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
User userSession = (User) request.getSession().getAttribute("user");
if (userSession == null) {
response.sendRedirect("/login");
}
}
Run Code Online (Sandbox Code Playgroud)
控制器类(在response.sendRedirect之后,此控制器仍然被执行).为什么?我陷入了这个问题.
@RequestMapping("/home")
public String home(Model model, HttpServletRequest httpServletRequest) {
String returnPage = "home-admin";
User user = (User) httpServletRequest.getSession().getAttribute("user");
if(user != null){
String accessType = accessTypeRepository.getAccessType(user.getAccessId());
if(StrUtil.isEqual(accessType, AccessTypeConst.MANAGER.getType())){
returnPage = "home-manager";
}
}
return returnPage;
}
Run Code Online (Sandbox Code Playgroud) 我目前正在使用Angular4应用程序。现在,我要实现XSRF保护。在Response标头Cookie中,我得到“ XSRF-TOKEN”,并且需要在下一个Request标头Cookie中发送“ X-XSRF-TOKEN”。如Angular官方文档中所述,Angular正在处理此问题。但是就我而言,angular并没有处理它。因此,我创建了以下自定义XsrfInterceptor,以将“ X-XSRF-TOKEN”附加到响应头。
import { NgModule, Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { HttpRequest, HttpHandler, HttpEvent, HttpXsrfTokenExtractor, HttpInterceptor } from "@angular/common/http";
@Injectable()
export class XsrfInterceptor implements HttpInterceptor {
constructor(private tokenExtractor: HttpXsrfTokenExtractor) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headerName = 'X-XSRF-TOKEN';
console.log("xsrf intercepter called");
let requestToForward = req;
let token = this.tokenExtractor.getToken() as string;
console.log(token);
if (token !== null) {
requestToForward = req.clone({ setHeaders: {headerName: token } });
}
return …Run Code Online (Sandbox Code Playgroud) 我正在尝试将HTTP拦截器添加到现有的Angular应用程序中.
关键是,它已经有一个拦截器提供:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: CustomInterceptor,
multi: true
},
AuthGuard, AuthService, AuthenticationInterceptor],
Run Code Online (Sandbox Code Playgroud)
就我所知的拦截概念而言,它们可以互相管道传递.因此我尝试了这个:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: CustomInterceptor, // existing interceptor
multi: true
}, AuthGuard, AuthService,
{
provide: HTTP_INTERCEPTORS,
useClass: AuthenticationInterceptor, // my interceptor
multi: true
}],
Run Code Online (Sandbox Code Playgroud)
事情正在发挥作用.但我不确定我是否已经覆盖了现有的拦截器.在Angular 5中注册多个拦截器是否可以?他们互相取消了吗?或者他们只是作为管道中的工作站工作并相互增强?
interceptor ×10
angular ×2
axios ×2
cdi ×2
java ×2
reactjs ×2
spring-mvc ×2
annotations ×1
cookies ×1
jakarta-ee ×1
jsf ×1
jsf-2 ×1
managed-bean ×1
quarkus ×1
redirect ×1
request ×1
rest ×1
spring ×1
spring-boot ×1
struts2 ×1
typescript ×1
x-xsrf-token ×1