我正在使用REST API(不是MVC)进行纯后端项目,并希望将SpringSecurity与JWT令牌一起使用来投影这些API。实现很好,并且所有API都已成功地由令牌保护,我可以将带有用户名和密码的JSON字符串发布到“ /login
”路径以获取令牌
我的问题是:
successfulAuthentication()
中返回带有令牌的响应,而不是继续转发到RestController(RestController的“ /login
”路径没有数据)] >>我的问题是:
/login
”路径,以便我可以对请求和路径中的安全性之外的新建令牌执行其他操作? 感谢任何帮助,谢谢!
我的代码:
@Component public class TokenWebSecurityConfig extends WebSecurityConfigurerAdapter { // ... @Override protected void configure(HttpSecurity http) throws Exception { // ... http.authorizeRequests() .antMatchers("/registry").permitAll() // allow path /registry .antMatchers("/login").permitAll() // allow path /login .antMatchers("/verify").permitAll() // allow path /verify .anyRequest().authenticated(); // ... } } @RestController public class EntranceEndpoint { @RequestMapping(path = "/login", method = RequestMethod.POST) public RestResponse<String> login(LoginMetaInfo login) { System.out.println(login); // no output here when login // some further operations for a successful login, and return a REST response } }
这就是SpringSecurity在成功登录后所做的事情
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
// ...
/**
* on login success
*/
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication auth) throws IOException {
// here build the token and insert into response for commitment
// - the SpringSecurity soon returns the response directly, rather then keep forwarding to RestController
String token = xxxx;
response.setStatus(StatusCode.SUCCESS().getCode());
RestResponse<String> body = RestResponse.succeeded(StatusCode.SUCCESS().withMsg(LoginResponseCode.LOGIN), token);
response.setContentType(MediaType.APPLICATION_JSON);
response.setCharacterEncoding(MediaType.CHARSET);
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getWriter(), body );
}
}
我正在使用REST API(不是MVC)进行纯后端项目,并希望将SpringSecurity与JWT令牌一起使用来投影这些API。实现很好,并且所有API都得到了成功的保护...
简单地使用HttpServletResponse的sendRedirect而不是写入响应呢?