我可以以编程方式调用 Spring Security "/login" post 方法吗?

问题描述

我只需要在没有浏览器和 html 页面的情况下验证用户... 这个想法是以编程方式使用 post 方法调用“/login”路径(这样我就可以使用假设的 JFrame 中的函数 login(username,password) 但我不知道该怎么做。 网上没查到,可能是spring security使用的MVC模式无法实现,请告知。

解决方法

是的,可以这样做。默认情况下,Spring Security 使用 POST 处理对 /login 端点的 Content-type: application/x-www-form-urlencoded 请求以处理身份验证请求。

使用 HTTPie 的请求示例:

http -f POST http://localhost:8080/login username=user password=password _csrf=your-csrf-token

请记住,您必须发送 CSRF 令牌,并且在这种情况下不会自动为您添加令牌。 考虑到这一点,您可以在任何地方执行此请求。

,

我猜你想要做的是在不从 html 中获取详细信息的情况下使用 Post 请求验证用户是否存在。 您不需要 Post 请求,您可以使用 Spring 提供的 HttpServletRequest。

public void authWithHttpServletRequest(HttpServletRequest request,String username,String password) {
    try {
        request.login(username,password);
    } 
    catch (ServletException e) {
        LOGGER.error("Error while login ",e);
    }
}

有关 Spring 安全性的更多详细信息,请参阅下面的 GitHub 项目 https://github.com/Baeldung/spring-security-registration

,
@GetMapping("/user")
public String user(Principal principal) {
    String username = principal.getName();
    System.out.println("username: " + username);
    return "Hello User";
}

假设这是您要调用的路径,您可以像这样从客户端执行此操作:

    HttpGet request = new HttpGet("http://localhost:8080/user");
    // You can get username and password from a simple form
    String auth = username + ":" + password;
    byte[] encodedAuth = Base64.encodeBase64(
      auth.getBytes(StandardCharsets.ISO_8859_1));
    Utente.updateSettings(CTT.getSede(),new String(encodedAuth),username);
    String authHeader = "Basic " + new String(encodedAuth);
    request.setHeader(HttpHeaders.AUTHORIZATION,authHeader);

    HttpClient client = HttpClientBuilder.create().build();
    HttpResponse response;
    try {
        response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        String serverResponse = EntityUtils.toString(response.getEntity());
        
        if(statusCode == 200) {
            System.out.println("Ok you are in");
        }else {
            throw new StatusCodeException();
        }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }catch (StatusCodeException err){
    }