简体   繁体   中英

How can I set up JdbcUserDetailsManager to use my table?

I'm learning about Spring Security with JdbcUserDetailsManager and I know that the default name for the MySQL table is users. The problem is that my MySQL table name is user, not users and I don't know how can I set up JdbcUserDetailsManager to work with this table.

So how can I set up this bean?

@Bean
public UserDetailsService userDetailsService() {
    JdbcUserDetailsManager service = new JdbcUserDetailsManager(primaryDataSource());
    return service;
}

And here is my MySQL schema:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `password` char(80) NOT NULL,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;

CREATE TABLE `role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

CREATE TABLE `users_roles` (
  `user_id` int(11) NOT NULL,
  `role_id` int(11) NOT NULL,
  PRIMARY KEY (`user_id`,`role_id`),
  KEY `FK_ROLE_idx` (`role_id`),
  CONSTRAINT `FK_ROLE` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`),
  CONSTRAINT `FK_USER_05` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Any feedback will be apreciated. Thank you very much

JdbcUserDetailsManager is only useful when the role has grouping concept (Think that a role can have many permissions and an user can have many roles. We check if an user is allowed to do something by checking if he has certain permissions).

But based on your DB schema, the role does not such grouping concept. Instead, you should use much simpler JdbcDaoImpl . You have to override the following SQL according to your DB schema:

@Bean
    public UserDetailsService userDetailsService() {
        UserDetailsService service = new JdbcDaoImpl(primaryDataSource());
        service.setUsersByUsernameQuery("select username, password , true from user where username = ? ");
        service.setAuthoritiesByUsernameQuery("select user.username , role.name " 
            + " from users_role "
            + " inner join role on role.id = users_role.role_id "
            + " inner join user on user.id = users_role.user_id " 
            + " where user.username = ?");

        return service;
    }

For details about how to override these SQL, refer to the javadocs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM