在SpringBoot应用程序中登录时出现禁止错误

时间:2018-06-28 07:08:30

标签: spring spring-mvc spring-boot spring-security thymeleaf

我有一个基本的SpringBoot应用程序。使用Spring Initializer,JPA,嵌入式Tomcat,Thymeleaf模板引擎并将其打包为可执行JAR文件。 这是我的配置文件:

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

    http
            .authorizeRequests()
            .antMatchers(publicMatchers()).permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin().loginPage("/login").defaultSuccessUrl("/menu/config")
        .failureUrl("/login?error").permitAll()
        .and()
        .logout().permitAll();
}

我的Thymeleaf模板:

 <form id="loginForm" th:action="@{/login}" method="post">

        <div class="row">
            <div class="col-md-6 col-md-offset-3 text-center">
                <div th:if="${param.error}" class="alert alert-danger alert-dismissible" role="alert">
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">x</span>
                    </button>
                    <p th:text="#{login.error.message}" />
                </div>
                <div th:if="${param.logout}" class="alert alert-success alert-dismissible" role="alert">
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">x</span>
                    </button>
                    <p th:text="#{login.logout.success}" />
                </div>
            </div>            
        </div>

        <div class="input_label"><i class="fa fa-user"></i><input type="text" id="usernameId"   name="username" th:attr="placeholder=#{login.user.placeholder}" value="peris" /></div>
        <div class="input_label"><i class="fa fa-key"></i><input type="password" name="password" value="peris"/></div>

        <input type="submit" value="LOGIN" />

         </form>

和我的登录控制器:

@Controller
public class LoginController {

    public static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

    /** The login view name */
    public static final String LOGIN_VIEW_NAME = "login/login";

    @RequestMapping(value={ "/", "/login", "/elCor/login"}, method = {RequestMethod.GET})
    public String login() {     

            LOG.info(serverContextPath + "/" + LOGIN_VIEW_NAME);
            return serverContextPath + "/" + LOGIN_VIEW_NAME;

    }
}

使用浏览器进行一切正常,但使用移动设备登录后,使用浏览器按钮返回,然后尝试再次登录,但出现此错误:

2018-06-28 08:56 [http-nio-5678-exec-2] ERROR c.t.w.c.AppErrorController - getErrorAttributes(request, true) --> {timestamp=Thu Jun 28 08:56:48 CEST 2018, status=403, error=Forbidden, message=Forbidden, path=/elCor/login}   

我在计算机浏览器中发现了相同的问题,但是只有一次,并且无法重现该问题。

1 个答案:

答案 0 :(得分:0)

尝试为登录请求添加csrf令牌。

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