Я пытаюсь передать объект из AJAX в Spring Controller. Я пробовал в основном каждое решение, с которым столкнулся здесь, на SO и множестве других онлайн-ресурсов, но безрезультатно. Я не могу понять, что я делаю неправильно, поэтому я ищу твою помощь. Я работаю над простым интернет-магазином, и все, что я хотел бы сделать на этом этапе, это передать значения логина (имя пользователя и пароль) контроллеру из формы, которая находится в модальном файле html. Вот мой код: LoginCredentials.java

public class LoginCredentials { private String username; private String password; // getters and setters } 

Index.html (часть html, в которой удалена большая часть начальной загрузки)

 {amp}lt;div id="loginModal" class="modal fade"{amp}gt; {amp}lt;div class="modal-body"{amp}gt; {amp}lt;form id="loginForm" method="POST"{amp}gt; {amp}lt;input type="text" class="form-control" id="username"{amp}gt; {amp}lt;input type="password" class="form-control" id="password"{amp}gt; {amp}lt;button type="submit"{amp}gt; Login{amp}lt;/button{amp}gt; {amp}lt;/form{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; 

Index.html (часть скрипта)

 {amp}lt;script{amp}gt; $(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(); }); }); }); {amp}lt;/script{amp}gt; 

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 …

Изменить №1 — трассировка стека на стороне сервера

 . ____ _ __ _ _ /\ / ___'_ __ _ _(_)_ __ __ _     ( ( )___ | '_ | '_| | '_ / _` |     \/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |___, | / / / / =========|_|==============|___/=/_/_/_/ :: 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:Usersigorvsource-eclipsefish-shop-web-apptargetclasses started by igorv in C:Usersogorodinsource-eclipsefish-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] .sdrcRepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode. 2019-07-25 11:18:08.028 INFO 8124 --- [ restartedMain] .sdrcRepositoryConfigurationDelegate : 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] osbwembedded.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] oacatalina.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 FilesJavajdk1.8.0_201bin;C:WINDOWSSunJavabin;C:WINDOWSsystem32;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 FilesOracleJavajavapath;C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPowerShellv1.0;C:Program FilesJavajdk-10.0.1bin;C:Program FilesJavajre-10.0.1bin;C:Program FilesGradlegradle-4.8.1bin;C:Usersogorodin.m2wrapperdistsapache-maven-3.5.3-bin2c22a6s60afpuloj4v181qvildapache-maven-3.5.3bin;C:WINDOWSSystem32OpenSSH;C:Program FilesTortoiseGitbin;C:Program Files (x86)NVIDIA CorporationPhysXCommon;C:Program FilesNVIDIA CorporationNVIDIA NvDLISR;C:Program Filesdotnet;C:Program FilesMicrosoft SQL Server130ToolsBinn;C:Program Filesnodejs;C:Program FilesMongoDBServer4.0bin;C:Program FilesJavajdk1.8.0_191bin;C:Program FilesJavajdk1.8.0_191lib;C:Program FilesIntelWiFibin;C:Program FilesCommon FilesIntelWirelessCommon;C:Program FilesMavenapache-maven-3.5.4bin;C:UsersogorodinAppDataLocalMicrosoftWindowsApps;C:Program FilesMicrosoft VS Codebin;C:UsersogorodinAppDataRoamingnpm;C:Program FilesIntelWiFibin;C:Program FilesCommon FilesIntelWirelessCommon;C:Usersigorveclipsejee-2018-12eclipse;;.] 2019-07-25 11:18:08.853 INFO 8124 --- [ restartedMain] oaccC[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2019-07-25 11:18:08.854 INFO 8124 --- [ restartedMain] osweb.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] ossweb.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] ossconcurrent.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] osbawsWelcomePageHandlerMapping : Adding welcome page template: index 2019-07-25 11:18:11.723 INFO 8124 --- [ restartedMain] osbaeweb.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator' 2019-07-25 11:18:11.792 INFO 8124 --- [ restartedMain] osbdaOptionalLiveReloadServer : LiveReload server is running on port 35729 2019-07-25 11:18:12.245 INFO 8124 --- [ restartedMain] osbwembedded.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] oaccC[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet' 2019-07-25 11:18:20.339 INFO 8124 --- [-nio-443-exec-4] osweb.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' 2019-07-25 11:18:20.347 INFO 8124 --- [-nio-443-exec-4] osweb.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 

Изменить №2 — 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(); } } 

Если я забыл упомянуть кое-что, что может быть важно для этой проблемы, пожалуйста, попросите дополнительную информацию, и я отредактирую этот пост. Я постарался сделать этот пост максимально коротким. Я благодарю вас за любую помощь. Ура!

Это уже ответили.

TL; DR отключить csrf или включить токен csrf в ваши запросы.

Когда CSRF включить в Spring Security, доступ запрещен 403