spring-security:HTTP状态405 - 不支持请求方法“POST”

时间:2016-12-16 18:44:01

标签: spring spring-mvc spring-security

我在这里检查了很多答案,但似乎对我没什么用。我有弹簧mvc的春天安全。当我的用户尝试注册时,我将发布数据发送到我的控制器。但它给了我405不支持的帖子我在安全配置中禁用了csrf令牌。请让我知道我哪里出错了? 这是我的webSecurityConfigureDapter:

package org.pkb.springlogin.config;

import org.pkb.springlogin.authentication.MyDBAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
// @EnableWebSecurity = @EnableWebMVCSecurity + Extra features
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    MyDBAuthenticationService myDBAauthenticationService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        // Users in memory.

        auth.inMemoryAuthentication().withUser("user1").password("12345").roles("USER");
        auth.inMemoryAuthentication().withUser("admin1").password("12345").roles("USER, ADMIN");

        // For User in database.
        auth.userDetailsService(myDBAauthenticationService);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable();

        // The pages does not require login
        http.authorizeRequests().antMatchers("/", "/welcome", "/login", "/logout","/signUp").permitAll();

        // /userInfo page requires login as USER or ADMIN.
        // If no login, it will redirect to /login page.
        http.authorizeRequests().antMatchers("/userInfo").access("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')");

        // For ADMIN only.
        http.authorizeRequests().antMatchers("/admin").access("hasRole('ROLE_ADMIN')");

        // When the user has logged in as XX.
        // But access a page that requires role YY,
        // AccessDeniedException will throw.
        http.authorizeRequests().and().exceptionHandling().accessDeniedPage("/403");

        // Config for Login Form
        http.authorizeRequests().and().formLogin()//
                // Submit URL of login page.
                .loginProcessingUrl("/j_spring_security_check") // Submit URL
                .loginPage("/login")//

                .defaultSuccessUrl("/userInfo")//
                .failureUrl("/login?error=true")//
                .usernameParameter("username")//
                .passwordParameter("password")
                // Config for Logout Page
                .and().logout().logoutUrl("/logout").logoutSuccessUrl("/logoutSuccessful");

    }
}

这是我的注册页面

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ page isELIgnored="false"%>

<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<html lang="en">

<head>
<link rel="stylesheet" href="<c:url value="/resources/css/bootstrap-theme.min.css"/>">
<link rel="stylesheet" href="<c:url value="/resources/css/bootstrap.min.css"/>">
 <title>Sign Up Form</title>
    <meta http-equiv="Content-Type" content="text/html charset=UTF-8" />
</head>
<body>
<div class="jumbotron page-header">
<h2>Login</h2>
</div>

<form:form class="form-horizontal" method="post"
         name="userReg"  id="userReg"     modelAttribute="userForm" action="${contextPath}/login">


 <div class="container">
 <label class="col-sm-2 control-label">Name</label>
 <div class="col-sm-4">
 <input  name="userName" type="text"   class="form-control" id="userName" placeholder="Name" />
 </div>
</div>
      <br>         
 <div class="container">
<label class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input name="email" class="form-control" id="email" placeholder="Email" />
</div>
 </div>
<br>
<div class="container">
<label class="col-sm-2 control-label">Date of Birth(dd-mm-yyyy)</label>
<div class="col-sm-4">
<input name="dob"  type="text" class="form-control" id="dob" placeholder="Date of birth" />
</div>
</div>

<br>
<div class="container">
<label class="col-sm-2 control-label">Password</label>
<div class="col-sm-4">
<input name="password"  type="password" class="form-control" id="password" placeholder="password" />
</div>
</div>
<br>
<div class="container">
<label class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-4">
<input name="confirmPassword"  type="password" class="form-control" id="cpassword" placeholder="confirm password" />
<span id='message'></span>
</div>
</div>
<br>
<div class="container">
<label class="col-sm-2 control-label">User type</label>
<div class="col-sm-4">
<select class="form-control" name="type" >
<option selected="selected">--select--</option>
 <option  value="user" >User</option>
 <option value="admin">Admin</option>

</select>
</div>
</div>
<br>
<br>
<div class="col-md-6 center-block">

<input type="submit" class="btn-lg btn-primary center-block" value="save">
</div>
 </form:form>
</body>
 <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 <script src="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>
 <script src="<c:url value="/resources/js/form-validation.js"/>"></script>
 <script src="<c:url value="/resources/js/passwordVerification.js"/>"></script> 
</html>

这是我的MainController

package org.pkb.springlogin.controller;

import java.security.Principal;

import org.pkb.springlogin.manager.SignUpHandler;
import org.pkb.springlogin.model.SignUpInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;



@Controller
public class MainController {
    @Autowired
    SignUpHandler signupHandler;
    private static final Logger logger =LoggerFactory.getLogger(MainController.class);
   @RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET)
   public String welcomePage(Model model) {
       model.addAttribute("title", "Welcome");
       model.addAttribute("message", "Hello friend!");
       return "welcomePage";
   }

   @RequestMapping(value = "/admin", method = RequestMethod.GET)
   public String adminPage(Model model) {
       return "adminPage";
   }

   @RequestMapping(value="/signUp",method=RequestMethod.POST)
   public String userLogin(@ModelAttribute("userForm") SignUpInfo user,ModelMap model){
    System.out.println(user);
    Integer id=signupHandler.process(user);
    if(id!=null){
        logger.debug("ID in controller:"+id);
                return "success";
    }
    logger.error("error in controller");
    return "Failure";
   }

   @RequestMapping(value="/signUp",method=RequestMethod.GET)
   public String register(Model model){
    SignUpInfo user=new SignUpInfo();
    model.addAttribute("userForm", user);
    return "signUp";
   }
   @RequestMapping(value = "/login", method = RequestMethod.GET)
   public String loginPage(Model model ) {

       return "loginPage";
   }

   @RequestMapping(value = "/logoutSuccessful", method = RequestMethod.GET)
   public String logoutSuccessfulPage(Model model) {
       model.addAttribute("title", "Logout");
       return "logoutSuccessfulPage";
   }

   @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
   public String userInfo(Model model, Principal principal) {

       // After user login successfully.
       String userName = principal.getName();

       System.out.println("User Name: "+ userName);

       return "userInfoPage";
   }

   @RequestMapping(value = "/403", method = RequestMethod.GET)
   public String accessDenied(Model model, Principal principal) {

       if (principal != null) {
           model.addAttribute("message", "Hi " + principal.getName()
                   + "<br> You do not have permission to access this page!");
       } else {
           model.addAttribute("msg",
                   "You do not have permission to access this page!");
       }
       return "403Page";
   }
}

这是我的signUpInfo

package org.pkb.springlogin.model;

public class SignUpInfo {
private String userName;
private String password;
private String confirmPassword;
private Type type;
private Byte enabled;

public Byte getEnabled() {
    return enabled;
}
public void setEnabled(Byte enabled) {
    this.enabled = enabled;
}
public String getUserName() {
    return userName;
}
public void setUserName(String userName) {
    this.userName = userName;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
public String getConfirmPassword() {
    return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
    this.confirmPassword = confirmPassword;
}
public Type getType() {
    return type;
}
public void setType(Type type) {
    this.type = type;
}
@Override
public String toString() {
    return "SignUpInfo [userName=" + userName + ", password=" + password + ", confirmPassword=" + confirmPassword
            + ", type=" + type + "]";
}

}

1 个答案:

答案 0 :(得分:1)

表格张贴到/login

  action="${contextPath}/login"

但注释login仅支持GET

  @RequestMapping(value = "/login", method = RequestMethod.GET)
  public String loginPage(Model model ) {
   return "loginPage";
  }

也许你应该发帖到/signUp