【问题标题】:getPrincipal() method returns anonymous usergetPrincipal() 方法返回匿名用户
【发布时间】:2016-02-19 23:35:10
【问题描述】:

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

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

当我使用 postman 从 web 服务 get 方法调用此方法时,即使已登录,它也会返回 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>

即使我将这一行 &lt;intercept-url pattern="/*" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"/&gt; 添加到上述配置中,它也会返回匿名用户。

这是我向邮递员请求的网址。

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

【问题讨论】:

    标签: java web-services spring-security roles


    【解决方案1】:

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

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

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

    【讨论】:

    • 即使有这个&lt;intercept-url pattern="/*" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"/&gt; ?
    猜你喜欢
    • 2023-04-03
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 2017-10-17
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    相关资源
    最近更新 更多