我可以通过编程方式调用Spring Security “/login”post方法吗?

nbewdwxp  于 2021-09-29  发布在  Java
关注(0)|答案(3)|浏览(329)

我只需要验证一个没有浏览器和html页面的用户。。。其思想是通过编程方式使用post方法调用“/login”路径(这样我就可以在jframe中使用假设的函数login(用户名、密码),但我不知道如何做。在网上我什么也找不到,可能是因为spring security使用的mvc模式,所以这是不可能的,请告诉我。

6ojccjat

6ojccjat1#

是的,这是可能的。默认情况下,spring安全句柄是 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 在这种情况下,不会自动为您添加令牌以及它。记住这一点,您可以在任何地方执行此请求。

emeijp43

emeijp432#

我猜您要做的是验证用户是否存在,或者不使用post请求,而不从html获取详细信息。您不需要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 Security 的更多详细信息,请参阅下面的github项目https://github.com/baeldung/spring-security-registration

7dl7o3gd

7dl7o3gd3#

@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){
    }

相关问题