SpringSecurity:如何在成功通过身份验证后继续将请求转发到RestController?

问题描述 投票:-1回答:1

我正在使用REST API(不是MVC)进行纯后端项目,并希望将SpringSecurity与JWT令牌一起使用来投影这些API。实现很好,并且所有API都已成功地由令牌保护,我可以将带有用户名和密码的JSON字符串发布到“ /login”路径以获取令牌

我的问题是:

  • SpringSecurity将直接在successfulAuthentication()中返回带有令牌的响应,而不是继续转发到RestController(RestController的“ /login”路径没有数据)] >>
  • 我的问题是:

  • 在成功通过身份验证后,我应该怎么做才能使SpringSecurity可以继续将请求转发到RestController的“ /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都得到了成功的保护...

spring-boot authentication spring-security jwt spring-restcontroller
1个回答
0
投票

简单地使用HttpServletResponse的sendRedirect而不是写入响应呢?

© www.soinside.com 2019 - 2024. All rights reserved.