使用Spring Security登录时如何从数据库获取用户ID

时间:2019-12-13 10:51:54

标签: spring-boot spring-security

我正在尝试从数据库获取当前登录的用户ID。我使用了用户名,但ID变得更加复杂。我也可以使用用户名获取用户信息,但是当表中存在多个相同的用户名时,这将是不正确的。我的桌子如下图

core_users

username | password |enabled | id
=================================
john     | 12345    | TRUE   | 1
--------------------------------
cris     | ronaldo  | TRUE   | 2

core_authorities

username | authority |
=====================
john     | ROLE_ADMIN|
---------------------
cris     | ROLE_USER |

我要从上面的表中获取ID,并希望使用此ID从表中收集所有相关信息并显示它们。也许我需要创建自己的User类并获取所有属性。任何帮助表示赞赏。

MyController.java

@RequestMapping("/welcome_page")
    public String welcome_page(ModelMap map) {

        String username, author,userPassword;
        List<String> auths = new ArrayList<>();

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        username = ((UserDetails) principal).getUsername();

        auths.add(((UserDetails) principal).getAuthorities().toString());
        System.out.println("Username logged in:" + username + ", with user_id: " + user_id);
        System.out.println("Authority in:" + auths.get(0));


        return "welcome_page";
    }

SecurityConfig.java


@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private DataSource dataSource;

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

        http.authorizeRequests()
        .antMatchers("/resources/**").permitAll()
        .antMatchers("/").hasAnyRole("USER","ADMIN")
        .antMatchers("/submit_info").hasAnyRole( "ADMIN")
        .and().formLogin()
        .loginPage("/login")
        .usernameParameter("username")
        .passwordParameter("password")
        .successForwardUrl("/welcome_page")
        .permitAll()
        .and()
        .logout()
        .permitAll()
        .and()
        .exceptionHandling().accessDeniedPage("/accessDenied");

        http.csrf().disable();
    }


    @Override
    public void configure(WebSecurity web) throws Exception{
        web.ignoring().antMatchers("/resources/**");


    }

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception{
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select username,password, enabled from core_users where username=?")
                .authoritiesByUsernameQuery("select username, authority from core_authorities where username=?");
    }

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


}

0 个答案:

没有答案