Статьи

Spring Security Реализация пользовательских пользовательских деталей с помощью Hibernate

Большую часть времени мы захотим настроить наши собственные роли доступа к безопасности в веб-приложениях. Это легко достигается в Spring Security. В этой статье мы увидим самый простой способ сделать это.

Прежде всего нам понадобятся следующие таблицы в базе данных:

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
CREATE TABLE IF NOT EXISTS `mydb`.`security_role` (
 
`id` INT(11) NOT NULL AUTO_INCREMENT ,
 
`name` VARCHAR(50) NULL DEFAULT NULL ,
 
PRIMARY KEY (`id`) )
 
ENGINE = InnoDB
 
AUTO_INCREMENT = 4
 
DEFAULT CHARACTER SET = latin1;
 
CREATE TABLE IF NOT EXISTS `mydb`.`user` (
 
`id` INT(11) NOT NULL AUTO_INCREMENT ,
 
`first_name` VARCHAR(45) NULL DEFAULT NULL ,
 
`family_name` VARCHAR(45) NULL DEFAULT NULL ,
 
`dob` DATE NULL DEFAULT NULL ,
 
`password` VARCHAR(45) NOT NULL ,
 
`username` VARCHAR(45) NOT NULL ,
 
`confirm_password` VARCHAR(45) NOT NULL ,
 
`active` TINYINT(1) NOT NULL ,
 
PRIMARY KEY (`id`) ,
 
UNIQUE INDEX `username` (`username` ASC) )
 
ENGINE = InnoDB
 
AUTO_INCREMENT = 9
 
DEFAULT CHARACTER SET = latin1;
 
CREATE TABLE IF NOT EXISTS `mydb`.`user_security_role` (
 
`user_id` INT(11) NOT NULL ,
 
`security_role_id` INT(11) NOT NULL ,
 
PRIMARY KEY (`user_id`, `security_role_id`) ,
 
INDEX `security_role_id` (`security_role_id` ASC) ,
 
CONSTRAINT `user_security_role_ibfk_1`
 
FOREIGN KEY (`user_id` )
 
REFERENCES `mydb`.`user` (`id` ),
 
CONSTRAINT `user_security_role_ibfk_2`
 
FOREIGN KEY (`security_role_id` )
 
REFERENCES `mydb`.`security_role` (`id` ))
 
ENGINE = InnoDB
 
DEFAULT CHARACTER SET = latin1;

Очевидно, что пользователь таблицы будет содержать пользователей, таблица security_role будет содержать роли безопасности, а user_security_roles будет содержать ассоциацию. Чтобы реализация была максимально простой, записи в таблице security_role всегда должны начинаться с «ROLE_», в противном случае нам потребуется инкапсулировать (это НЕ будет рассмотрено в этой статье).

Поэтому мы выполняем следующие утверждения:

01
02
03
04
05
06
07
08
09
10
11
insert into security_role(name) values ('ROLE_admin');
 
insert into security_role(name) values ('ROLE_Kennel_Owner');
 
insert into security_role(name) values ('ROLE_User');
 
insert into user (first_name,family_name,password,username,confirm_password,active)
 
values ('ioannis','ntantis','123456','giannisapi','123456',1);
 
insert into user_security_role (user_id,security_role_id) values (1,1);

Итак, после этих команд мы имеем следующее:

Три разные роли безопасности

Один пользователь с именем пользователя «giannisapi»

Мы предоставили роль «ROLE_admin» пользователю «giannisapi».

Теперь, когда все выполнено на стороне базы данных, мы перейдем на сторону Java, чтобы посмотреть, что нужно сделать.

Сначала мы создадим необходимый DTO (есть различные инструменты, которые будут автоматически генерировать DTO из базы данных):

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package org.intan.pedigree.form;
 
import java.io.Serializable;
 
import java.util.Collection;
 
import java.util.Date;
 
import java.util.Set;
 
import javax.persistence.Basic;
 
import javax.persistence.Column;
 
import javax.persistence.Entity;
 
import javax.persistence.GeneratedValue;
 
import javax.persistence.GenerationType;
 
import javax.persistence.Id;
 
import javax.persistence.JoinColumn;
 
import javax.persistence.JoinTable;
 
import javax.persistence.ManyToMany;
 
import javax.persistence.NamedQueries;
 
import javax.persistence.NamedQuery;
 
import javax.persistence.Table;
 
import javax.persistence.Temporal;
 
import javax.persistence.TemporalType;
 
/**
 
*
 
* @author intan
 
*/
 
@Entity
 
@Table(name = 'user', catalog = 'mydb', schema = '')
 
@NamedQueries({
 
@NamedQuery(name = 'UserEntity.findAll', query = 'SELECT u FROM UserEntity u'),
 
@NamedQuery(name = 'UserEntity.findById', query = 'SELECT u FROM UserEntity u WHERE u.id = :id'),
 
@NamedQuery(name = 'UserEntity.findByFirstName', query = 'SELECT u FROM UserEntity u WHERE u.firstName = :firstName'),
 
@NamedQuery(name = 'UserEntity.findByFamilyName', query = 'SELECT u FROM UserEntity u WHERE u.familyName = :familyName'),
 
@NamedQuery(name = 'UserEntity.findByDob', query = 'SELECT u FROM UserEntity u WHERE u.dob = :dob'),
 
@NamedQuery(name = 'UserEntity.findByPassword', query = 'SELECT u FROM UserEntity u WHERE u.password = :password'),
 
@NamedQuery(name = 'UserEntity.findByUsername', query = 'SELECT u FROM UserEntity u WHERE u.username = :username'),
 
@NamedQuery(name = 'UserEntity.findByConfirmPassword', query = 'SELECT u FROM UserEntity u WHERE u.confirmPassword = :confirmPassword'),
 
@NamedQuery(name = 'UserEntity.findByActive', query = 'SELECT u FROM UserEntity u WHERE u.active = :active')})
 
public class UserEntity implements Serializable {
 
private static final long serialVersionUID = 1L;
 
@Id
 
@GeneratedValue(strategy = GenerationType.IDENTITY)
 
@Basic(optional = false)
 
@Column(name = 'id')
 
private Integer id;
 
@Column(name = 'first_name')
 
private String firstName;
 
@Column(name = 'family_name')
 
private String familyName;
 
@Column(name = 'dob')
 
@Temporal(TemporalType.DATE)
 
private Date dob;
 
@Basic(optional = false)
 
@Column(name = 'password')
 
private String password;
 
@Basic(optional = false)
 
@Column(name = 'username')
 
private String username;
 
@Basic(optional = false)
 
@Column(name = 'confirm_password')
 
private String confirmPassword;
 
@Basic(optional = false)
 
@Column(name = 'active')
 
private boolean active;
 
@JoinTable(name = 'user_security_role', joinColumns = {
 
@JoinColumn(name = 'user_id', referencedColumnName = 'id')}, inverseJoinColumns = {
 
@JoinColumn(name = 'security_role_id', referencedColumnName = 'id')})
 
@ManyToMany
 
private Set securityRoleCollection;
 
public UserEntity() {
 
}
 
public UserEntity(Integer id) {
 
this.id = id;
 
}
 
public UserEntity(Integer id, String password, String username, String confirmPassword, boolean active) {
 
this.id = id;
 
this.password = password;
 
this.username = username;
 
this.confirmPassword = confirmPassword;
 
this.active = active;
 
}
 
public Integer getId() {
 
return id;
 
}
 
public void setId(Integer id) {
 
this.id = id;
 
}
 
public String getFirstName() {
 
return firstName;
 
}
 
public void setFirstName(String firstName) {
 
this.firstName = firstName;
 
}
 
public String getFamilyName() {
 
return familyName;
 
}
 
public void setFamilyName(String familyName) {
 
this.familyName = familyName;
 
}
 
public Date getDob() {
 
return dob;
 
}
 
public void setDob(Date dob) {
 
this.dob = dob;
 
}
 
public String getPassword() {
 
return password;
 
}
 
public void setPassword(String password) {
 
this.password = password;
 
}
 
public String getUsername() {
 
return username;
 
}
 
public void setUsername(String username) {
 
this.username = username;
 
}
 
public String getConfirmPassword() {
 
return confirmPassword;
 
}
 
public void setConfirmPassword(String confirmPassword) {
 
this.confirmPassword = confirmPassword;
 
}
 
public boolean getActive() {
 
return active;
 
}
 
public void setActive(boolean active) {
 
this.active = active;
 
}
 
public Set getSecurityRoleCollection() {
 
return securityRoleCollection;
 
}
 
public void setSecurityRoleCollection(Set securityRoleCollection) {
 
this.securityRoleCollection = securityRoleCollection;
 
}
 
@Override
 
public int hashCode() {
 
int hash = 0;
 
hash += (id != null ? id.hashCode() : 0);
 
return hash;
 
}
 
@Override
 
public boolean equals(Object object) {
 
// TODO: Warning - this method won't work in the case the id fields are not set
 
if (!(object instanceof UserEntity)) {
 
return false;
 
}
 
UserEntity other = (UserEntity) object;
 
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
 
return false;
 
}
 
return true;
 
}
 
@Override
 
public String toString() {
 
return 'org.intan.pedigree.form.User[id=' + id + ']';
 
}
 
}
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package org.intan.pedigree.form;
 
import java.io.Serializable;
 
import java.util.Collection;
 
import javax.persistence.Basic;
 
import javax.persistence.Column;
 
import javax.persistence.Entity;
 
import javax.persistence.GeneratedValue;
 
import javax.persistence.GenerationType;
 
import javax.persistence.Id;
 
import javax.persistence.ManyToMany;
 
import javax.persistence.NamedQueries;
 
import javax.persistence.NamedQuery;
 
import javax.persistence.Table;
 
/**
 
*
 
* @author intan
 
*/
 
@Entity
 
@Table(name = 'security_role', catalog = 'mydb', schema = '')
 
@NamedQueries({
 
@NamedQuery(name = 'SecurityRoleEntity.findAll', query = 'SELECT s FROM SecurityRoleEntity s'),
 
@NamedQuery(name = 'SecurityRoleEntity.findById', query = 'SELECT s FROM SecurityRoleEntity s WHERE s.id = :id'),
 
@NamedQuery(name = 'SecurityRoleEntity.findByName', query = 'SELECT s FROM SecurityRoleEntity s WHERE s.name = :name')})
 
public class SecurityRoleEntity implements Serializable {
 
private static final long serialVersionUID = 1L;
 
@Id
 
@GeneratedValue(strategy = GenerationType.IDENTITY)
 
@Basic(optional = false)
 
@Column(name = 'id')
 
private Integer id;
 
@Column(name = 'name')
 
private String name;
 
@ManyToMany(mappedBy = 'securityRoleCollection')
 
private Collection userCollection;
 
public SecurityRoleEntity() {
 
}
 
public SecurityRoleEntity(Integer id) {
 
this.id = id;
 
}
 
public Integer getId() {
 
return id;
 
}
 
public void setId(Integer id) {
 
this.id = id;
 
}
 
public String getName() {
 
return name;
 
}
 
public void setName(String name) {
 
this.name = name;
 
}
 
public Collection getUserCollection() {
 
return userCollection;
 
}
 
public void setUserCollection(Collection userCollection) {
 
this.userCollection = userCollection;
 
}
 
@Override
 
public int hashCode() {
 
int hash = 0;
 
hash += (id != null ? id.hashCode() : 0);
 
return hash;
 
}
 
@Override
 
public boolean equals(Object object) {
 
// TODO: Warning - this method won't work in the case the id fields are not set
 
if (!(object instanceof SecurityRoleEntity)) {
 
return false;
 
}
 
SecurityRoleEntity other = (SecurityRoleEntity) object;
 
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
 
return false;
 
}
 
return true;
 
}
 
@Override
 
public String toString() {
 
return 'org.intan.pedigree.form.SecurityRole[id=' + id + ']';
 
}
 
}

Теперь, когда у нас есть DTO, давайте создадим необходимые классы DAO:

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package org.intan.pedigree.dao;
 
import java.util.List;
 
import java.util.Set;
 
import org.hibernate.SessionFactory;
 
import org.intan.pedigree.form.SecurityRoleEntity;
 
import org.intan.pedigree.form.UserEntity;
 
import org.springframework.beans.factory.annotation.Autowired;
 
import org.springframework.stereotype.Repository;
 
@Repository
 
public class UserEntityDAOImpl implements UserEntityDAO{
 
@Autowired
 
private SessionFactory sessionFactory;
 
public void addUser(UserEntity user) {
 
try {
 
sessionFactory.getCurrentSession().save(user);
 
} catch (Exception e) {
 
System.out.println(e);
 
}
 
}
 
public UserEntity findByName(String username) {
 
UserEntity user = (UserEntity) sessionFactory.getCurrentSession().createQuery(
 
'select u from UserEntity u where u.username = '' + username + ''').uniqueResult();
 
return user;
 
}
 
public UserEntity getUserByID(Integer id) {
 
UserEntity user = (UserEntity) sessionFactory.getCurrentSession().createQuery(
 
'select u from UserEntity u where id = '' + id + ''').uniqueResult();
 
return user;
 
}
 
public String activateUser(Integer id) {
 
String hql = 'update UserEntityset active = :active where id = :id';
 
org.hibernate.Query query = sessionFactory.getCurrentSession().createQuery(hql);
 
query.setString('active','Y');
 
query.setInteger('id',id);
 
int rowCount = query.executeUpdate();
 
System.out.println('Rows affected: ' + rowCount);
 
return '';
 
}
 
public String disableUser(Integer id) {
 
String hql = 'update UserEntity set active = :active where id = :id';
 
org.hibernate.Query query = sessionFactory.getCurrentSession().createQuery(hql);
 
query.setInteger('active',0);
 
query.setInteger('id',id);
 
int rowCount = query.executeUpdate();
 
System.out.println('Rows affected: ' + rowCount);
 
return '';
 
}
 
public void updateUser(UserEntity user) {
 
try {
 
sessionFactory.getCurrentSession().update(user);
 
} catch (Exception e) {
 
System.out.println(e);
 
}
 
}
 
public List listUser() {
 
return sessionFactory.getCurrentSession().createQuery('from UserEntity')
 
.list();
 
}
 
public void removeUser(Integer id) {
 
UserEntity user = (UserEntity) sessionFactory.getCurrentSession().load(
 
UserEntity.class, id);
 
if (null != user) {
 
sessionFactory.getCurrentSession().delete(user);
 
}
 
}
 
public Set getSecurityRolesForUsername(String username) {
 
UserEntity user = (UserEntity) sessionFactory.getCurrentSession().createQuery(
 
'select u from UserEntity u where u.username = '' + username + ''').uniqueResult();
 
if (user!= null) {
 
Set roles = (Set) user.getSecurityRoleCollection();
 
if (roles != null && roles.size() > 0) {
 
return roles;
 
}
 
}
 
return null;
 
}
 
}
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package org.intan.pedigree.dao;
 
import java.util.List;
 
import org.hibernate.Criteria;
 
import org.hibernate.SessionFactory;
 
import org.hibernate.criterion.Restrictions;
 
import org.intan.pedigree.form.Country;
 
import org.intan.pedigree.form.Kennel;
 
import org.intan.pedigree.form.SecurityRoleEntity;
 
import org.springframework.beans.factory.annotation.Autowired;
 
import org.springframework.stereotype.Repository;
 
@Repository
 
public class SecurityRoleEntityDAOImpl implements SecurityRoleEntityDAO{
 
@Autowired
 
private SessionFactory sessionFactory;
 
public void addSecurityRoleEntity(SecurityRoleEntity securityRoleEntity) {
 
try {
 
sessionFactory.getCurrentSession().save(securityRoleEntity);
 
} catch (Exception e) {
 
System.out.println(e);
 
}
 
}
 
public List listSecurityRoleEntity() {
 
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(SecurityRoleEntity.class);
 
criteria.add(Restrictions.ne('name','ROLE_ADMIN' ));
 
return criteria.list();
 
}
 
public SecurityRoleEntity getSecurityRoleEntityById(Integer id) {
 
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(SecurityRoleEntity.class);
 
criteria.add(Restrictions.eq('id',id));
 
return (SecurityRoleEntity) criteria.uniqueResult();
 
}
 
public void removeSecurityRoleEntity(Integer id) {
 
SecurityRoleEntity securityRoleEntity = (SecurityRoleEntity) sessionFactory.getCurrentSession().load(
 
SecurityRoleEntity.class, id);
 
if (null != securityRoleEntity) {
 
sessionFactory.getCurrentSession().delete(securityRoleEntity);
 
}
 
}
 
}

Теперь мы создадим сервисный слой для вышеупомянутых DAO.

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
45
46
47
48
49
50
51
52
53
54
55
package org.intan.pedigree.service;
 
import java.util.List;
 
import org.intan.pedigree.dao.SecurityRoleEntityDAO;
 
import org.intan.pedigree.form.SecurityRoleEntity;
 
import org.springframework.beans.factory.annotation.Autowired;
 
import org.springframework.stereotype.Service;
 
import org.springframework.transaction.annotation.Transactional;
 
@Service
 
public class SecurityRoleEntityServiceImpl implements SecurityRoleEntityService{
 
@Autowired
 
private SecurityRoleEntityDAO securityRoleEntityDAO;
 
@Transactional
 
public void addSecurityRoleEntity(SecurityRoleEntity securityRoleEntity) {
 
securityRoleEntityDAO.addSecurityRoleEntity(securityRoleEntity);
 
}
 
@Transactional
 
public List listSecurityRoleEntity() {
 
return securityRoleEntityDAO.listSecurityRoleEntity();
 
}
 
@Transactional
 
public void removeSecurityRoleEntity(Integer id) {
 
securityRoleEntityDAO.removeSecurityRoleEntity(id);
 
}
 
@Transactional
 
public SecurityRoleEntity getSecurityRoleEntityById(Integer id) {
 
return securityRoleEntityDAO.getSecurityRoleEntityById( id);
 
}
 
}

В слое Service UserDetails ниже обратите внимание, что он реализует UserDetailsService из org.springframework.security.core.userdetails.UserDetailsService.

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
45
46
47
48
49
50
51
52
53
54
55
package org.intan.pedigree.service;
 
import org.intan.pedigree.dao.UserEntityDAO;
 
import org.intan.pedigree.dao.UserEntityDAO;
 
import org.intan.pedigree.form.UserEntity;
 
import org.springframework.beans.factory.annotation.Autowired;
 
import org.springframework.dao.DataAccessException;
 
import org.springframework.stereotype.Service;
 
import org.springframework.transaction.annotation.Transactional;
 
import org.springframework.security.core.userdetails.User;
 
import org.springframework.security.core.userdetails.UserDetails;
 
import org.springframework.security.core.userdetails.UserDetailsService;
 
import org.springframework.security.core.userdetails.UsernameNotFoundException;
 
@Service('userDetailsService')
 
public class UserDetailsServiceImpl implements UserDetailsService {
 
@Autowired
 
private UserEntityDAO dao;
 
@Autowired
 
private Assembler assembler;
 
@Transactional(readOnly = true)
 
public UserDetails loadUserByUsername(String username)
 
throws UsernameNotFoundException, DataAccessException {
 
UserDetails userDetails = null;
 
UserEntity userEntity = dao.findByName(username);
 
if (userEntity == null)
 
throw new UsernameNotFoundException('user not found');
 
return assembler.buildUserFromUserEntity(userEntity);
 
}
 
}

Вы также видите выше, что методы loadUserByUsername возвращают результат assemblyr.buildUserFromUserEntity. Проще говоря, этот метод ассемблера делает для создания объекта org.springframework.security.core.userdetails.User из заданного UserEntity DTO. Код класса Assembler приведен ниже:

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
45
46
47
48
49
50
51
52
53
54
55
56
57
package org.intan.pedigree.service;
 
import java.util.ArrayList;
 
import java.util.Collection;
 
import org.intan.pedigree.form.SecurityRoleEntity;
 
import org.intan.pedigree.form.UserEntity;
 
import org.springframework.security.core.GrantedAuthority;
 
import org.springframework.security.core.authority.GrantedAuthorityImpl;
 
import org.springframework.security.core.userdetails.User;
 
import org.springframework.stereotype.Service;
 
import org.springframework.transaction.annotation.Transactional;
 
@Service('assembler')
 
public class Assembler {
 
@Transactional(readOnly = true)
 
User buildUserFromUserEntity(UserEntity userEntity) {
 
String username = userEntity.getUsername();
 
String password = userEntity.getPassword();
 
boolean enabled = userEntity.getActive();
 
boolean accountNonExpired = userEntity.getActive();
 
boolean credentialsNonExpired = userEntity.getActive();
 
boolean accountNonLocked = userEntity.getActive();
 
Collection authorities = new ArrayList();
 
for (SecurityRoleEntity role : userEntity.getSecurityRoleCollection()) {
 
authorities.add(new GrantedAuthorityImpl(role.getName()));
 
}
 
User user = new User(username, password, enabled,
 
accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
 
return user;
 
}
 
}

Единственное, что осталось сделать сейчас, — это определить, что необходимо в applicationContext-Security.xml. Для этого создайте новый XML-файл с именем «applicationContext-Security.xml» со ​​следующим содержимым:

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
<?xml version='1.0' encoding='UTF-8'?>
  
  
  
  
 <beans:bean id='userDetailsService' class='org.intan.pedigree.service.UserDetailsServiceImpl'></beans:bean>
 <context:component-scan base-package='org.intan.pedigree' />
  
 <http auto-config='true'>
  <intercept-url pattern='/admin/**' access='ROLE_ADMIN' />
  <intercept-url pattern='/user/**' access='ROLE_REGISTERED_USER' />
  <intercept-url pattern='/kennel/**' access='ROLE_KENNEL_OWNER' />
  <!-- <security:intercept-url pattern='/login.jsp' access='IS_AUTHENTICATED_ANONYMOUSLY' />  -->
 </http>
 
  <beans:bean id='daoAuthenticationProvider'
  class='org.springframework.security.authentication.dao.DaoAuthenticationProvider'>
  <beans:property name='userDetailsService' ref='userDetailsService' />
 </beans:bean>
 
 <beans:bean id='authenticationManager'
  class='org.springframework.security.authentication.ProviderManager'>
  <beans:property name='providers'>
   <beans:list>
    <beans:ref local='daoAuthenticationProvider' />
   </beans:list>
  </beans:property>
 </beans:bean>
 
 <authentication-manager>
  <authentication-provider user-service-ref='userDetailsService'>
   <password-encoder hash='plaintext' />
  </authentication-provider>
 </authentication-manager>
 
 
</beans:beans>

В ваш web.xml поместите следующий код, чтобы загрузить файл applicationContext-security.xml.

1
2
3
4
5
6
<context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/applicationContext-hibernate.xml
     /WEB-INF/applicationContext-security.xml
 </param-value>
</context-param>

И наконец, извините за любые опечатки и т. Д., Так как этот код просто скопировал и вставил из моей личной работы, если что-то не работает, пожалуйста, напишите вопрос, и я буду более чем рад помочь вам.

Ссылка: Spring 3, Spring Security Внедрение пользовательских пользовательских деталей с помощью Hibernate от нашего партнера по JCG Иоанниса Дадиса в блоге Giannisapi .