-1

我正在使用SpringBoot 2.4.7并且正在尝试实现 jdbc 身份验证。问题是我无法通过 http 访问后端。我已经阅读了以下配置:

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/login")
        .permitAll()
        .and()
        .formLogin()
        ....

我可以在我的上下文应用程序地址访问默认登录页面。但我想用和参数调用POST登录端点。usernamepassword

我怎样才能做到这一点?

4

1 回答 1

0

如果您尝试通过 REST 端点接收用户凭据并手动验证用户身份,您可以这样做:

@RestController
@RequestMapping("/login")
public class LoginController {
    private final AuthenticationManager authenticationManager;

    // constructor injecting authenticationManager

    @PostMapping
    public void login(@RequestBody UserCredentials credentials) {
        UsernamePasswordAuthenticationToken token
                = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());

        Authentication auth = this.authenticationManager.authenticate(token);

        if (auth != null) {
            SecurityContext context = SecurityContextHolder.createEmptyContext();
            context.setAuthentication(auth);
            SecurityContextHolder.setContext(context);
        }

        throw new SomeException();
    }
}

这样,Filters它将为您处理其余的身份验证步骤。可以研究 Spring Security 文档以获取更多详细信息

如果您想使用默认登录页面生成的端点,您可以按照文档中的步骤提出您自己的请求:

  • 表单应该执行到 /login 的帖子
  • 该表格需要包含一个由 Thymeleaf 自动包含的 CSRF 令牌。
  • 表单应在名为 username 的参数中指定用户名
  • 表单应在名为 password 的参数中指定密码
  • 如果发现HTTP参数错误,说明用户未能提供有效的用户名/密码
  • 如果找到http参数logout,说明用户已经注销成功
于 2021-06-17T14:15:22.207 回答