嗨,我有一个控制器:-
@CrossOrigin(origins = "http://localhost", maxAge = 3600)
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/login", method = RequestMethod.get)
public String login(@RequestBody User login) throws ServletException{
}
}
,我还有另一个GenericFilterBean
类。这是为了执行一些安全功能,例如验证令牌等。
public class JwtFilter extends GenericFilterBean {
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
final String authHeader = request.getHeader("authorization");
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
chain.doFilter(req, res);
} else {
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
new ModelAndView("user/login");// this way i am trying to call one controller method.
throw new ServletException("Missing or invalid Authorization header"); // this is throws one exception. This is only for the dev purpose.
}else {
final String token = authHeader.substring(7);
try {
final Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
request.setAttribute("claims", claims);
} catch (final SignatureException e) {
throw new ServletException("Invalid token");
}
chain.doFilter(req, res);
}
}
}
}
我的问题来自doFilter
方法,我该如何调用控制器方法login
此new ModelAndView("user/login");
代码无法正常工作。因此,请提出一些方法。
答案 0 :(得分:0)
作为最佳实践,您不应真正将登录放在get请求中。
第二,如果您希望过滤器验证登录名,则可以将其用作中间件/作为方面/或者仅在服务类中编写验证方法并使用它。
如果您确实要通过过滤器调用端点,则可以尝试使用其余模板。
String fooResourceUrl = "http://localhost:8080/user/login";
User userWithLoginCredentials = new User() //Create your user object
HttpEntity<User> request = new HttpEntity<>(userWithLoginCredentials);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Foo> response = restTemplate.exchange(fooResourceUrl, HttpMethod.GET, request, User.class);