【问题标题】:extract Username from inMemoryAuthentication() -WebSecurityConfigurerAdapter从 inMemoryAuthentication() -WebSecurityConfigurerAdapter 中提取用户名
【发布时间】:2020-04-10 00:40:12
【问题描述】:

我正在使用 SpringBoot 进行一个学校项目,在添加了一些在互联网上看到的安全功能(WebSecurityConfigurerAdapter)之后,我想知道是否有可能提取当前登录用户的用户名,因为我需要他的 id关于控制器的其他方法 为了从数据库中提取一些信息。

我的 SecurityConfig 类看起来像这样

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/*").access("hasRole('USER')")
                .antMatchers("/admin/*").hasRole("ADMIN")
                .and()
                // some more method calls
                .formLogin();
    }


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)      throws Exception {

        auth.inMemoryAuthentication().withUser("flaviu")
                .password("yes").roles("USER");
    }

    @SuppressWarnings("deprecation")
    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }

}

【问题讨论】:

    标签: java spring-boot spring-security


    【解决方案1】:

    检索当前经过身份验证的主体的最简单方法是通过静态调用 SecurityContextHolder:

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String currentUserName = authentication.getName();
    

    在控制器中获取用户:

    @Controller
    public class SecurityController {
    
        @RequestMapping(value = "/username", method = RequestMethod.GET)
        @ResponseBody
        public String currentUserName(Principal principal) {
            return principal.getName();
        }
    }
    

    我们也可以使用认证令牌:

    @Controller
    public class SecurityController {
    
        @RequestMapping(value = "/username", method = RequestMethod.GET)
        @ResponseBody
        public String currentUserName(Authentication authentication) {
            return authentication.getName();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      相关资源
      最近更新 更多