Configure Users With JdbcUserDetailsManager#
Configure Users With JdbcUserDetailsManager#
- As we learned in the Understanding User Management interfaces and Classes, so we will take an example for using
JdbcUserDetailsManagerto manage our users which are defined in the database.
Dependencies#
- To do this example we will need to add some dependencies as below into
pom.xml
| pom.xml | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
Prepare Tables In Database#
- Then in the database we will create 2 tables named
usersandauthoritieswhich are the same table names and attributes columns as put in queries of the classJdbcUserDetailsManagerin spring security. Let's use the SQL scripts below to create tables and insert a sample user and authority.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
Configure JdbcUserDetailsManager#
- Now, go back to the our spring boot application. We need to add the configuration for
JdbcUserDetailsManager. See the code below
| ProjectSecurityConfig.java | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | |
- We will create a bean
userDetailsServicewhich has the type ofJdbcUserDetailsManager. - Now, let add the datasource configuration in the
application.yml. Then start the application up to test.application.yml 1 2 3 4 5 6 7 8 9 10 11
#spring: # security: # user: # name: user # password: 12345 spring: datasource: url: jdbc:mysql://localhost:3306/worldbank?useUnicode=true&characterEncoding=UTF-8 username: root password: password
Testing#
- You will see that we can call protected api successfully by using the username/password which is defined in the database.
See Also#
- Defining And Managing Users
- Understanding User Management interfaces and Classes
- Custom UserDetailsService Of Spring Security
