从inMemoryAuthentication()中提取用户名 – WebSecurityConfigurerAdapter

huangapple go评论68阅读模式
英文:

extract Username from inMemoryAuthentication() -WebSecurityConfigurerAdapter

问题

我正在进行一个使用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()
                // 其他方法调用
                .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();
    }
}
英文:

I working on a school project with SpringBoot and after adding some security features (WebSecurityConfigurerAdapter) seen on the internet, I would like to know if there is a possibility to extract the username of the current logged in user because I need his id on other methods from controller
in order to extract some information from the database.

My SecurityConfig class look like this

@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();
    }

}

答案1

得分: 3

获取当前已认证的主体最简单的方法是通过静态调用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();
    }
}
英文:

The simplest way to retrieve the currently authenticated principal is via a static call to the SecurityContextHolder:

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

Get the User in a Controller:

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

we can also use the authentication token:

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

huangapple
  • 本文由 发表于 2020年4月10日 00:02:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/61125332.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定