2014-07-02 4 views
1

J'essaie actuellement d'obtenir une connexion de sécurité Spring simple pour fonctionner. J'utilise mongodb et peut amener les utilisateurs à être enregistrés dans la base de données (peut les interroger à partir de mongo shell). Toutefois, lorsque j'entre les informations d'identification dans le formulaire de connexion, je suis redirigé vers/j_spring_security_check et je ne suis pas sûr si l'authentification est même tentée. Voici la sortie de la console après que je tente de vous connecter:Spring Security Ouverture de session Redirection vers/j_spring_security_check Sans authentification

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: [email protected] 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.AnonymousAuthentica[email protected]: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.sprin[email protected]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.spring[email protected]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 

J'ai joint les fichiers de configuration appropriés:

Voici mon ressort 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> 

MongoUserDetailsService.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... 

Et enfin mon 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> 

S'il vous plaît laissez-moi savoir si vous voyez où je vais mal ou besoin d'informations supplémentaires. Cela serait très appréciable.

Edit:

J'ai essayé la suggestion dans le commentaire ci-dessous. Il tente une authentification, mais l'authentification échoue. J'ai vérifié mon mongodb et je suis en train de saisir correctement les informations d'identification, donc je ne suis pas sûr de ce que je fais mal. Voici le nouveau journal d'erreur:

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: [email protected] 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.se[email protected]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: [email protected] 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.sprin[email protected]6faa6108: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.sprin[email protected]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.sprin[email protected]6faa6108: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.sprin[email protected]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.sp[email protected]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 

Répondre

1

Vous postez vos informations d'identification à «/api/comptes/j_spring_security_check », alors que l'URL surveillée est juste «/j_spring_security_check ». Vous devez construire l'URL d'action sous la forme en utilisant:

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

Ainsi, le résultat serait:

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

Mise à jour après question a été modifiée ...

échoue Votre authentification lancer Exception ou retourner null. Le résultat de l'appel à votre UserDetailsProvider sont vérifiés comme celui-ci (à l'intérieur DaoAuthenticationProvider) avec le résultat de jeter 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"); 
    } 

Vous devez:

  • améliorer votre code pour inclure une journalisation
  • débogueur de démarrage et passez par votre code pour voir ce qui échoue ou renvoie null
  • ou implémenter un AuthenticationFailureHandler personnalisé qui imprimera le contenu complet de l'exception qu'il reçoit en tant que paramètre et p le traîner au lieu de celui par défaut
+0

Merci pour la réponse.Essayé cela et il a tenté l'authentification, mais pour une raison quelconque encore échoué. J'ai posté mon journal d'erreur dans mon édition. – msenevir

+0

Hey @ s3wix Je suggère de donner crédit pour cette réponse - il suffit de cocher la coche verte à gauche de la réponse. – pherris

Questions connexes