В предыдущем посте мы реализовали защиту на основе схем таблиц по умолчанию, которые Spring Security выдает.
Учитывая пользователей и роли, разработчики приложений используют схему, которая соответствует их потребностям. Spring дает нам возможность указать запросы, необходимые для получения такой информации, как имя пользователя, пароль и роли.
Наши пользовательские таблицы будут сильно отличаться от таблиц первого примера.
|
1
2
3
4
5
6
7
|
drop table if exists Custom_Users;create table Custom_Users(id bigint auto_increment, username varchar(255), password varchar(255));insert into Custom_Users(username,password) values('TestUser','TestPass');drop table if exists Custom_Roles;create table Custom_Roles(username varchar(255),authority varchar(255), UNIQUE(username,authority));insert into Custom_Roles(username,authority) values('TestUser','superadmin'); |
Чтобы использовать эти таблицы с пружинной защитой, мы должны передать запросы, которые будет использовать пружинная защита, чтобы получить необходимую информацию о безопасности.
Для этого мы создадим конфигурацию безопасности, которая настроит необходимые запросы.
|
01
02
03
04
05
06
07
08
09
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
|
package com.gkatzioura.spring.security.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Profile;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import javax.sql.DataSource;/** * Created by gkatzioura on 9/20/16. */@EnableWebSecurity@Profile("customquery")public class CustomQuerySecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Autowired public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication().dataSource(dataSource) .usersByUsernameQuery("SELECT username,password,1 FROM Custom_Users where username=?") .authoritiesByUsernameQuery("SELECT username,authority FROM Custom_Roles where username=?"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/public").permitAll() .anyRequest().authenticated() .and() .formLogin() .permitAll() .and() .logout() .permitAll(); }} |
Мы используем пружинные профили. Наш весенний профиль будет «customquery», поэтому CustomQuerySecurityConfig будет привязан к профилю «customquery».
Для удобства работы по соображениям удобства нам необходимо изменить профиль по умолчанию в нашем файле build.gradle.
|
01
02
03
04
05
06
07
08
09
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
|
group 'com.gkatzioura'version '1.0-SNAPSHOT'buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE") }}apply plugin: 'java'apply plugin: 'idea'apply plugin: 'spring-boot'sourceCompatibility = 1.8repositories { mavenCentral()}dependencies { compile("org.springframework.boot:spring-boot-starter-web") compile("org.thymeleaf:thymeleaf-spring4") compile("org.springframework.boot:spring-boot-starter-security") compile("org.springframework:spring-jdbc") compile("com.h2database:h2:1.4.192") compile("org.slf4j:slf4j-api:1.6.6") compile("ch.qos.logback:logback-core:1.1.7") compile("ch.qos.logback:logback-classic:1.1.7") testCompile "junit:junit:4.11"}bootRun { systemProperty "spring.profiles.active", "customquery"} |
Чтобы запустить проблему приложения
|
1
|
gradle bootRun |
Вы можете найти исходный код на GitHub
| Ссылка: | Spring boot с Spring Security и jdbc Part 2 от нашего партнера JCG Эммануила Гкациоураса в блоге gkatzioura . |