【发布时间】:2021-05-14 14:15:26
【问题描述】:
我为 Spring 安全创建了 JWT 过滤器。 应用运行时,过滤器被执行,本应注入的字段为空(SessionDao和TokenService) 对于那些类(SessionDao 和 TokenService),我添加了注释,它们也运行良好,还添加了 spring-config.xml Beans
<bean id="sessionDao" class="com.dao.impl.SessionDaoImpl" scope="prototype"/>
<bean id="tokenService" class="com.service.impl.TokenServiceImpl" scope="prototype"/>
还尝试使用@Autowired
其他过滤器效果很好(CorsFilter(没有注入字段))
下面的JwtFilter类
@Component
@NoArgsConstructor(force = true)
@AllArgsConstructor
public class JwtFilter extends GenericFilterBean {
private static final String AUTHORIZATION_HEADER = "Authorization";
private final SessionDao sessionDao;
private final TokenService tokenService;
private final Logger log = new LoggerUtil().getLogger();
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain
filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String token = request.getHeader(AUTHORIZATION_HEADER);
try {
Authentication authentication = tokenService.getAuthentication(token);
if (authentication != null) {
AuthorizedUser authorizedUser = (AuthorizedUser) authentication.getPrincipal();
SessionEntity session = sessionDao.getByJwtId(authorizedUser.getJwtId());
if (!session.isDeleted()) {
session.setLastActivityTime(new Timestamp(System.currentTimeMillis()));
sessionDao.save(session);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
} catch (Exception ignored) {
}
filterChain.doFilter(request, response);
}
}
由 web.xml 启用 …… 科尔斯 rsoft.component.SimpleCORSFilter
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>JwtFilter</filter-name>
<filter-class>com.component.JwtFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>JwtFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
如果我在 JwtFilter 中删除 @NoArgsConstructor (force = true) 或类中的默认构造函数,则会出现编译错误,因为 JwtFilter 类的默认构造函数将保留在 web.xml 在那一行
<filter-class>com.component.JwtFilter</filter-class>
提前致谢!
【问题讨论】:
标签: xml spring filter config javabeans