getPrincipal() 方法 returns 匿名用户

getPrincipal() method returns anonymous user

我正在尝试通过 spring 安全方法获取连接的用户

public static User getConnectedUser() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    User currentUser=auth.getPrincipal();
}

当我使用邮递员从 web 服务 get 方法调用此方法时,它 returns anonymousUser 即使我已登录。 这是我的 spring 安全配置:

<http auto-config="true" use-expressions="true">
    <intercept-url pattern="/app/admin/**" access="hasRole('ROLE_ADMIN')"/>
    <intercept-url pattern="/app/passwordHint*" access="hasAnyRole('ROLE_USER','ROLE_ADMIN','ROLE_ANONYMOUS')"/>
    <intercept-url pattern="/app/requestRecoveryToken*" access="hasAnyRole('ROLE_USER','ROLE_ADMIN','ROLE_ANONYMOUS')" />
    <intercept-url pattern="/app/updatePassword*" access="hasAnyRole('ROLE_USER','ROLE_ADMIN','ROLE_ANONYMOUS')" />
    <intercept-url pattern="/app/signup*" access="hasAnyRole('ROLE_USER','ROLE_ADMIN','ROLE_ANONYMOUS')"/>
    <intercept-url pattern="/app/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"/>
    <form-login login-page="/login" authentication-failure-url="/login?error=true" login-processing-url="/j_security_check"/>
    <remember-me user-service-ref="userDao" key="e37f4b31-0c45-11dd-bd0b-0800200c9a66"/>
    <custom-filter ref="ajaxTimeoutRedirectFilter" after="EXCEPTION_TRANSLATION_FILTER"/>
</http>

即使我将此行 <intercept-url pattern="/*" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"/> 添加到上述配置中,它 returns 匿名用户。

这是我向邮递员请求的 url。

http://localhost:8080/myApp/services/api/seal/

您的 intercept-url 都不匹配,因为您的路径以 services 开头,而不是 app

如果您的上下文根是 myApp,您的配置应该是:

<intercept-url pattern="/services/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"/>