在这篇文章中,我们将为您详细介绍SpringSecurity-405请求方法'POST'不支持的内容,并且讨论关于springsecuritypost403的相关问题。此外,我们还会涉及一些关于HTT
在这篇文章中,我们将为您详细介绍Spring Security-405请求方法'POST'不支持的内容,并且讨论关于spring security post 403的相关问题。此外,我们还会涉及一些关于HTTP状态405-不支持请求方法“ POST”(Spring MVC)、HTTP状态405-具有Spring Security的Spring MVC不支持请求方法'POST'、java – Spring Boot – 不支持请求方法’POST’、Spring Boot 使用 Spring Security POST 无法访问解决方案的知识,以帮助您更全面地了解这个主题。
本文目录一览:- Spring Security-405请求方法'POST'不支持(spring security post 403)
- HTTP状态405-不支持请求方法“ POST”(Spring MVC)
- HTTP状态405-具有Spring Security的Spring MVC不支持请求方法'POST'
- java – Spring Boot – 不支持请求方法’POST’
- Spring Boot 使用 Spring Security POST 无法访问解决方案
Spring Security-405请求方法'POST'不支持(spring security post 403)
我已经为项目实现了Spring Security,但是尝试登录时状态为405。我已经在中添加了csrf
令牌form
。
这是我发送用户名和密码时遇到的错误: HTTP Status 405 - Request method ''POST'' not supported
spring版本:4.0.2。发布
<div> <c:url var="loginUrl" value="/login" /> <form action="${loginUrl}" method="post"> <c:if test="${param.error != null}"> <div> <p>Invalid username and password.</p> </div> </c:if> <c:if test="${param.logout != null}"> <div> <p>You have been logged out successfully.</p> </div> </c:if> <div> <labelfor="username"> <i></i> </label> <input type="text"id="username" name="clientusername" placeholder="Enter Username" required> </div> <div> <labelfor="password"> <i></i> </label> <input type="password"id="password" name="clientpassword" placeholder="Enter Password" required> </div> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> <div> <input type="submit"value="Log in"> </div> </form></div>
安全配置:
@Configuration@EnableWebSecuritypublic class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired @Qualifier("G2BUserDetailsService") UserDetailsService userDetailsService; @Autowired public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/home").permitAll() .antMatchers("/admin/**").access("hasRole(''ADMIN'')") .and().formLogin().loginPage("/login") .usernameParameter("clientusername").passwordParameter("clientpassword") .and().csrf() .and().exceptionHandling().accessDeniedPage("/Access_Denied");// .and().csrf().disable(); }
控制器:
@RequestMapping(value = "/login", method = RequestMethod.GET)public ModelAndView loginPage() { return new ModelAndView("login");}@RequestMapping(value="/logout", method = RequestMethod.GET)public String logoutPage (HttpServletRequest request, HttpServletResponse response) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null){ new SecurityContextLogoutHandler().logout(request, response, auth); } return "redirect:/login?logout";} @RequestMapping(value = "/Access_Denied", method = RequestMethod.GET) public ModelAndView accessDeniedPage(ModelMap model) { model.addAttribute("user", getPrincipal()); return new ModelAndView("accessDenied"); } @RequestMapping(value = "/admin", method = RequestMethod.GET) public ModelAndView adminPage(ModelMap model) { model.addAttribute("user", getPrincipal()); return new ModelAndView("admin"); } private String getPrincipal(){ String userName = null; Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { userName = ((UserDetails)principal).getUsername(); } else { userName = principal.toString(); } return userName; }
关于此问题的几乎每个主题都说我们需要添加csrf
令牌,但是我已经添加了。我想念什么吗?
答案1
小编典典您可以为一个网址设置两个端点。但是您不能根据需要设置任何请求参数。当我看到您的登录请求映射时,可以这样设置请求方法:
@RequestMapping(value = "/login", method = { RequestMethod.GET, RequestMethod.POST })public ModelAndView loginPage() { return new ModelAndView("login");}
HTTP状态405-不支持请求方法“ POST”(Spring MVC)
如何解决HTTP状态405-不支持请求方法“ POST”(Spring MVC)?
我发现了导致HTTP错误的问题。
在“ setFalse()
保存”按钮触发的函数中,我的代码试图提交包含该按钮的表单。
function setFalse(){
document.getElementById("hasId").value ="false";
document.deliveryForm.submit();
document.submitForm.submit();
当我删除document.submitForm.submit();
它的作品:
function setFalse(){
document.getElementById("hasId").value ="false";
document.deliveryForm.submit()
@RogerLindsjö感谢您发现我没有传递正确参数的错误!
解决方法
我收到此错误: HTTP Status 405 - Request method ''POST'' not supported
我正在尝试做的是创建一个带有下拉框的表单,该表单会根据在另一个下拉框中选择的其他值进行填充。例如,当我在customerName
框中选择一个名称时,onChange
应运行.jsp页面中的函数,然后提交提交的页面,然后在customerCountry
框中再次加载相应的值。
但是我收到此HTTP状态405错误。我在互联网上搜索了解决方案,但找不到任何有帮助的方法。这是我的代码的相关部分:
jsp页面的一部分
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style>
.error { color: red; }
</style>
<script>
function repopulate(){
document.deliveryForm.submit();
}
function setFalse(){
document.getElementById("hasId").value ="false";
document.deliveryForm.submit();
// document.submitForm.submit(); (This was causing the error)
}
</script>
</head>
<body>
<h1>Create New Delivery</h1>
<c:url var="saveUrl" value="/test/delivery/add" />
<form:form modelAttribute="deliveryDtoAttribute" method="POST" action="${saveUrl}" name="deliveryForm">
<table>
<tr>
<td><form:hidden id="hasId" path="hasCustomerName" value="true"/></td>
</tr>
<tr>
<td>Customer Name</td>
<td><form:select path="customerName" onChange="repopulate()">
<form:option value="" label="--- Select ---" />
<form:options items="${customerNameList}" />
</form:select>
</td>
<td><form:errors path="customerName" css/></td>
</tr>
<tr>
<td>Customer Country</td>
<td><form:select path="customerCountry">
<form:option value="" label="--- Select ---" />
<form:options items="${customerCountryList}" />
</form:select>
</td>
<td><form:errors path="customerCountry" css/></td>
</tr>
</form:form>
<form:form name="submitForm">
<input type="button" value="Save" onClick="setFalse()"/>
</form:form>
</body>
</html>
控制器的一部分:
@RequestMapping(value = "/add",method = RequestMethod.GET)
public String getDelivery(ModelMap model) {
DeliveryDto deliveryDto = new DeliveryDto();
model.addAttribute("deliveryDtoAttribute",deliveryDto);
model.addAttribute("customerNameList",customerService.listAllCustomerNames());
model.addAttribute("customerCountryList",customerService
.listAllCustomerCountries(deliveryDto.getCustomerName()));
return "new-delivery";
}
// I want to enter this method if hasId=true which means that a value in the CustomerName
// drop down list was selected. This should set the CountryList to the corresponding values
// from the database. I want this post method to be triggered by the onChange in the jsp page
@RequestMapping(value = "/add",method = RequestMethod.POST,params="hasCustomerName=true")
public String postDelivery(
@ModelAttribute("deliveryDtoAttribute") DeliveryDto deliveryDto,BindingResult result,ModelMap model) {
model.addAttribute("deliveryDtoAttribute",deliveryDto);
model.addAttribute("customerNameList",customerService.listAllCustomerNames());
model.addAttribute("customerCountryList",customerService
.listAllCustomerCountries(deliveryDto.getCustomerName()));
return "new-delivery";
}
// This next post method should only be entered if the save button is hit in the jsp page
@RequestMapping(value = "/add",params="hasCustomerName=false")
public String postDelivery2(
@ModelAttribute("deliveryDtoAttribute") @Valid DeliveryDto deliveryDto,ModelMap model) {
if (result.hasErrors()) {
model.addAttribute("deliveryDtoAttribute",customerService
.listAllCustomerCountries(deliveryDto.getCustomerName()));
return "new-delivery";
} else {
Delivery delivery = new Delivery();
//Setters to set delivery values
return "redirect:/mis/home";
}
}
我怎么会得到这个错误?任何帮助将非常感激!谢谢
编辑: 更改hasId
为hasCustomerName
。我仍然收到HTTP Status 405 - Request method
''POST'' not supported
错误。
EDIT2: 注释掉setFalse
导致错误的函数中的行
// D
HTTP状态405-具有Spring Security的Spring MVC不支持请求方法'POST'
我使用freemarker模板作为视图部分创建了一个Spring mvc应用程序。在此尝试使用表格添加模型。我也在使用spring security这是代码
员工
<fieldset> <legend>Add Employee</legend> <form name="employee" action="addEmployee" method="post"> Firstname: <input type="text" name="name" /> <br/> Employee Code: <input type="text" name="employeeCode" /> <br/> <input type="submit" value=" Save " /> </form>
employeeController.java
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST) public String addEmployee(@ModelAttribute("employee") Employee employee) { employeeService.add(employee); return "employee"; }
web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><!-- Spring MVC --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring/appServlet/servlet-context.xml, /WEB-INF/spring/springsecurity-servlet.xml </param-value> </context-param> <!-- Spring Security --> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>
Spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd"> <http security="none" pattern="/resources/**"/> <!-- enable use-expressions --> <http auto-config="true" use-expressions="true"> <intercept-url pattern="/login" access="isAnonymous()"/> <intercept-url pattern="/**" access="hasRole(''ROLE_ADMIN'')" /> <!-- access denied page --> <access-denied-handler error-page="/403" /> <form-login login-page="/login" default-target-url="/" authentication-failure-url="/login?error" username-parameter="username" password-parameter="password" /> <logout logout-success-url="/login?logout" /> <!-- enable csrf protection --> <csrf /> </http> <authentication-manager> <authentication-provider user-service-ref="userDetailsService" > <password-encoder hash="bcrypt" /> </authentication-provider> </authentication-manager></beans:beans>
单击提交按钮时,将返回错误`
HTTP状态405-不支持请求方法“ POST”
`我在ftl和controller上都给出了POST方法。那为什么会这样呢?
答案1
小编典典我不确定这是否有帮助,但是我遇到了同样的问题。
您正在使用带有CSRF保护的springSecurityFilterChain。这意味着通过POST请求发送表单时必须发送令牌。尝试将下一个输入添加到表单中:
<input type="hidden"name="${_csrf.parameterName}"value="${_csrf.token}"/>
java – Spring Boot – 不支持请求方法’POST’
这是我的控制器:
@RestController public class LoginController { UserWrapper userWrapper = new UserWrapper(); @RequestMapping(value = "/api/login",method = RequestMethod.POST,headers = "Content-type: application/*") public @ResponseBody ResponseEntity getCredentials(@RequestBody UserDTO userDTO) { User user = userWrapper.wrapUser(userDTO); if (userDTO.getpassword().equals(user.getpassword())) { return new ResponseEntity(HttpStatus.OK); } else { return new ResponseEntity(HttpStatus.BAD_REQUEST); } } }
我在localhost发送邮件请求:8080 / api / login但它不起作用.你有什么想法吗?
编辑:
UserDTO:
public class UserDTO implements Serializable { private String email; private String password; //getters and setters
和json我发送:
{ "email":"email@email.com","password":"password" }
解决方法
@Configuration class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); } }
Spring Boot 使用 Spring Security POST 无法访问解决方案
在《Spring Boot 基于 SpringSecurity 设置 swagger2 访问权限》一文中我们集成了 SpringSecurity,但是在使用的过程中发现一个问题,就是 get 请求可以正常访问,而 post 的请求却无法访问。
再三检查了对 url 路径权限的匹配,都没有问题。上篇文章中对应的 SecurityConfig 配置如下:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll();
}
}
api 的 post 请求返回结果信息如下:
{
"timestamp": "2020-03-24T12:44:12.782+0000",
"status": 403,
"error": "Forbidden",
"message": "Forbidden",
"path": "/api/check"
}
也就是说由于权限问题导致请求失败,返回 403 错误。
针对这个问题,最主要的原因是:SpringSecrity 默认开启 CSRF 保护。
CSRF(Cross Site Request Forgery, 跨站域请求伪造)是一种网络的攻击方式。
可以这么理解 CSRF 攻击:攻击者盗用了你的身份,以你的名义发送恶意请求。CSRF 能够做的事情包括:以你名义发送邮件,发消息,盗取你的账号,甚至于购买商品,虚拟货币转账… 造成的问题包括:个人隐私泄露以及财产安全。
那么如何解决呢?方案有两种:
方案一:简单直接,禁用 CSRF。修改之后的代码如下:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll();
}
}
也就是添加了一行 http.csrf ().disable ();。
方案二:重写 CSRF 保护策略。示例代码如下:
import org.springframework.security.web.util.matcher.RequestMatcher;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class CsrfSecurityRequestMatcher implements RequestMatcher {
private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
@Override
public boolean matches(HttpServletRequest request) {
List<String> unExecludeUrls = new ArrayList<>();
//unExecludeUrls.add("/api/test");//(不允许post请求的url路径)此处根据自己的需求做相应的逻辑处理
if (unExecludeUrls != null && unExecludeUrls.size() > 0) {
String servletPath = request.getServletPath();
request.getParameter("");
for (String url : unExecludeUrls) {
if (servletPath.contains(url)) {
return true;
}
}
}
return allowedMethods.matcher(request.getMethod()).matches();
}
}
经过以上两种方案解决之后,错误也就消失了。
原文链接:《Spring Boot 使用 Spring Security POST 无法访问解决方案》
精品 SpringBoot 2.x 视频教程
《Spring Boot 2.x 视频教程全家桶》,精品 Spring Boot 2.x 视频教程,打造一套最全的 Spring Boot 2.x 视频教程。
本文同步分享在 博客 “程序新视界”(CSDN)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与 “OSC 源创计划”,欢迎正在阅读的你也加入,一起分享。
今天的关于Spring Security-405请求方法'POST'不支持和spring security post 403的分享已经结束,谢谢您的关注,如果想了解更多关于HTTP状态405-不支持请求方法“ POST”(Spring MVC)、HTTP状态405-具有Spring Security的Spring MVC不支持请求方法'POST'、java – Spring Boot – 不支持请求方法’POST’、Spring Boot 使用 Spring Security POST 无法访问解决方案的相关知识,请在本站进行查询。
本文标签: