Authentication 在Guice筛选器中创建主体
我试图在Guice中实现一个自定义身份验证过滤器。我接收令牌,从令牌中获取用户名和域,然后创建一个主体。现在我被卡住了,我不知道如何设置校长。如果我能像这样设置request.setUserPrincipal(principal),那就太好了代码>,但显然我不能 我该怎么做 我的doFilter方法如下所示:Authentication 在Guice筛选器中创建主体,authentication,servlets,guice,Authentication,Servlets,Guice,我试图在Guice中实现一个自定义身份验证过滤器。我接收令牌,从令牌中获取用户名和域,然后创建一个主体。现在我被卡住了,我不知道如何设置校长。如果我能像这样设置request.setUserPrincipal(principal),那就太好了,但显然我不能 我该怎么做 我的doFilter方法如下所示: @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, Fi
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
if (authorizationHeader != null && authorizationHeader.length() > 0) {
String token = authorizationHeader.substring("Bearer".length()).trim();
if (token.length() > 0) {
try {
Credentials credentials = securityService.getCredentials(token);
String username = credentials.getUsername();
String realm = credentials.getRealm();
Principal principal = new HttpPrincipal(username, realm);
// request.setUserPrincipal(principal);
LOGGER.info(credentials);
} catch (Exception e) {
LOGGER.error(e);
}
}
}
filterChain.doFilter(servletRequest, servletResponse);
}
servlet规范第13.10节规定: 容器在调用之前建立请求的调用方标识 将请求分派到servlet引擎。呼叫者身份 在整个请求处理过程中或直到 应用程序成功地在上调用身份验证、登录或注销 请求 这就是为什么没有
setUserPrincipal
但也有好消息。您可以提供自己的getUserPrincipal
,因为您可以提供自己的HttpServletRequest
对象。任何servlet过滤器都可以做到这一点。看看您的代码,您正在使用两个参数调用chain方法:请求和响应。不需要传递您接收的相同对象
该规范甚至为您提供了一个助手类:HttpServletRequestWrapper
。您只需创建自己的请求类作为包装器的子类,并覆盖您想要的任何方法,如getUserPrincipal