簡體   English   中英

Spring Security登錄無需身份驗證即可重定向到/ j_spring_security_check

[英]Spring Security Login Redirects to /j_spring_security_check Without Authenticating

我目前正在嘗試使簡單的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”。 您應使用以下格式在表單中構造操作網址:

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

因此結果將是:

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

更改問題后更新...

您的身份驗證失敗,將引發Exception或返回null。 像這樣(在DaoAuthenticationProvider內部)檢查對UserDetailsProvider的調用結果,並拋出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,它將打印接收到的異常的完整內容作為參數並將其插入而不是默認值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM