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 protected UserDAO userDAO = null;
46
47 public SampleRealm() {
48 setName("SampleRealm");
49 setCredentialsMatcher(new Sha256CredentialsMatcher());
50 }
51
52 @Autowired
53 public void setUserDAO(UserDAO userDAO) {
54 this.userDAO = userDAO;
55 }
56
57 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
58 UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
59 User user = userDAO.findUser(token.getUsername());
60 if( user != null ) {
61 return new SimpleAuthenticationInfo(user.getId(), user.getPassword(), getName());
62 } else {
63 return null;
64 }
65 }
66
67
68 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
69 Long userId = (Long) principals.fromRealm(getName()).iterator().next();
70 User user = userDAO.getUser(userId);
71 if( user != null ) {
72 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
73 for( Role role : user.getRoles() ) {
74 info.addRole(role.getName());
75 info.addStringPermissions( role.getPermissions() );
76 }
77 return info;
78 } else {
79 return null;
80 }
81 }
82
83 }
84