spring - Spring Security不会发布到提供的登录处理URL

标签 spring spring-mvc spring-security spring-boot

出于某些奇怪的原因,我无法点击已注册用于处理登录帖子的 Controller 。我只是被重定向到我的资源文件夹中的这个愚蠢的图像:

https://localhost:8443/images/piggy-bank.jpeg

这是我的 Controller 。
@RequestMapping(value = "/login/process", method = RequestMethod.POST)
public String loginPost(HttpSession session, Authentication authentication) {

    String client_id = (String) session.getAttribute("client_id");

    if (client_id.equals(Constants.TRUSTED_CLIENT)) {

        //TODO:
        /*
         * 1. Generate an access_token
         * 2. Save to database
         * 3. Form redirect url with all necessary tokens
         * 4. Return redirect url string
         */

        return "redirect:" + Constants.REDIRECT_TRUSTED_CLIENT; 

    }

    long userId = AuthenticationUtils.getAuthenticatedUserId(authentication);
    return "/user/" + userId;
}

这是我的安全配置:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
                authorizeRequests()
                .antMatchers("/","/sign_up","/resources/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .permitAll()
                .loginPage("/login")
                .loginProcessingUrl("/login/process")
                .defaultSuccessUrl("/")
                .failureUrl("/access_denied")
                .and()
            .csrf()
                .and()
            .exceptionHandling()
                .accessDeniedPage("/access_denied")
                .and()
            .logout()
                .permitAll();

    }
}

这是 View :
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head lang="en">

        <title>Spring App</title>

        <!--/*/ <th:block th:include="fragments/headerinc :: head"></th:block> /*/-->
    </head>

    <body>
        <div class="container">
            <!--/*/ <th:block th:include="fragments/header :: header"></th:block> /*/-->

            <div id="mainWrapper">
                <div class="login-container">
                    <div class="login-card">
                        <div class="login-form">
                            <form th:action="@{/login/process}" method="post" class="form-horizontal">
                                <div th:if="${param.error != null}">
                                    <div class="alert alert-danger">
                                        <p>Invalid username and password.</p>
                                    </div>
                                </div>
                                <div th:if="${param.logout != null}">
                                    <div class="alert alert-success">
                                        <p>You have been logged out successfully.</p>
                                    </div>
                                </div>
                                <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="username" placeholder="Enter Username" />
                                </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="password" placeholder="Enter Password" />
                                </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>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

检查我的网络数据,我发现到/login/process的表单发布成功,并且服务器响应良好!
Request URL:https://localhost:8443/login/process
Request Method:POST
Status Code:302 Found
Remote Address:[::1]:8443

Spring 启动期间的日志还确认将URL“/login/post”注册到上述 Controller 。对应的日志:
2016-04-21 20:44:30.725  INFO 25290 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login/process],methods=[POST]}" onto public java.lang.String com.springapp.controllers.UserController.loginPost(javax.servlet.http.HttpSession,org.springframework.security.core.Authentication)

这种情况可能更加阴险,因为我似乎甚至都无法重定向到defaultSuccessURL页面,即索引(“/”)。即使我使用默认的现成登录 View ,也存在相同的情况(即,loginProcessingURL和defaultSuccessfulURL不重定向)。我的jsp View 有问题吗?我是否缺少一些安全配置?

但是,只要我经过正确的身份验证,手动输入/user/{id}或任何其他URL都会成功将我带到目标URL。这意味着什么?

最后是在我的所有jsp中插入的“header.html”和“headerinc.html”百里香片段:

header.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

    <link href="../../static/css/app.css"
          th:href="@{css/app.css}" rel="stylesheet" media="screen"/>
    <link href="../../static/css/bootstrap.css"
          th:href="@{css/bootstrap.css}" rel="stylesheet" media="screen"/>
    <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css"
          th:href="@{/webjars/font-awesome/4.2.0/font-awesome.css}" rel="stylesheet" media="screen"/>

</head>
<body>

<div class="container">
    <div th:fragment="header">
        <nav class="navbar navbar-default">
            <div class="container-fluid">
                <div class="navbar-header">
                    <a class="navbar-brand" href="#" th:href="@{/}">Home</a>
                    <ul class="nav navbar-nav">
                        <!-- if logged in, then display -logout, else display -login, -Sign up. -->
                        <div th:with="currentUser=${#httpServletRequest.userPrincipal?.name}">

                            <div th:if="${currentUser != null}">
                                <form th:action="@{/logout}" method="post">
                                    <input type="submit" value="Log out"/>
                                </form>
                            </div>

                            <div th:if="${currentUser == null}">
                                <li><a href="#" th:href="@{/login}">Log in</a></li>
                                <li><a href="#" th:href="@{/sign_up}">Sign up</a></li>
                            </div>

                            <!-- This is to simply test some authentication logic-->
                            <a href="#" th:href="@{/users}">All Users</a>
                        </div>
                    </ul>
                </div>
            </div>
        </nav>

        <div class="jumbotron">
            <div class="row text-center">
                <div class="">
                    <h2>Spring Framework Example..</h2>

                    <h3>Spring Boot Web App</h3>
                </div>
            </div>
            <div class="row text-center">
                <img src="../../static/images/NewBannerBOOTS_2.png" width="400"
                     th:src="@{/images/piggy-bank.jpeg}"/>
            </div>
        </div>
    </div>
</div>
</body>
</html>

headerinc.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en" th:fragment="head">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" media="screen" />

    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <link href="../static/css/guru.css"
          th:href="@{/css/guru.css}" rel="stylesheet" media="screen"/>
</head>
<body>

</body>
</html>

最佳答案

这行:

.loginProcessingUrl("/login/process")

告诉Spring Security在发送指定路径时处理提交的凭证,默认情况下,将用户重定向回页面用户来自。它不会将请求传递给Spring MVC和您的 Controller 。

也许您想要的而不是请求映射的是自定义AuthenticationSuccessHandler

关于spring - Spring Security不会发布到提供的登录处理URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36782990/

相关文章:

java - spring mvc 中输入文件的 byte[]

java - Spring boot AuthenticationSuccessHandler 被忽略

java - 出现类似 "java.lang.UnsupportedOperationException: Section 4.4 of the Servlet 3.0 specification does not permit this method to be called"的错误

java - Mysql 和 Spring Boot

java - Spring Roo 项目命令错误

java - 如何使该消息系统按预期工作

java - 让 Spring Boot 重新创建测试数据库

Spring 安全 : Redirect to Login Page in case of 401

java - 我是否需要为具有登录系统的 Web 应用程序实现 OAuth 服务器?

java - Spring-data-mongodb 泛型类型