用户登录后如何在控制器中获取会话数据

问题描述 投票:1回答:1

我在WebSecurityConfigurerAdapter Spring Boot应用程序中扩展了MVC。我还创建了以下方法

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
        .antMatchers("/")
        .permitAll()
        .antMatchers("/login")
        .permitAll()
        .antMatchers("/registration")
        .permitAll()
        .antMatchers("/dashboard")
        .hasAuthority("ADMIN")
        .anyRequest()
        .authenticated()
        .and()
        .csrf()
        .disable()
        .formLogin()
        .loginPage("/login")
        .failureUrl("/login?error=true")
        .defaultSuccessUrl("/dashboard")
        .usernameParameter("email")
        .passwordParameter("password")
        .and()
        .logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .logoutSuccessUrl("/home")
        .and()
        .exceptionHandling()
        .accessDeniedPage("/access-denied");
}

用户登录后,我需要在/dashboard控制器中输入用户名,角色,电子邮件等信息。我怎样才能做到这一点?

我试过谷歌搜索,但没有找到任何具体的信息。

java spring-mvc spring-boot spring-security spring-data-jpa
1个回答
2
投票

嗯,你有几个选择:

  1. 您可以调用静态方法SecurityContextHolder.getContext().getAuthentication()(这样您就可以获得遍布应用程序的凭据)
  2. 如果您在控制器中,则可以使用Principle作为参数来获取信息
  3. 如果需要身份验证令牌,可以将Authentication作为参数。

请注意,您必须具有某种机制来对用户进行身份验证(例如,使用active-directory打开openid)并让服务器使用它。

有关更多信息,请参阅http://www.baeldung.com/get-user-in-spring-security

© www.soinside.com 2019 - 2024. All rights reserved.