当前位置: 首页 > 知识库问答 >
问题:

将JSONObject映射到Rest模板以获得spring security中的

充阳秋
2023-03-14

我需要用'username'和'password'json主体向/user/auth发出POST请求,以从spring安全endpoint检索用户身份验证。

我有一个thymeleaf登录表单。它发送'username'和'password'到我的自定义身份验证筛选器endpoint。

正在触发终结点,但它接收的对象为NULL。

我可以使用postman将json主体发送到endpoint,并且可以成功登录,但是当使用thymeleaf表单时,我发送的对象为空。

我曾经尝试过:使用预身份验证endpoint拦截请求,并将thymeleaf对象处理成JSON。不过,我想我没有了解如何使用RestTemplate。



    @PostMapping(value = "/preauth", produces = "application/json")
    @ResponseBody
    public UserDto preAuth(@ModelAttribute LoginRequestModel loginRequestModel) {
        log.info("username to test: {}", loginRequestModel.getUsername());
        log.info("password to test: {}", loginRequestModel.getPassword());
// ^^ these are coming back correct ^^


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", loginRequestModel.getUsername());
        jsonObject.put("password", loginRequestModel.getPassword());

jsonObject.toMap().forEach((s, o) -> System.out.println(s + " : " + o));

// ^^ this also comes back correct ^^
// dont understand how to get this JSONObject inserted into the Rest Template

        RestTemplate restTemplate = new RestTemplate(jsonObject);

        restTemplate.exchange("http://localhost:8080/user/auth", loginRequestModel, LoginRequestModel.class);

        return userInfo;

    }
<form action="#" method="POST" th:action="@{/user/auth/preauth}" th:object="${loginRequestModel}">
    <p>Username: <input th:field="*{username}" type="text"/></p>
    <p>Password: <input th:field="*{password}" type="text"/></p>
    <p><input type="submit" value="Submit"/> <input type="reset" value="Reset"/></p>
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        log.info("attempting to authenticate user");
        try {
            log.info("trying to map object");
            LoginRequestModel creds = new ObjectMapper()
                    .readValue(request.getInputStream(), LoginRequestModel.class);


            return getAuthenticationManager().authenticate(
                    new UsernamePasswordAuthenticationToken(
                            creds.getUsername(),
                            creds.getPassword(),
                            new ArrayList<>()
                    )
            );

        } catch (IOException e) {

            throw new RuntimeException(e);
        }

    }

无论出于什么原因,当我试图在浏览器中直接从thymeleaf表单调用request.getInputStream()时,它返回为null。

[http-nio-8080-exec-3] DEBUG o.s.s.w.FilterChainProxy - /user/auth?username=admin&password=admin at position 5 of 12 in additional filter chain; firing Filter: 'AuthenticationFilter' 
[http-nio-8080-exec-3] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/user/auth'; against '/user/auth' 
[http-nio-8080-exec-3] DEBUG t.j.w.j.a.s.AuthenticationFilter - Request is to process authentication 
[http-nio-8080-exec-3] INFO  t.j.w.j.a.s.AuthenticationFilter - attempting to authenticate user 
[http-nio-8080-exec-3] INFO  t.j.w.j.a.s.AuthenticationFilter - trying to map object 
[http-nio-8080-exec-3] INFO  t.j.w.j.a.s.AuthenticationFilter - the exception was caught! 
[http-nio-8080-exec-3] INFO  t.j.w.j.a.s.AuthenticationFilter - the headers:: 
[http-nio-8080-exec-3] INFO  t.j.w.j.a.s.AuthenticationFilter - null 
[http-nio-8080-exec-3] INFO  t.j.w.j.a.s.AuthenticationFilter - null 
[http-nio-8080-exec-3] DEBUG o.s.s.w.h.w.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@46b257b6 
[http-nio-8080-exec-3] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 
[http-nio-8080-exec-3] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed 
[http-nio-8080-exec-3] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception 
java.lang.RuntimeException: com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input
 at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 1, column: 0]
    at tech.jdevmin.web.jdevminweb.app.security.AuthenticationFilter.attemptAuthentication(AuthenticationFilter.java:72)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:94)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input
 at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 1, column: 0]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59)
    at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4146)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4001)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3071)
    at tech.jdevmin.web.jdevminweb.app.security.AuthenticationFilter.attemptAuthentication(AuthenticationFilter.java:49)
    ... 51 common frames omitted

共有1个答案

庾君博
2023-03-14

我认为在使用UsernamePasswordAuthenticationToken时,您应该获得username密码,如下所示

 @Override
 public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException {
    // TODO Auto-generated method stub
    request.getSession().setMaxInactiveInterval(sessionTimeout);

    CustomUsernamePasswordAuthenticationToken authRequest = getAuthRequest(request);
    _log.info("");
    setDetails(request, authRequest);

    return this.getAuthenticationManager().authenticate(authRequest);
}

    private CustomUsernamePasswordAuthenticationToken getAuthRequest(HttpServletRequest request) {
         String username = obtainUsername(request);
     String password = obtainPassword(request);
    _log.info("UserName IN Filter : "+username);
    _log.info("UserName IN Filter : "+password);

    return new CustomUsernamePasswordAuthenticationToken(username, password);
}
 类似资料:
  • 我有一个RESTAPIendpoint,它将返回一个

  • 我是REST API的新手,我必须映射一个endpoint来返回这个JSON: 我有我的控制器与此调用: 我的服务实现: 现在我有点糊涂了。我创建了OfferMapper来接收来自这个JSON的所有属性,但有些属性将为空。我也不知道创建子对象(OfferRequest请求、OfferResponse响应)是否是映射它的正确方法。 以下是OfferResponse请求和响应: 当我打电话给邮递员时,

  • 问题内容: 我有一个经典的Hibernate 用。工作正常。但是,数据库中大约有500个不同的值,我需要将它们中的大约30个映射到Java类(子类),将其余的映射到父Java类。 可以将问题建模为对Animal类的示例继承。 因此,我在Java代码中使用定义了大约30个Animal的子类。当Hibernate发现鉴别器的未知值时,它将抛出。但是,我需要将这些未知的标识符值映射到一个实体,最好是An

  • 在对这个话题进行了大量的测试和研究之后,我无法完全解决我的问题。我正在springboot应用程序中使用modelmapper进行实体/DTO映射。我正在尝试配置modelmapper,将一个集合映射到一个简单的DTO对象。我已经创建了一个自定义转换器,它正在按预期工作: 我现在的问题是将此转换器应用于所有“集合”= 如果我直接在模型映射器中添加转换器,它就是不工作。 你对此有什么提示或解决办法吗

  • Elasticsearch 是一个 schema-less 的系统,但 schema-less 并不代表 no schema,而是 ES 会尽量根据 JSON 源数据的基础类型猜测你想要的字段类型映射。如果你对这种动态生成的映射关系不满意,或者想要使用一些更高级的映射设置,那么就需要使用自定义映射。 创建和更新映射 正如上面所说,ES 可以随时根据数据中的新字段来创建新的映射关系。所以,我们也可以