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.*;
22  import org.apache.shiro.authz.AuthorizationInfo;
23  import org.apache.shiro.authz.SimpleRole;
24  import org.apache.shiro.subject.PrincipalCollection;
25  import org.apache.shiro.util.CollectionUtils;
26  
27  import java.util.HashSet;
28  import java.util.LinkedHashMap;
29  import java.util.Map;
30  import java.util.Set;
31  import java.util.concurrent.locks.Lock;
32  import java.util.concurrent.locks.ReadWriteLock;
33  import java.util.concurrent.locks.ReentrantReadWriteLock;
34  
35  /**
36   * A simple implementation of the {@link Realm Realm} interface that
37   * uses a set of configured user accounts and roles to support authentication and authorization.  Each account entry
38   * specifies the username, password, and roles for a user.  Roles can also be mapped
39   * to permissions and associated with users.
40   * <p/>
41   * User accounts and roles are stored in two {@code Map}s in memory, so it is expected that the total number of either
42   * is not sufficiently large.
43   *
44   * @since 0.1
45   */
46  public class SimpleAccountRealm extends AuthorizingRealm {
47  
48      //TODO - complete JavaDoc
49      protected final Map<String, SimpleAccount> users; //username-to-SimpleAccount
50      protected final Map<String, SimpleRole> roles; //roleName-to-SimpleRole
51      protected final ReadWriteLock USERS_LOCK;
52      protected final ReadWriteLock ROLES_LOCK;
53  
54      public SimpleAccountRealm() {
55          this.users = new LinkedHashMap<String, SimpleAccount>();
56          this.roles = new LinkedHashMap<String, SimpleRole>();
57          USERS_LOCK = new ReentrantReadWriteLock();
58          ROLES_LOCK = new ReentrantReadWriteLock();
59          //SimpleAccountRealms are memory-only realms - no need for an additional cache mechanism since we're
60          //already as memory-efficient as we can be:
61          setCachingEnabled(false);
62      }
63  
64      public SimpleAccountRealm(String name) {
65          this();
66          setName(name);
67      }
68  
69      protected SimpleAccount getUser(String username) {
70          USERS_LOCK.readLock().lock();
71          try {
72              return this.users.get(username);
73          } finally {
74              USERS_LOCK.readLock().unlock();
75          }
76      }
77  
78      public boolean accountExists(String username) {
79          return getUser(username) != null;
80      }
81  
82      public void addAccount(String username, String password) {
83          addAccount(username, password, (String[]) null);
84      }
85  
86      public void addAccount(String username, String password, String... roles) {
87          Set<String> roleNames = CollectionUtils.asSet(roles);
88          SimpleAccount account = new SimpleAccount(username, password, getName(), roleNames, null);
89          add(account);
90      }
91  
92      protected String getUsername(SimpleAccount account) {
93          return getUsername(account.getPrincipals());
94      }
95  
96      protected String getUsername(PrincipalCollection principals) {
97          return getAvailablePrincipal(principals).toString();
98      }
99  
100     protected void add(SimpleAccount account) {
101         String username = getUsername(account);
102         USERS_LOCK.writeLock().lock();
103         try {
104             this.users.put(username, account);
105         } finally {
106             USERS_LOCK.writeLock().unlock();
107         }
108     }
109 
110     protected SimpleRole getRole(String rolename) {
111         ROLES_LOCK.readLock().lock();
112         try {
113             return roles.get(rolename);
114         } finally {
115             ROLES_LOCK.readLock().unlock();
116         }
117     }
118 
119     public boolean roleExists(String name) {
120         return getRole(name) != null;
121     }
122 
123     public void addRole(String name) {
124         add(new SimpleRole(name));
125     }
126 
127     protected void add(SimpleRole role) {
128         ROLES_LOCK.writeLock().lock();
129         try {
130             roles.put(role.getName(), role);
131         } finally {
132             ROLES_LOCK.writeLock().unlock();
133         }
134     }
135 
136     protected static Set<String> toSet(String delimited, String delimiter) {
137         if (delimited == null || delimited.trim().equals("")) {
138             return null;
139         }
140 
141         Set<String> values = new HashSet<String>();
142         String[] rolenamesArray = delimited.split(delimiter);
143         for (String s : rolenamesArray) {
144             String trimmed = s.trim();
145             if (trimmed.length() > 0) {
146                 values.add(trimmed);
147             }
148         }
149 
150         return values;
151     }
152 
153     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
154         UsernamePasswordToken upToken = (UsernamePasswordToken) token;
155         SimpleAccount account = getUser(upToken.getUsername());
156 
157         if (account != null) {
158 
159             if (account.isLocked()) {
160                 throw new LockedAccountException("Account [" + account + "] is locked.");
161             }
162             if (account.isCredentialsExpired()) {
163                 String msg = "The credentials for account [" + account + "] are expired";
164                 throw new ExpiredCredentialsException(msg);
165             }
166 
167         }
168 
169         return account;
170     }
171 
172     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
173         String username = getUsername(principals);
174         USERS_LOCK.readLock().lock();
175         try {
176             return this.users.get(username);
177         } finally {
178             USERS_LOCK.readLock().unlock();
179         }
180     }
181 }