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

如何使用Spring Security性将对象从AJAX传递到Spring控制器

胥博文
2023-03-14

我正在尝试将对象从AJAX传递给Spring控制器。我基本上尝试了我在SO和大量其他在线资源上遇到的所有解决方案,但都无济于事。我不知道我做错了什么,所以我寻求您的帮助。我正在开发一个简单的网络商店,此时我想做的就是将登录值(用户名和密码)从html文件上的模态表单传递给控制器。这是我的代码:LoginCredentials.java

public class LoginCredentials {

    private String username;
    private String password;
    // getters and setters
}

指数html(删除大部分引导的html部分)

<div id="loginModal" class="modal fade">
    <div class="modal-body">
        <form id="loginForm" method="POST">
            <input type="text" class="form-control" id="username">
            <input type="password" class="form-control" id="password">
            <button type="submit"> Login</button>
        </form>
    </div>
</div>

我ndex.html(剧本部分)

<script>
$(document).ready(function() {
    $('#login').on('click', function() {
        $('#loginModal').modal('toggle');
            $('#loginForm').submit(function(event) {
                var formData = {
                    'username' : $('#username').val(),
                    'password' : $('#password').val()
                };

                var loginUrl = '/login';

                $.ajax({
                    type : 'POST',
                    contentType : "application/json",                       
                    data : JSON.stringify(formData),
                    url : loginUrl,
                    success : function(payload) {
                        console.log('success block');
                        console.log(formData);
                    },
                    error : function(payload) {
                        console.log('this is the URL: ' + loginUrl);
                        console.log('this is the formData: ');
                        console.log(formData);
                        alert('Something went wrong');
                        }
                });
                event.preventDefault();
            });
        });
    });
</script>

LoginController。Java语言

@RequestMapping(value = "/login", method = RequestMethod.POST)
public void login(@RequestBody LoginCredentials credentials) {
    String username = credentials.getUsername();
    String password = credentials.getPassword();
    System.out.println("User: " + username + "\nPass: " + password);
    // logic to access the database
    }

发生的情况是AJAX中的代码总是以错误函数告终。url和JSON值被正确拾取并显示在控制台中。“网络”通知我403错误...

编辑no1-服务器端堆栈跟踪


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.3.RELEASE)

2019-07-25 11:18:07.092  INFO 8124 --- [  restartedMain] org.ogorodin.FishShopWebAppApplication   : Starting FishShopWebAppApplication on DESKTOP-3GFCDON with PID 8124 (C:\Users\igorv\source-eclipse\fish-shop-web-app\target\classes started by igorv in C:\Users\ogorodin\source-eclipse\fish-shop-web-app)
2019-07-25 11:18:07.094  INFO 8124 --- [  restartedMain] org.ogorodin.FishShopWebAppApplication   : No active profile set, falling back to default profiles: default
2019-07-25 11:18:07.129  INFO 8124 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-07-25 11:18:07.129  INFO 8124 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2019-07-25 11:18:07.959  INFO 8124 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-07-25 11:18:08.028  INFO 8124 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 63ms. Found 3 repository interfaces.
2019-07-25 11:18:08.397  INFO 8124 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$809c671f] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-07-25 11:18:08.719  INFO 8124 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 443 (https) 8080 (http)
2019-07-25 11:18:08.749  INFO 8124 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-07-25 11:18:08.750  INFO 8124 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.16]
2019-07-25 11:18:08.756  INFO 8124 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_201\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jdk1.8.0_201/bin/../jre/bin/server;C:/Program Files/Java/jdk1.8.0_201/bin/../jre/bin;C:/Program Files/Java/jdk1.8.0_201/bin/../jre/lib/amd64;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\Java\jdk-10.0.1\bin;C:\Program Files\Java\jre-10.0.1\bin;C:\Program Files\Gradle\gradle-4.8.1\bin;C:\Users\ogorodin\.m2\wrapper\dists\apache-maven-3.5.3-bin\2c22a6s60afpuloj4v181qvild\apache-maven-3.5.3\bin;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\TortoiseGit\bin;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\nodejs\;C:\Program Files\MongoDB\Server\4.0\bin;C:\Program Files\Java\jdk1.8.0_191\bin;C:\Program Files\Java\jdk1.8.0_191\lib;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\Maven\apache-maven-3.5.4\bin;C:\Users\ogorodin\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Microsoft VS Code\bin;C:\Users\ogorodin\AppData\Roaming\npm;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Users\igorv\eclipse\jee-2018-12\eclipse;;.]
2019-07-25 11:18:08.853  INFO 8124 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-07-25 11:18:08.854  INFO 8124 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1725 ms
2019-07-25 11:18:09.294  INFO 8124 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-07-25 11:18:09.667  INFO 8124 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-07-25 11:18:09.715  INFO 8124 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2019-07-25 11:18:09.765  INFO 8124 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.7.Final}
2019-07-25 11:18:09.766  INFO 8124 --- [  restartedMain] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-07-25 11:18:09.885  INFO 8124 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-07-25 11:18:10.009  INFO 8124 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-07-25 11:18:10.592  INFO 8124 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-07-25 11:18:11.066  INFO 8124 --- [  restartedMain] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@48ab7426, org.springframework.security.web.context.SecurityContextPersistenceFilter@7ed4df6f, org.springframework.security.web.header.HeaderWriterFilter@771313fd, org.springframework.security.web.csrf.CsrfFilter@79eb5a49, org.springframework.security.web.authentication.logout.LogoutFilter@6758cf57, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@1712267a, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@b0f5215, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@4e467cdc, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@205da9be, org.springframework.security.web.session.SessionManagementFilter@147b37f, org.springframework.security.web.access.ExceptionTranslationFilter@4b97bdc5, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@42a952fa]
2019-07-25 11:18:11.204  INFO 8124 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-25 11:18:11.455  WARN 8124 --- [  restartedMain] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-07-25 11:18:11.552  INFO 8124 --- [  restartedMain] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page template: index
2019-07-25 11:18:11.723  INFO 8124 --- [  restartedMain] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
2019-07-25 11:18:11.792  INFO 8124 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2019-07-25 11:18:12.245  INFO 8124 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 443 (https) 8080 (http) with context path ''
2019-07-25 11:18:12.247  INFO 8124 --- [  restartedMain] org.ogorodin.FishShopWebAppApplication   : Started FishShopWebAppApplication in 5.395 seconds (JVM running for 6.101)
2019-07-25 11:18:20.338  INFO 8124 --- [-nio-443-exec-4] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-07-25 11:18:20.339  INFO 8124 --- [-nio-443-exec-4] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-07-25 11:18:20.347  INFO 8124 --- [-nio-443-exec-4] o.s.web.servlet.DispatcherServlet        : Completed initialization in 8 ms
Hibernate: SELECT products.id, products.title, products.the_type AS productType,stock.price, stock.quantity FROM products LEFT  JOIN stock ON products.id=stock.product_id

编辑no2-SecurityConfig。Java语言

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserPrincipalDetailsService userPrincipalDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/login/**").permitAll() // this is the line I added
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/api/**").hasRole("ADMIN")
            .antMatchers("/employee/**").hasAnyRole("EMPLOYEE", "ADMIN")
        .and().httpBasic();
    }

    @Bean
    DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        daoAuthenticationProvider.setUserDetailsService(this.userPrincipalDetailsService);
        return daoAuthenticationProvider;       
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

如果我忘记提到对这个问题可能很重要的东西,请询问更多信息,我会编辑这篇文章。我尽量让这篇文章尽可能短。我感谢你的任何帮助。干杯!

共有1个答案

姬衡
2023-03-14

已经回答了。

TL;DR禁用csrf或在您的请求中包含csrf令牌。

当CSRF在Spring Security中启用时,访问被拒绝403

 类似资料:
  • 我的控制器代码: 但不管用。

  • 问题内容: 我想将一个对象传递给控制器​​,并在控制器中检索值。我定义如下: HTML代码: Javascript: 但是我无法在控制器中检索值。它越来越空。 问题答案: 尝试以下操作:-您正在传递对象数组,因此您应该执行HTTPPost而不是HttpGet(这将适用于通过查询字符串发送它的原始类型数组,例如int,strgin等列表)(请记住查询字符串的限制)。尝试使用HTTPPost

  • 问题内容: 我正在使用SpringMVC,我正在将数据从Ajax传递到控制器,但是我在控制器中得到了空值,请检查下面的代码 MyControllerCode 任何人都可以帮助我 问题答案: 嘿享受下面的代码。 Javascript AJAX调用 弹簧控制器代码 以下搜索类如下 该类的优点是,将来可以根据需要向该类添加更多变量。 例如。 如果要实现排序功能。

  • 我想将两个对象从thymeleaf表单传递到控制器。这是我的ThymileAF代码: 在表单中,除了这里实际提交的付款对象之外,我想将学生对象或id传递给我的控制器,因为任何付款都应该对应于特定的学生。我找了很多,直到现在才找到办法。 PaymentController方法,我希望在其中传递对象,因为我使用提交表单,所以无法在th:action中传递变量 请建议。我被困在这里了

  • 如果对象为NULL,则无法传递对象项目。如何将对象从HTML传递给spring控制器?

  • 我需要你的帮助。假设我的JSP中有form:form,表单内部是form:input with date..,如下所示: 在控制器中,我有方法: PersonalTask看起来像: 问题是...如何从JSP传递日期时间并与@ModelAtcm(“个人任务”)个人任务任务绑定??