View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.shiro.realm;
20  
21  import org.apache.shiro.authc.AuthenticationException;
22  import org.apache.shiro.authc.AuthenticationInfo;
23  import org.apache.shiro.authc.AuthenticationToken;
24  import org.apache.shiro.authc.ExpiredCredentialsException;
25  import org.apache.shiro.authc.LockedAccountException;
26  import org.apache.shiro.authc.SimpleAccount;
27  import org.apache.shiro.authc.UsernamePasswordToken;
28  import org.apache.shiro.authz.AuthorizationInfo;
29  import org.apache.shiro.authz.SimpleRole;
30  import org.apache.shiro.subject.PrincipalCollection;
31  import org.apache.shiro.util.CollectionUtils;
32  
33  import java.util.HashSet;
34  import java.util.LinkedHashMap;
35  import java.util.Map;
36  import java.util.Set;
37  import java.util.concurrent.locks.ReadWriteLock;
38  import java.util.concurrent.locks.ReentrantReadWriteLock;
39  
40  /**
41   * A simple implementation of the {@link Realm Realm} interface that
42   * uses a set of configured user accounts and roles to support authentication and authorization.  Each account entry
43   * specifies the username, password, and roles for a user.  Roles can also be mapped
44   * to permissions and associated with users.
45   * <p/>
46   * User accounts and roles are stored in two {@code Map}s in memory, so it is expected that the total number of either
47   * is not sufficiently large.
48   *
49   * @since 0.1
50   */
51  public class SimpleAccountRealm extends AuthorizingRealm {
52  
53      /**
54       * username-to-SimpleAccount.
55       */
56      protected final Map<String, SimpleAccount> users;
57  
58      /**
59       * roleName-to-SimpleRole.
60       */
61      protected final Map<String, SimpleRole> roles;
62  
63      protected final ReadWriteLock usersLock;
64      protected final ReadWriteLock rolesLock;
65  
66      public SimpleAccountRealm() {
67          this.users = new LinkedHashMap<String, SimpleAccount>();
68          this.roles = new LinkedHashMap<String, SimpleRole>();
69          usersLock = new ReentrantReadWriteLock();
70          rolesLock = new ReentrantReadWriteLock();
71          //SimpleAccountRealms are memory-only realms - no need for an additional cache mechanism since we're
72          //already as memory-efficient as we can be:
73          setCachingEnabled(false);
74      }
75  
76      public SimpleAccountRealm(String name) {
77          this();
78          setName(name);
79      }
80  
81      protected SimpleAccount getUser(String username) {
82          usersLock.readLock().lock();
83          try {
84              return this.users.get(username);
85          } finally {
86              usersLock.readLock().unlock();
87          }
88      }
89  
90      public boolean accountExists(String username) {
91          return getUser(username) != null;
92      }
93  
94      public void addAccount(String username, String password) {
95          addAccount(username, password, (String[]) null);
96      }
97  
98      public void addAccount(String username, String password, String... roles) {
99          Set<String> roleNames = CollectionUtils.asSet(roles);
100         SimpleAccount account = new SimpleAccount(username, password, getName(), roleNames, null);
101         add(account);
102     }
103 
104     protected String getUsername(SimpleAccount account) {
105         return getUsername(account.getPrincipals());
106     }
107 
108     protected String getUsername(PrincipalCollection principals) {
109         return getAvailablePrincipal(principals).toString();
110     }
111 
112     protected void add(SimpleAccount account) {
113         String username = getUsername(account);
114         usersLock.writeLock().lock();
115         try {
116             this.users.put(username, account);
117         } finally {
118             usersLock.writeLock().unlock();
119         }
120     }
121 
122     protected SimpleRole getRole(String rolename) {
123         rolesLock.readLock().lock();
124         try {
125             return roles.get(rolename);
126         } finally {
127             rolesLock.readLock().unlock();
128         }
129     }
130 
131     public boolean roleExists(String name) {
132         return getRole(name) != null;
133     }
134 
135     public void addRole(String name) {
136         add(new SimpleRole(name));
137     }
138 
139     protected void add(SimpleRole role) {
140         rolesLock.writeLock().lock();
141         try {
142             roles.put(role.getName(), role);
143         } finally {
144             rolesLock.writeLock().unlock();
145         }
146     }
147 
148     protected static Set<String> toSet(String delimited, String delimiter) {
149         if (delimited == null || delimited.trim().equals("")) {
150             return null;
151         }
152 
153         Set<String> values = new HashSet<String>();
154         String[] rolenamesArray = delimited.split(delimiter);
155         for (String s : rolenamesArray) {
156             String trimmed = s.trim();
157             if (trimmed.length() > 0) {
158                 values.add(trimmed);
159             }
160         }
161 
162         return values;
163     }
164 
165     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
166         UsernamePasswordToken upToken = (UsernamePasswordToken) token;
167         SimpleAccount account = getUser(upToken.getUsername());
168 
169         if (account != null) {
170 
171             if (account.isLocked()) {
172                 throw new LockedAccountException("Account [" + account + "] is locked.");
173             }
174             if (account.isCredentialsExpired()) {
175                 String msg = "The credentials for account [" + account + "] are expired";
176                 throw new ExpiredCredentialsException(msg);
177             }
178 
179         }
180 
181         return account;
182     }
183 
184     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
185         String username = getUsername(principals);
186         usersLock.readLock().lock();
187         try {
188             return this.users.get(username);
189         } finally {
190             usersLock.readLock().unlock();
191         }
192     }
193 }