1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
|
16 | |
|
17 | |
|
18 | |
|
19 | |
package org.apache.shiro.samples.sprhib.security; |
20 | |
|
21 | |
import org.apache.shiro.authc.*; |
22 | |
import org.apache.shiro.authc.credential.Sha256CredentialsMatcher; |
23 | |
import org.apache.shiro.authz.AuthorizationInfo; |
24 | |
import org.apache.shiro.authz.SimpleAuthorizationInfo; |
25 | |
import org.apache.shiro.realm.AuthorizingRealm; |
26 | |
import org.apache.shiro.samples.sprhib.dao.UserDAO; |
27 | |
import org.apache.shiro.samples.sprhib.model.Role; |
28 | |
import org.apache.shiro.samples.sprhib.model.User; |
29 | |
import org.apache.shiro.subject.PrincipalCollection; |
30 | |
import org.springframework.beans.factory.annotation.Autowired; |
31 | |
import org.springframework.stereotype.Component; |
32 | |
|
33 | |
|
34 | |
|
35 | |
|
36 | |
|
37 | |
|
38 | |
|
39 | |
|
40 | |
|
41 | |
|
42 | |
@Component |
43 | |
public class SampleRealm extends AuthorizingRealm { |
44 | |
|
45 | 0 | protected UserDAO userDAO = null; |
46 | |
|
47 | 0 | public SampleRealm() { |
48 | 0 | setName("SampleRealm"); |
49 | 0 | setCredentialsMatcher(new Sha256CredentialsMatcher()); |
50 | 0 | } |
51 | |
|
52 | |
@Autowired |
53 | |
public void setUserDAO(UserDAO userDAO) { |
54 | 0 | this.userDAO = userDAO; |
55 | 0 | } |
56 | |
|
57 | |
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { |
58 | 0 | UsernamePasswordToken token = (UsernamePasswordToken) authcToken; |
59 | 0 | User user = userDAO.findUser(token.getUsername()); |
60 | 0 | if( user != null ) { |
61 | 0 | return new SimpleAuthenticationInfo(user.getId(), user.getPassword(), getName()); |
62 | |
} else { |
63 | 0 | return null; |
64 | |
} |
65 | |
} |
66 | |
|
67 | |
|
68 | |
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { |
69 | 0 | Long userId = (Long) principals.fromRealm(getName()).iterator().next(); |
70 | 0 | User user = userDAO.getUser(userId); |
71 | 0 | if( user != null ) { |
72 | 0 | SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); |
73 | 0 | for( Role role : user.getRoles() ) { |
74 | 0 | info.addRole(role.getName()); |
75 | 0 | info.addStringPermissions( role.getPermissions() ); |
76 | 0 | } |
77 | 0 | return info; |
78 | |
} else { |
79 | 0 | return null; |
80 | |
} |
81 | |
} |
82 | |
|
83 | |
} |
84 | |
|