Spring Security - 不支持 405 请求方法“POST”

新手上路,请多包涵

我已经在我的项目中实施了 Spring Security,但是当我尝试登录时我的状态为 405。我已经在 — 中添加了 form csrf 标记。

这是我在发送用户名和密码时遇到的错误: HTTP Status 405 - Request method 'POST' not supported

春季版本:4.0.2.RELEASED

 <div class="login-form">
    <c:url var="loginUrl" value="/login" />
    <form action="${loginUrl}" method="post" class="form-horizontal">
        <c:if test="${param.error != null}">
            <div class="alert alert-danger">
                <p>Invalid username and password.</p>
            </div>
        </c:if>
        <c:if test="${param.logout != null}">
            <div class="alert alert-success">
                <p>You have been logged out successfully.</p>
            </div>
        </c:if>
        <div class="input-group input-sm">
            <label class="input-group-addon" for="username">
                <i class="fa fa-user"></i>
            </label>
            <input type="text" class="form-control" id="username"
                name="clientusername" placeholder="Enter Username" required>
        </div>
        <div class="input-group input-sm">
            <label class="input-group-addon" for="password">
                <i class="fa fa-lock"></i>
            </label>
            <input type="password" class="form-control" id="password"
                name="clientpassword" placeholder="Enter Password" required>
        </div>

        <input type="hidden" name="${_csrf.parameterName}"
            value="${_csrf.token}" />

        <div class="form-actions">
            <input type="submit" class="btn btn-block btn-primary btn-default"
                value="Log in">
        </div>
    </form>
</div>

安全配置:

 @Configuration
@EnableWebSecurity
public 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 令牌,但我已经添加了。我错过了什么吗?

原文由 Eniss 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

您可以为一个 url 设置两个端点。但是您不能根据需要设置任何请求参数。当我看到您的登录请求映射时,您可以像这样设置您的请求方法:

 @RequestMapping(value = "/login", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView loginPage() {
    return new ModelAndView("login");
}

原文由 Alican Balik 发布,翻译遵循 CC BY-SA 3.0 许可协议

首先 csrf 在 Spring 4.0 中 默认启用, 因此无需自己显式启用它。

其次,您没有端点来验证您的登录。您正在做的是向 /login 发送请求,它只需要 GET 请求。您可以创建另一个控制器方法来接收 POST 请求和身份验证,或者您可以使用 UserDetailsService

安全配置

protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers("/login-form")
                        .anonymous()
                    .and()
                .formLogin()
                    .loginPage("/user-login")
                    .defaultSuccessUrl("/admin", true) // the second parameter is for enforcing this url always
                    .loginProcessingUrl("/login")
                    .failureUrl("/user-login")
                    .permitAll();
}

@Autowired
private UserDetailsService userDetailsService;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    BCryptPasswordEncoder pe = new  BCryptPasswordEncoder();
    auth.userDetailsService(userDetailsService).passwordEncoder(pe);
}

这里我们的视图页面是 /user-login 处理 url 是 /login 这意味着在你的控制器中你需要删除 /login 的映射并添加以下内容:

控制器

@RequestMapping(value="/user-login", method=RequestMethod.GET)
public ModelAndView loginForm() {
    return new ModelAndView("login-form");
}

并改变你的看法。

查看(登录表单.jsp)

 <c:url value="/login" var="loginUrl"/>
<form action="${loginUrl}" method="post" modelAttribute="user">
    Username: <input type="text" id="username" name="username" placeholder=""><br>
    Password: <input type="password" id="password" name="password" placeholder=""><br>

    <input type="hidden"
    name="${_csrf.parameterName}"
    value="${_csrf.token}"/>
    <button type="submit">Login</button>
</form>

原文由 px06 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题