为什么我仍然会收到AuthenticationCredentialsNotFoundException?

时间:2016-01-12 23:00:36

标签: spring spring-security

我以为我有the solution to this但不幸的是问题仍然存在,我不知道还能做些什么。

我所做的是以用户身份登录。我的AuthenticationProvider没有检查任何意味着任何用户此刻可以登录的内容。

问题是,有时登录确实有效。我通过服务器获取请求并加载数据。有时候我需要等一会儿,1或2分钟,突然间我开始收到AuthenticationCredentialsNotFoundException。有时我第一次无法登录。我必须发送另一个请求才能成功登录。

我无法看到一种模式或任何可以引导我找到原因的模式。所以,在这里,我从我的LoginService和我AuthenticationProvider的实现:

开始
public class LoginService {

    private AuthenticationProvider adminAuthenticationProvider;     

    public LoginService(DSLContext ctx, AuthenticationProvider adminAuthenticationProvider) {       
        this.adminAuthenticationProvider = adminAuthenticationProvider;
    }

    @Transactional
    public void login(String userId, String password) {

        CustomUserDetails user = new CustomUserDetails(userId, password, true, true, true, true, new ArrayList<GrantedAuthority>());

        Authentication auth = new UsernamePasswordAuthenticationToken(user, password,
                new ArrayList<GrantedAuthority>());     

        try {
            auth = this.adminAuthenticationProvider.authenticate(auth);
        } catch(BadCredentialsException e) {
            throw e;
        }

        SecurityContextHolder.getContext().setAuthentication(auth);     
    }
}

public class AdminAuthenticationProvider implements AuthenticationProvider {

    private RestaurantAdminRepository restaurantAdminRepository;

    public AdminAuthenticationProvider(DSLContext ctx) {
        this.restaurantAdminRepository = new RestaurantAdminRepository(ctx);
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        CustomUserDetails user = (CustomUserDetails) authentication.getPrincipal();

        List<String> roles = new ArrayList<>();
        roles.add("ROLE_ADMIN");

        Authentication customAuthentication = new CustomUserAuthentication(roles, authentication);
        customAuthentication.setAuthenticated(true);

        return customAuthentication;
    }

    @Override
    public boolean supports(Class<? extends Object> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}

我猜这没什么特别的。我的电话仅由isAuthenticated()

保护
@PreAuthorize("isAuthenticated()")
public List<StoreDTO> getAvailableStores() {        
    // ..
    return result;
}

接下来是调试输出,包括我自己的代码的输出和org.springframework调试级别的TRACE。您可以看到授权成功但在某些请求之后抛出异常。对不起这个大输出。您也可以查看here

[http-bio-8080-exec-2] DEBUG com.mz.server.web.servlet.LoginServletImpl - Login request by userId: sfalk
[http-bio-8080-exec-2] DEBUG com.mz.server.web.service.LoginService - Login for sfalk
[http-bio-8080-exec-2] INFO  com.mz.server.web.auth.AdminAuthenticationProvider - authenticate(), Username: sfalk
[http-bio-8080-exec-2] DEBUG com.mz.server.web.repository.StoreAdminRepository - findByUsername(): sfalk
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:postgresql://localhost:5432/mz_db]
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
[http-bio-8080-exec-2] DEBUG com.mz.server.web.repository.StoreAdminRepository - User found.
[http-bio-8080-exec-2] INFO  com.mz.server.web.repository.StoreAdminRepository - Checking password for sfalk
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:postgresql://localhost:5432/mz_db]
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
[http-bio-8080-exec-2] DEBUG com.mz.server.web.repository.StoreAdminRepository - Password valid.
[http-bio-8080-exec-2] DEBUG com.mz.server.web.auth.CustomUserAuthentication - getPrincipal()
[http-bio-8080-exec-2] DEBUG com.mz.server.web.auth.CustomUserAuthentication - Setting user com.mz.server.web.auth.CustomUserDetails@684666d: Username: sfalk; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities to 'authenticated'.
[http-bio-8080-exec-2] DEBUG com.mz.server.web.service.LoginService - User successfully authenticated [userId=sfalk]
[http-bio-8080-exec-2] DEBUG com.mz.server.web.servlet.StoreServletImpl - Requested available stores.
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Secure object: ReflectiveMethodInvocation: public java.util.List com.mz.server.web.service.StoreService.getAvailableStores(); target is of class [com.mz.server.web.service.StoreService]; Attributes: [[authorize: 'isAuthenticated()', filter: 'null', filterTarget: 'null']]
[http-bio-8080-exec-2] DEBUG com.mz.server.web.auth.CustomUserAuthentication - isAuthenticate(): true
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Previously Authenticated: com.mz.server.web.auth.CustomUserAuthentication@7d055aa6
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter@36d4a51, returned: 1
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Authorization successful
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - RunAsManager did not change Authentication object
[http-bio-8080-exec-2] DEBUG com.mz.server.web.service.StoreService - Trying to get available stores for ..
[http-bio-8080-exec-2] DEBUG com.mz.server.web.auth.CustomUserAuthentication - getPrincipal()
[http-bio-8080-exec-2] DEBUG com.mz.server.web.service.StoreService - sfalk
[http-bio-8080-exec-2] DEBUG com.mz.server.web.repository.StoreAdminRepository - Fetching stores for store_admin_id 1
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:postgresql://localhost:5432/mz_db]
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
[http-bio-8080-exec-2] DEBUG com.mz.server.web.repository.StoreAdminRepository - Stores found..
[http-bio-8080-exec-2] DEBUG com.mz.server.web.servlet.StoreServletImpl - Requesting items for store ..
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Secure object: ReflectiveMethodInvocation: public java.util.Map com.mz.server.web.service.StoreService.getItems(java.lang.Long); target is of class [com.mz.server.web.service.StoreService]; Attributes: [[authorize: 'isAuthenticated()', filter: 'null', filterTarget: 'null']]
[http-bio-8080-exec-2] DEBUG com.mz.server.web.auth.CustomUserAuthentication - isAuthenticate(): true
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Previously Authenticated: com.mz.server.web.auth.CustomUserAuthentication@7d055aa6
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter@36d4a51, returned: 1
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Authorization successful
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - RunAsManager did not change Authentication object
[http-bio-8080-exec-2] DEBUG com.mz.server.web.service.StoreService - Getting items.
[http-bio-8080-exec-2] DEBUG com.mz.server.web.repository.StoreAdminRepository - getItems
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:postgresql://localhost:5432/mz_db]
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
[http-bio-8080-exec-2] DEBUG com.mz.server.web.servlet.StoreServletImpl - Requested  offers from 2016-01-11T00:00:00.278+01:00 to 2016-01-17T00:00:00.278+01:00.
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Secure object: ReflectiveMethodInvocation: public java.util.List com.mz.server.web.service.StoreService.getUpcomingOffersForCalendarWeek(java.lang.Long,java.lang.String,java.lang.String); target is of class [com.mz.server.web.service.StoreService]; Attributes: [[authorize: 'isAuthenticated()', filter: 'null', filterTarget: 'null']]
[http-bio-8080-exec-2] DEBUG com.mz.server.web.auth.CustomUserAuthentication - isAuthenticate(): true
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Previously Authenticated: com.mz.server.web.auth.CustomUserAuthentication@7d055aa6
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter@36d4a51, returned: 1
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Authorization successful
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - RunAsManager did not change Authentication object
[http-bio-8080-exec-2] DEBUG com.mz.server.web.service.StoreService - Getting offers ..
[http-bio-8080-exec-2] DEBUG com.mz.server.web.auth.CustomUserAuthentication - getPrincipal()
[http-bio-8080-exec-1] DEBUG com.mz.server.web.servlet.StoreServletImpl - Requested offers from 2016-01-11T00:00:00.167+01:00 to 2016-01-17T00:00:00.167+01:00.
[http-bio-8080-exec-1] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Secure object: ReflectiveMethodInvocation: public java.util.List com.mz.server.web.service.StoreService.getUpcomingOffersForCalendarWeek(java.lang.Long,java.lang.String,java.lang.String); target is of class [com.mz.server.web.service.StoreService]; Attributes: [[authorize: 'isAuthenticated()', filter: 'null', filterTarget: 'null']]
[http-bio-8080-exec-1] TRACE org.springframework.web.context.support.XmlWebApplicationContext - Publishing event in Root WebApplicationContext: org.springframework.security.access.event.AuthenticationCredentialsNotFoundEvent[source=ReflectiveMethodInvocation: public java.util.List com.mz.server.web.service.StoreService.getUpcomingOffersForCalendarWeek(java.lang.Long,java.lang.String,java.lang.String); target is of class [com.mz.server.web.service.StoreService]]
[http-bio-8080-exec-1] DEBUG com.mz.server.web.auth.CustomHttpSessionListener - AuthenticationCredentialsNotFoundEvent
Jän 12, 2016 11:27:02 PM org.apache.catalina.core.ApplicationContext log
SEVERE: Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.util.List com.mz.shared.web.service.store.StoreServlet.getUpcomingOffersForCalendarWeek(java.lang.Long,java.lang.String,java.lang.String)' threw an unexpected exception: org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:416)
    at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:605)
    at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:333)
    at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:303)
    at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:373)
    at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:378)
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:222)
    at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
    at com.mz.server.web.service.StoreService$$EnhancerBySpringCGLIB$$b5728734.getUpcomingOffersForCalendarWeek(<generated>)
    at com.mz.server.web.servlet.StoreServletImpl.getUpcomingOffersForCalendarWeek(StoreServletImpl.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:587)
    ... 25 more

最后一件事是我的应用程序上下文配置文件。这是我的配置 applicationContext-spring-acl.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:jdbc="http://www.springframework.org/schema/jdbc"

    xmlns:sec="http://www.springframework.org/schema/security"

    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/security 
        http://www.springframework.org/schema/security/spring-security-4.0.xsd
        http://www.springframework.org/schema/jdbc 
        http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd">

    <!-- Imports -->
    <import resource="applicationContext-jooq.xml"/>

    <!-- See 15.3.2 Built-In Expression @http://static.springsource.org/spring-security/site/docs/3.0.x/reference/el-access.html#el-permission-evaluator -->
    <bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
        <!-- To use hasPermission() in expressions, configure a PermissionEvaluator -->
        <property name="permissionEvaluator" ref="permissionEvaluator" />
        <property name="roleHierarchy" ref="roleHierarchy" />
    </bean>

    <bean class="com.mahlzeit.server.web.auth.permission.CustomAclPermissionEvaluator" id="permissionEvaluator">
        <constructor-arg ref="aclService" />
    </bean>

    <!-- Declare an acl service -->
    <bean class="org.springframework.security.acls.jdbc.JdbcMutableAclService"  id="aclService">
        <constructor-arg ref="dataSource" />
        <constructor-arg ref="lookupStrategy" />
        <constructor-arg ref="aclCache" />
    </bean>

    <!-- Declare a lookup strategy -->
    <bean id="lookupStrategy"
        class="org.springframework.security.acls.jdbc.BasicLookupStrategy">
        <constructor-arg ref="dataSource" />
        <constructor-arg ref="aclCache" />
        <constructor-arg ref="aclAuthorizationStrategy" />
        <constructor-arg ref="auditLogger" />
    </bean>

    <!-- Declare an acl cache -->
    <bean id="aclCache" class="org.springframework.security.acls.domain.EhCacheBasedAclCache">
        <constructor-arg>
            <bean class="org.springframework.cache.ehcache.EhCacheFactoryBean">
                <property name="cacheManager">
                    <bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:shared="true"/>
                </property>
                <property name="cacheName" value="aclCache" />
            </bean>
        </constructor-arg>
        <constructor-arg>
            <bean
                class="org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy">
                <constructor-arg>
                    <bean class="org.springframework.security.acls.domain.ConsoleAuditLogger" />
                </constructor-arg>
            </bean>
        </constructor-arg>
        <constructor-arg>
            <bean
                class="org.springframework.security.acls.domain.AclAuthorizationStrategyImpl">
                <constructor-arg>
                    <list>
                        <bean
                            class="org.springframework.security.core.authority.SimpleGrantedAuthority">
                            <constructor-arg value="ROLE_ACL_ADMIN" />
                        </bean>
                    </list>
                </constructor-arg>
            </bean>
        </constructor-arg>      
    </bean>

    <!-- Declare an acl authorization strategy -->
    <bean id="aclAuthorizationStrategy" class="org.springframework.security.acls.domain.AclAuthorizationStrategyImpl">
        <constructor-arg>
            <list>
                <bean
                    class="org.springframework.security.core.authority.SimpleGrantedAuthority">
                    <constructor-arg value="ROLE_ADMIN" />
                </bean>
                <bean
                    class="org.springframework.security.core.authority.SimpleGrantedAuthority">
                    <constructor-arg value="ROLE_ADMIN" />
                </bean>
                <bean
                    class="org.springframework.security.core.authority.SimpleGrantedAuthority">
                    <constructor-arg value="ROLE_ADMIN" />
                </bean>
            </list>
        </constructor-arg>
    </bean>

    <!-- Declare an audit logger -->
    <bean id="auditLogger"
        class="org.springframework.security.acls.domain.ConsoleAuditLogger" />

    <!-- http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/access/hierarchicalroles/RoleHierarchyImpl.html -->
    <bean id="roleHierarchy"
        class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
        <property name="hierarchy">
            <value>
                ROLE_ADMIN > ROLE_USER
                ROLE_USER > ROLE_VISITOR
            </value>
        </property>
    </bean>

    <sec:global-method-security authentication-manager-ref="authenticationManager" pre-post-annotations="enabled">   
        <sec:expression-handler ref="expressionHandler"/>       
    </sec:global-method-security>
</beans>

这是 applicationContext-spring-security.xml

<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

    xmlns:sec="http://www.springframework.org/schema/security"

    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/security 
    http://www.springframework.org/schema/security/spring-security-4.0.xsd"    
    >

    <!-- Imports -->
    <import resource="applicationContext-spring-acl.xml"/>

    <sec:http pattern="/**" auto-config="true" use-expressions="true"/>

    <bean id="httpSessionSecurityContextRepository" class='org.springframework.security.web.context.HttpSessionSecurityContextRepository'>
        <property name='allowSessionCreation' value='false' />
    </bean>

    <bean id="securityContextPersistenceFilter" class="org.springframework.security.web.context.SecurityContextPersistenceFilter">
        <constructor-arg ref="httpSessionSecurityContextRepository" />
    </bean>

    <bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy">
        <constructor-arg>
            <list>
                <sec:filter-chain pattern="/**" filters="securityContextPersistenceFilter" />
            </list>
        </constructor-arg>
    </bean>

    <bean id="authenticationListener" class="com.mahlzeit.server.web.auth.CustomAuthenticationListener"/>

    <bean id="adminAuthenticationProvider" class="com.mahlzeit.server.web.auth.AdminAuthenticationProvider">
        <constructor-arg ref="dslContext" />
    </bean>

    <bean id="userDetailsService" class="com.mahlzeit.server.web.service.CustomUserDetailsService"/>

    <sec:authentication-manager alias="authenticationManager">
        <sec:authentication-provider ref="adminAuthenticationProvider"/>
    </sec:authentication-manager>

</beans>

感谢您提供任何有助于此的帮助。

2 个答案:

答案 0 :(得分:0)

在我看来,SecurityContextPersistenceFilter并不是围绕您的请求执行的。我可以看到它已在applicationContext-spring-security.xml中定义,但是,由于您没有发布web.xml,我只能假设您在{{1}中没有相应的过滤条目使用web.xml作为过滤器类。您可以在DelegatingFilterProxy中定义过滤器,如下所示:

web.xml

请注意,<filter> <filter-name>filterChainProxy</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>filterChainProxy</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 引用名为filter-name的春天上下文中的bean。

来自filterChainProxy javadoc:

  

标准Servlet 2.3过滤器的代理,委托给   Spring管理的bean,它实现了Filter接口。支持a   &#34; targetBeanName&#34;在web.xml中过滤init-param,指定名称   Spring应用程序上下文中的目标bean。

     

web.xml通常包含DelegatingFilterProxy定义   在Spring中对应于bean名称的指定filter-name   根应用程序上下文那么对过滤器代理的所有调用都将是   在Spring上下文中委托给那个bean,这是必需的   实现标准的Servlet 2.3过滤器接口。

我希望这会有所帮助。

答案 1 :(得分:0)

我想知道问题是否与登录方法中的空GrantedAuthority列表有关。 在我的实现中,LocalAuthenticationProvider扩展了AbstractUserDetailsAuthenticationProvider,并在GrantedAuthority列表中添加了来自我的域的用户角色。

    final List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
    for(com.tony.trip.domain.Role role:user.getRoles()){
        auths.add(new SimpleGrantedAuthority(role.getRolename()));
    }

希望这个肝脏