isAnonymous() 和 isAuthenticated() 都返回 false

Posted

技术标签:

【中文标题】isAnonymous() 和 isAuthenticated() 都返回 false【英文标题】:Both isAnonymous() and isAuthenticated() are returning false 【发布时间】:2014-04-28 04:45:40 【问题描述】:

我有一个简单的页面,它根据用户是否登录显示简单的文本。

<sec:authorize access="isAnonymous()">
    No, you failed!
</sec:authorize>
<sec:authorize access="isAuthenticated()">
   yes, logged in. Well done!
</sec:authorize>

上面的代码什么也没显示!这意味着 isAuthenticated() 和 isAnonymous() 都返回了 false。

这里 (Both isAnonymous() and isAuthenticated() return false on error page) 建议我必须使用此配置进行过滤器映射:

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <!-- apply Spring Security authentication to error-pages -->
    <dispatcher>ERROR</dispatcher>
</filter-mapping>

我没有使用 XML,但我的配置是一样的:

EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);
characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");

FilterRegistration.Dynamic security = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());
security.addMappingForUrlPatterns(dispatcherTypes, true, "/*");

为什么会发生这种情况?

编辑: 这是我的安全上下文:

@Configuration
@EnableWebSecurity
public class SecurityContext extends WebSecurityConfigurerAdapter 

@Autowired
private UserRepository userRepository;

@Override
public void configure(WebSecurity web) throws Exception 
    web
            //Spring Security ignores request to static resources such as CSS or JS files.
            .ignoring()
                .antMatchers("/static/**");


@Override
protected void configure(HttpSecurity http) throws Exception 
    http
            //Configures form login
            .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login/authenticate")
                .failureUrl("/login?error=bad_credentials")
            //Configures the logout function
            .and()
                .logout()
                    .deleteCookies("JSESSIONID")
                    .logoutUrl("/logout")
                    .logoutSuccessUrl("/login")
            //Configures url based authorization
            .and()
                .authorizeRequests()
                    //Anyone can access the urls
                    .antMatchers(
                            "/auth/**",
                            "/login",
                            "/signin/**",
                            "/signup/**",
                            "/user/register/**"
                    ).permitAll()
                    //The rest of the our application is protected.
                    .antMatchers("/**").hasRole("USER")
            //Adds the SocialAuthenticationFilter to Spring Security's filter chain.
            .and()
                .apply(new SpringSocialConfigurer());


/**
* Configures the authentication manager bean which processes authentication
* requests.
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception 
    auth
            .userDetailsService(userDetailsService())
            .passwordEncoder(passwordEncoder());


/**
* This is used to hash the password of the user.
*/
@Bean
public PasswordEncoder passwordEncoder() 
    return new BCryptPasswordEncoder(10);


/**
* This bean is used to load the user specific data when social sign in
* is used.
 */
@Bean
public SocialUserDetailsService socialUserDetailsService() 
    return new SimpleSocialUserDetailsService(userDetailsService());


/**
* This bean is load the user specific data when form login is used.
*/
@Bean
public UserDetailsService userDetailsService() 
    return new RepositoryUserDetailsService(userRepository);
 
  

这个页面控制器:

@Controller
public class LoginController 

private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

protected static final String VIEW_NAME_LOGIN_PAGE = "user/login";

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String showLoginPage() 
    LOGGER.debug("Rendering login page.");
    return VIEW_NAME_LOGIN_PAGE;
 

【问题讨论】:

你试过加DispatcherType.ERROR吗? 在阅读您的评论后,我尝试了它,但它没有用。但它是因为它不适用于DispatcherType.ERROR,因为它不是错误页面。 您可能需要发布您的安全配置。您正在查看的页面是否受到过滤器链的保护? @DaveSyer 感谢您的评论。我添加了我的安全上下文。我认为EnumSet&lt;DispatcherType&gt; dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD); characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*"); 中的“/*”保护了我的所有页面是不是错了。 它自己不能保证任何东西都受到保护(我相信)。您需要@EnableWebSecurityWebSecurityConfigurerAdapter 才能完成图片。 【参考方案1】:

ApplicationContext 必须包含

@ComponentScan(basePackages = 
    "com.social.user.detail.service"
)

在这个包中,我的用户类包含以下内容:

public interface UserService 

   public User registerNewUserAccount(RegistrationForm userAccountData) throws DuplicateEmailException;

【讨论】:

【参考方案2】:

确保您没有绕过该 URL 的安全性,如下所示:

<http pattern="/xyz.xx" security="none" />

【讨论】:

以上是关于isAnonymous() 和 isAuthenticated() 都返回 false的主要内容,如果未能解决你的问题,请参考以下文章

sec:authorize 在 thymeleaf 视图中为 isAuthenticated() 和 isAnonymous() 返回 true

sec:authorize 总是在浏览器中为百里香视图中的 isAuthenticated() 和 isAnonymous() 返回相同的视图

Facebook护照身份验证,导出passport.authenticate方法

模块导出,nodejs对于护照身份验证需要太长时间

角色认证和授权

Vue的路由守卫前置和后置