我使用 spring 安全登录成功并重定向我的家,但仍然是匿名的

I logged success with spring security and redirect my home but is still anonymous

我的项目是具有 Spring 安全性的 JSF。

我使用 spring 安全登录成功并重定向我的家,但仍然是匿名的。我使用安全标签但不起作用。 我的 class UserDetailsS​​ervice:

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UsuarioDetails usuario = userMapper.findByUsername(username);

     if (Objects.isNull(usuario)) throw new UsernameNotFoundException(username);

     return usuario;    
}

protected void configure(HttpSecurity http) {
    try {
        List<Transacao> transacoes = transacaoDao.findAll();

            http.csrf().disable();
            http.authorizeRequests().antMatchers("/", "/index.xhtml", "/javax.faces.resource/**").permitAll();

                http.authorizeRequests().anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/template/login.xhtml").usernameParameter("username").passwordParameter("password")
                .permitAll()
                .failureUrl("/template/login.jsf?error=true").defaultSuccessUrl("/index.xhtml")
                .and().exceptionHandling().accessDeniedPage("/403.xhtml")
                .and().logout().logoutSuccessUrl("/login.xhtml").invalidateHttpSession(true).deleteCookies("JSESSIONID")
                .and().httpBasic()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);;

            for(Transacao t : transacoes) {
                http.authorizeRequests().antMatchers(t.getUrl()).access(t.getNome());
            }
        }
        catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

我的用户详细信息有用户名、密码和角色。当登录重定向到主页时,在我的控制器中我检查了:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

身份验证是匿名用户。 还有一个用户 um 我的主页标签不显示元素:

 <sec:authorize access="hasRole('PROCESSO')">
    <h:outputLabel value="Show my"></h:outputLabel>
 </sec:authorize>

我认为你应该从你的 HttpSecurity 配置中删除这一行:

and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

您说在登录后重定向时用户变为 anonymusUser,这在您使用 stateless 会话创建策略时是有道理的。

发生的事情是您被登录了,但是当您使用 stateless 时,您在登录过程中获得的授权会在请求结束后立即丢失,因此在处理执行重定向时默认成功 url 处理程序上下文没有找到为此请求保存的任何身份验证(更好的说法是,甚至没有执行会话身份验证的上下文搜索)。

我发现 baeldung.com: Control the Session with Spring Security 中的这篇文章非常有用。

这是其中的一些引述:

2. When Is The Session Created?

We can control exactly when our session gets created and how Spring Security will interact with it:

  • always – a session will always be created if one doesn’t already exist

  • ifRequired – a session will be created only if required (default)

  • never – the framework will never create a session itself but it will use one if it already exists
  • stateless – no session will be created or used by Spring Security

还有这个:

3. Under The Hood

Before executing the Authentication process, Spring Security will run a filter responsible with storing the Security Context between requests – the SecurityContextPersistenceFilter. The context will be stored according to a strategy – HttpSessionSecurityContextRepository by default – which uses the HTTP Session as storage.

For the strict create-session=”stateless” attribute, this strategy will be replaced with another – NullSecurityContextRepository – and no session will be created or used to keep the context.

最后,只是说你不应该使用 stateless 会话创建策略,除非你准备好在每个请求中提供和处理凭据