Java 在 REST 服务器的 SecurityContext 中找不到身份验证对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18824458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:24:44  来源:igfitidea点击:

An Authentication object was not found in the SecurityContext in a REST Server

javaspringsecurityrestspring-security

提问by Jorge

I'm a newbie in Spring and Spring Security and I am having this error:

我是 Spring 和 Spring Security 的新手,我遇到了这个错误:

An Authentication object was not found in the SecurityContext

在 SecurityContext 中找不到身份验证对象

A little part of the securityApplicationContext.xml is:

securityApplicationContext.xml 的一小部分是:

<bean id="authenticationProcessingFilter" 
        class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
      <property name="authenticationManager" ref="authenticationManager"/>
</bean>

<security:http auto-config="true"/>

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

<security:authentication-manager alias="authenticationManager">
    <security:authentication-provider user-service-ref="userService">
   </security:authentication-provider>
</security:authentication-manager>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/pfc" />
    <property name="username" value="root" />
    <property name="password" value="" />
</bean>

<security:jdbc-user-service id="userService" data-source-ref="dataSource"
    users-by-username-query=
    "select email as username, claveAcceso as password, true as enabled from usuarios
    join usuarios_privado on usuarios.idUsuario = usuarios_privado.idUsuario
    and email=?"
    authorities-by-username-query=
    "select email as username, rol as authorities from usuarios where email=?"/>

One fragment of the web.xml is:

web.xml 的一个片段是:

[EDIT3]

[编辑3]

<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
   <filter-name>springSecurityFilterChain</filter-name>
   <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/**</url-pattern>
</filter-mapping>

And as I have <security:global-method-security secured-annotations="enabled" />the class UsuarioDAO.java has the annotation @Secured on the method, just like this:

因为我有<security:global-method-security secured-annotations="enabled" />类 UsuarioDAO.java 在方法上有@Secured 注释,就像这样:

@Secured("hasRole('USUARIO')")
@SuppressWarnings("unchecked")
@Transactional
public List<Usuario> list(){
    Session session = sessionFactory.getCurrentSession();
    List<Usuario> usuarios = null;
    try {
        usuarios = (List<Usuario>)session.createQuery("from Usuario").list();
       } catch (HibernateException e) {
           e.printStackTrace();
       }
    return usuarios;
}

[EDIT]

[编辑]

The stacktrace is:

堆栈跟踪是:

sep 17, 2013 12:00:47 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Spring MVC Dispatcher Servlet] in context with path
[/servicio] threw exception [Request processing failed; nested exception is
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An
Authentication object was not found in the SecurityContext] with root cause
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An
Authentication object was not found in the at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:339) at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:198)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:60)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy29.list(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)

[EDIT2]

[编辑2]

POM:

聚甲醛:

<dependencies>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.0-api</artifactId>
        <version>1.0.1.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.0.1.Final</version>
        <scope>provided</scope>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.2.3.Final</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.0.1.Final</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <scope>test</scope>
        <version>3.2.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.8.2</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.codehaus.Hymanson</groupId>
        <artifactId>Hymanson-mapper-asl</artifactId>
        <version>1.9.3</version>
    </dependency>

    <dependency>
        <groupId>org.codehaus.Hymanson</groupId>
        <artifactId>Hymanson-core-asl</artifactId>
        <version>1.9.3</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.6.4</version>
        <scope>provided</scope>
    </dependency>


    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.25</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.2.3.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-c3p0</artifactId>
        <version>4.2.3.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>4.2.3.Final</version>
    </dependency>

    <!-- Test -->

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.1.1</version>
    </dependency>

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20090211</version>
    </dependency>

    <!-- Log -->

    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.3</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.5</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.5</version>
    </dependency>

    <!-- Security -->

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>3.1.4.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>3.1.4.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>3.1.4.RELEASE</version>
    </dependency>

</dependencies>

I'm using the firefox extension "RestClient" to test the api.

我正在使用 Firefox 扩展“RestClient”来测试 api。

I've searched in many web sites, I've tried a lot of things and I haven't been able to fix the error. I hope someone can help me.

我在许多网站上进行了搜索,尝试了很多方法,但都无法修复错误。我希望有一个人可以帮助我。

Thanks in advance.

提前致谢。

回答by Haim Raman

@Secured does not support expressions
Use

@Secured 不支持表达式
使用

@Secured('USUARIO')

You already have

你已经有了

<global-method-security> 

that enables @Secure

启用@Secure

You can switch to springs @PreAuthorize @PreAuthorize("hasRole('USUARIO')") by adding

您可以通过添加切换到弹簧 @PreAuthorize @PreAuthorize("hasRole('USUARIO')")

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

There is a different issue related to mvc controllers if you are using spring mvc. You may need to create an interface for your controllers and place the annotation on the interface

如果您使用的是 spring mvc,则存在与 mvc 控制器相关的不同问题。您可能需要为您的控制器创建一个界面并将注释放在界面上

See the following answer https://stackoverflow.com/a/8571972/1625740

请参阅以下答案 https://stackoverflow.com/a/8571972/1625740

UPDATEI have to admit that I failed to figure out your problem from the stacktrace. As the configuration looks fine, I would suspect the user service. Try replacing the userService with the most basic one provided by spring (comment out your jdbc one)

更新我不得不承认我没能从堆栈跟踪中找出你的问题。由于配置看起来不错,我怀疑用户服务。尝试用 spring 提供的最基本的替换 userService (注释掉你的 jdbc 一个)

<security:authentication-manager alias="authenticationManager">
    <security:authentication-provider>
    <user-service>
     <user authorities="ROLE_USER" name="guest"password="guest"/>
    </user-service>
   </security:authentication-provider>
</security:authentication-manager>

If it works, reevaluate you datasource and sqls. If in this basic configuration the problem will persist I would recheck the classpath for spring-security version and the compatibility with spring and spring mvc.

如果有效,请重新评估您的数据源和 sql。如果在这个基本配置中问题仍然存在,我将重新检查 spring-security 版本的类路径以及与 spring 和 spring mvc 的兼容性。