2 * Copyright 2005 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.usermgt;
18 import java.security.AccessController;
19 import java.security.Principal;
23 import javax.security.auth.Subject;
27 * Implementation of the user accessor that retrieves user information from
30 * @author Erik Brakkee
32 public class JaasUserAccessor implements UserAccessor {
34 * User administration to use.
36 private UserAdministration admin;
39 * Class of the JAAS user principal.
41 private Class userPrincipalClass;
44 * Constructs user accessor.
45 * @param aAdmin User administration.
46 * @param aUserClassName Class name of the user principal.
48 public JaasUserAccessor(UserAdministration aAdmin, String aUserClassName) {
52 userPrincipalClass = Class.forName(aUserClassName);
54 if (!Principal.class.isAssignableFrom(userPrincipalClass)) {
55 throw new IllegalArgumentException("Specified class '"
56 + aUserClassName + "' is not a subclass of '"
57 + Principal.class.getName());
59 } catch (ClassNotFoundException e) {
60 throw new RuntimeException(e);
67 * @see org.wamblee.usermgt.UserAccessor#getCurrentUser()
72 * @return DOCUMENT ME!
74 public User getCurrentUser() {
75 Subject subject = Subject.getSubject(AccessController.getContext());
77 if (subject == null) {
81 Principal userPrincipal = getUserPrincipal(subject);
83 return admin.getUser(userPrincipal.getName());
87 * Gets the user principal from the subject.
89 * @param subject Subject.
91 * @return User principal.
93 * @throws IllegalArgumentException In case there is a duplicate principal
94 * or the principal was not found.
96 private Principal getUserPrincipal(Subject subject) {
97 Set<Principal> principals = subject.getPrincipals();
98 Principal userPrincipal = null;
100 for (Principal principal : principals) {
101 if (principal.getClass().equals(userPrincipalClass)) {
102 if (userPrincipal != null) {
103 throw new IllegalArgumentException(
104 "Multiple principals for class '" + userPrincipalClass
105 + "', subject: " + subject);
108 userPrincipal = principal;
112 if (userPrincipal == null) {
113 throw new IllegalArgumentException(
114 "No user principal found for class '" + userPrincipalClass
115 + "', subject: " + subject);
118 return userPrincipal;