java - Spring Security登录重定向到/j_spring_security_check而不进行身份验证

标签 java spring spring-mvc spring-security

我目前正在尝试让一个简单的 Spring 安全登录工作。我正在使用 mongodb 并且可以将用户保存到数据库中(可以从 mongo shell 查询它们)。但是,当我在登录表单中输入凭据时,我被重定向到/j_spring_security_check 并且我不确定是否正在尝试进行身份验证。这是我尝试登录后的控制台输出:

11:19:10.625 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 1 of 9 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
11:19:10.625 [tomcat-http--7] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT
11:19:10.625 [tomcat-http--7] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@54c21095. A new one will be created.
11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 2 of 9 in additional filter chain; firing Filter: 'LogoutFilter'
11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 3 of 9 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 4 of 9 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
11:19:10.626 [tomcat-http--7] DEBUG o.s.s.w.s.DefaultSavedRequest - pathInfo: both null (property equals)
11:19:10.626 [tomcat-http--7] DEBUG o.s.s.w.s.DefaultSavedRequest - queryString: both null (property equals)
11:19:10.626 [tomcat-http--7] DEBUG o.s.s.w.s.DefaultSavedRequest - requestURI: arg1=/api/accounts/admin; arg2=/api/accounts/j_spring_security_check (property not equals)
11:19:10.626 [tomcat-http--7] DEBUG o.s.s.w.s.HttpSessionRequestCache - saved request doesn't match
11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 5 of 9 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 6 of 9 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
11:19:10.626 [tomcat-http--7] DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@90572420: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@255f8: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: 897C850D53E8B5AEC983E6060077E3F0; Granted Authorities: ROLE_ANONYMOUS'
11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 7 of 9 in additional filter chain; firing Filter: 'SessionManagementFilter'
11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 8 of 9 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check at position 9 of 9 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
11:19:10.626 [tomcat-http--7] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/api/accounts/j_spring_security_check'; against '/api/accounts/login'
11:19:10.626 [tomcat-http--7] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/api/accounts/j_spring_security_check'; against '/api/accounts/logout'
11:19:10.626 [tomcat-http--7] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/api/accounts/j_spring_security_check'; against '/api/accounts/accessdenied'
11:19:10.626 [tomcat-http--7] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/api/accounts/j_spring_security_check'; against '/api/accounts/admin'
11:19:10.626 [tomcat-http--7] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Public object - authentication not attempted
11:19:10.626 [tomcat-http--7] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/j_spring_security_check reached end of additional filter chain; proceeding with original chain
11:19:10.626 [tomcat-http--7] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'appServlet' processing POST request for [/hdft-rest-api/api/accounts/j_spring_security_check]
11:19:10.627 [tomcat-http--7] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /api/accounts/j_spring_security_check
11:19:10.641 [tomcat-http--7] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Did not find handler method for [/api/accounts/j_spring_security_check]
11:19:10.641 [tomcat-http--7] DEBUG o.s.w.s.h.SimpleUrlHandlerMapping - Matching patterns for request [/api/accounts/j_spring_security_check] are [/**]
11:19:10.641 [tomcat-http--7] DEBUG o.s.w.s.h.SimpleUrlHandlerMapping - URI Template variables for request [/api/accounts/j_spring_security_check] are {}
11:19:10.641 [tomcat-http--7] DEBUG o.s.w.s.h.SimpleUrlHandlerMapping - Mapping [/api/accounts/j_spring_security_check] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler@29ab0eef] and 1 interceptor
11:19:10.641 [tomcat-http--7] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
11:19:10.641 [tomcat-http--7] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
11:19:10.641 [tomcat-http--7] DEBUG o.s.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'appServlet': assuming HandlerAdapter completed request handling
11:19:10.641 [tomcat-http--7] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request
11:19:10.641 [tomcat-http--7] DEBUG o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally
11:19:10.641 [tomcat-http--7] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed

我已附上相关配置文件:

这是我的 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.1.xsd">

<global-method-security pre-post-annotations="enabled" secured-annotations="enabled" />

<http auto-config="false"  use-expressions="true" access-denied-page="/api/accounts/accessdenied">
    <intercept-url pattern="/api/accounts/login" access="permitAll" />
    <intercept-url pattern="/api/accounts/logout" access="permitAll" />
    <intercept-url pattern="/api/accounts/accessdenied" access="permitAll" />
    <intercept-url pattern="/api/accounts/admin" access="hasRole('ROLE_ADMIN')" />

    <form-login login-page="/api/accounts/login" default-target-url="/api/accounts/welcome" authentication-failure-url="/api/accounts/accessdenied"  />
    <logout logout-success-url="/api/accounts/logout" />
</http>

<beans:bean id="mongoUserDetailsService" class="com.services.impl.MongoUserDetailsService" />

<authentication-manager alias="authenticationManager">
    <authentication-provider user-service-ref="mongoUserDetailsService">
        <password-encoder hash="plaintext" />
    </authentication-provider>
</authentication-manager>

MongoUserDetailsS​​ervice.java:

@Component
public class MongoUserDetailsService implements UserDetailsService {

@Resource
private UserRepository urepo;

private org.springframework.security.core.userdetails.User userdetails;

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    boolean enabled = true;
    boolean accountNonExpired = true;
    boolean credentialsNonExpired = true;
    boolean accountNonLocked = true;
    com.DTOs.users.User user = urepo.findByUsername(username);

    userdetails = new User(user.getUsername(), 
                           user.getPassword(),
                           enabled,
                           accountNonExpired,
                           credentialsNonExpired,
                           accountNonLocked,
                           getAuthorities(user.getRole()));

    return userdetails;
}

public List<GrantedAuthority> getAuthorities(Integer role) {
    List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
    if (role.intValue() == 1) {
        authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

    } else if (role.intValue() == 2) {
        authList.add(new SimpleGrantedAuthority("ROLE_USER"));
    }
    System.out.println(authList);
    return authList;
}

User.java POJO:

@Document
public class User {

@Id
private String id;
private String firstName;
private String lastName;
private String username;
private int role;
private String password;

public User(String id, String firstName, String lastName, String username, int role, String password) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.username = username;
    this.role = role;
    this.password = password
}

// setter and getter methods...

最后是我的login.jsp:

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

<html>
    <body>
    <h1 id="banner">Spring 3 security MongoDB Demo</h1>

    <form name="f" action="j_spring_security_check" method="post">
        <label for="username">Username:</label>
        <input id="username" name="j_username"></br>
        <label for="password">Password:</label>
        <input id="password" name="j_password" type='password'></br>
        <input name="submit" type="submit" value="Login"/>
    </form>

</body>

如果您发现我哪里出错了或者需要更多信息,请告诉我。我们将不胜感激。

编辑:

我尝试了下面评论中的建议。它正在尝试身份验证,但身份验证失败。我检查了我的 mongodb,我肯定输入了正确的凭据,所以我不确定我做错了什么。这是新的错误日志:

11:07:28.794 [tomcat-http--12] DEBUG o.s.security.web.FilterChainProxy - /j_spring_security_check at position 1 of 9 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT
11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@7f10f850. A new one will be created.
11:07:28.794 [tomcat-http--12] DEBUG o.s.security.web.FilterChainProxy - /j_spring_security_check at position 2 of 9 in additional filter chain; firing Filter: 'LogoutFilter'
11:07:28.794 [tomcat-http--12] DEBUG o.s.security.web.FilterChainProxy - /j_spring_security_check at position 3 of 9 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Request is to process authentication
11:07:28.794 [tomcat-http--12] DEBUG o.s.s.authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Authentication request failed: org.springframework.security.authentication.AuthenticationServiceException
11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Updated SecurityContextHolder to contain null Authentication
11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Delegating to authentication failure handler org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler@52e16021
11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.a.SimpleUrlAuthenticationFailureHandler - Redirecting to /api/accounts/accessdenied
11:07:28.794 [tomcat-http--12] DEBUG o.s.s.web.DefaultRedirectStrategy - Redirecting to '/hdft-rest-api/api/accounts/accessdenied'
11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
11:07:28.794 [tomcat-http--12] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
11:07:28.796 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 1 of 9 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
11:07:28.796 [tomcat-http--13] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT
11:07:28.796 [tomcat-http--13] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@7f10f850. A new one will be created.
11:07:28.796 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 2 of 9 in additional filter chain; firing Filter: 'LogoutFilter'
11:07:28.796 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 3 of 9 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
11:07:28.796 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 4 of 9 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
11:07:28.796 [tomcat-http--13] DEBUG o.s.s.w.s.DefaultSavedRequest - pathInfo: both null (property equals)
11:07:28.796 [tomcat-http--13] DEBUG o.s.s.w.s.DefaultSavedRequest - queryString: both null (property equals)
11:07:28.796 [tomcat-http--13] DEBUG o.s.s.w.s.DefaultSavedRequest - requestURI: arg1=/hdft-rest-api/api/accounts/admin; arg2=/hdft-rest-api/api/accounts/accessdenied (property not equals)
11:07:28.796 [tomcat-http--13] DEBUG o.s.s.w.s.HttpSessionRequestCache - saved request doesn't match
11:07:28.796 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 5 of 9 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
11:07:28.796 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 6 of 9 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
11:07:28.796 [tomcat-http--13] DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@6faa6108: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff10d0: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: 7A0F91CF4FD4ADA0A192E2EDE53AADB0; Granted Authorities: ROLE_ANONYMOUS'
11:07:28.797 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 7 of 9 in additional filter chain; firing Filter: 'SessionManagementFilter'
11:07:28.797 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 8 of 9 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
11:07:28.797 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied at position 9 of 9 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
11:07:28.797 [tomcat-http--13] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/api/accounts/accessdenied'; against '/api/accounts/login'
11:07:28.797 [tomcat-http--13] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/api/accounts/accessdenied'; against '/api/accounts/logout'
11:07:28.797 [tomcat-http--13] DEBUG o.s.s.web.util.AntPathRequestMatcher - Checking match of request : '/api/accounts/accessdenied'; against '/api/accounts/accessdenied'
11:07:28.797 [tomcat-http--13] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /api/accounts/accessdenied; Attributes: [permitAll]
11:07:28.797 [tomcat-http--13] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@6faa6108: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff10d0: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: 7A0F91CF4FD4ADA0A192E2EDE53AADB0; Granted Authorities: ROLE_ANONYMOUS
11:07:28.797 [tomcat-http--13] DEBUG o.s.s.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@7de6385e, returned: 1
11:07:28.797 [tomcat-http--13] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Authorization successful
11:07:28.797 [tomcat-http--13] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - RunAsManager did not change Authentication object
11:07:28.797 [tomcat-http--13] DEBUG o.s.security.web.FilterChainProxy - /api/accounts/accessdenied reached end of additional filter chain; proceeding with original chain
11:07:28.797 [tomcat-http--13] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'appServlet' processing GET request for [/hdft-rest-api/api/accounts/accessdenied]
11:07:28.797 [tomcat-http--13] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /api/accounts/accessdenied
11:07:28.797 [tomcat-http--13] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Returning handler method [public java.lang.String com.schneiderlab.hdft_mobile.rest_api.UserController.loginerror(org.springframework.ui.ModelMap)]
11:07:28.797 [tomcat-http--13] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'userController'
11:07:28.798 [tomcat-http--13] DEBUG o.s.web.servlet.DispatcherServlet - Last-Modified value for [/hdft-rest-api/api/accounts/accessdenied] is: -1
11:07:28.798 [tomcat-http--13] DEBUG o.s.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'denied'; URL [/WEB-INF/views/denied.jsp]] in DispatcherServlet with name 'appServlet'
11:07:28.798 [tomcat-http--13] DEBUG o.s.web.servlet.view.JstlView - Added model object 'error' of type [java.lang.String] to request in view with name 'denied'
11:07:28.798 [tomcat-http--13] DEBUG o.s.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/views/denied.jsp] in InternalResourceView 'denied'
11:07:28.799 [tomcat-http--13] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
11:07:28.799 [tomcat-http--13] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request
11:07:28.799 [tomcat-http--13] DEBUG o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally
11:07:28.799 [tomcat-http--13] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed

最佳答案

您正在将凭据发布到“/api/accounts/j_spring_security_check”,而受监控的 URL 只是“/j_spring_security_check”。您应该使用以下方式在表单中构建操作 URL:

<c:url value="/j_spring_security_check"/>

所以结果是:

<form name="f" action="<c:url value="/j_spring_security_check"/>" method="post">

问题更改后更新...

您的身份验证失败,抛出异常或返回 null。像这样检查对 UserDetailsProvider 的调用结果(在 DaoAuthenticationProvider 内部),并抛出 AuthenticationServiceException 的结果:

    try {
        loadedUser = this.getUserDetailsService().loadUserByUsername(username);
    } catch (UsernameNotFoundException notFound) {
        throw notFound;
    } catch (Exception repositoryProblem) {
        throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
    }

    if (loadedUser == null) {
        throw new AuthenticationServiceException(
                "UserDetailsService returned null, which is an interface contract violation");
    }

你应该:

  • 改进您的代码以包含一些日志记录
  • 启动调试器并检查代码以查看失败或返回 null 的内容
  • 或者实现一个自定义的 AuthenticationFailureHandler ,它将打印作为参数接收到的异常的完整内容,并将其插入而不是默认的

关于java - Spring Security登录重定向到/j_spring_security_check而不进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24535164/

相关文章:

java - 前台服务意外停止

spring - JpaRepository 删除子元素

java - 在服务类中调用时服务类不更新数据库

java - 我可以验证空数据源/空白 pdf 吗?

java - 幻影断点让我发疯!

java - 通过 <a href> 和 jSTL 标记将参数从 JSTL 传递到 servlet

spring - Grails 3.0.2 无法解析 Controller 中的@Secured 注释

java - Hibernate集合在持久化后为NULL

java - 使用 Spring Security 框架实现安全性的不同方式

java - Spring Boot MVC Controller 是多线程的吗?