2 * Copyright 2005-2010 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;
26 * Implementation of the user accessor that retrieves user information from
29 * @author Erik Brakkee
31 public class JaasUserAccessor implements UserAccessor {
33 * User administration to use.
35 private UserAdministration admin;
38 * Class of the JAAS user principal.
40 private Class userPrincipalClass;
43 * Constructs user accessor.
46 * User administration.
47 * @param aUserClassName
48 * Class name of the user principal.
50 public JaasUserAccessor(UserAdministration aAdmin, String aUserClassName) {
54 userPrincipalClass = Class.forName(aUserClassName);
56 if (!Principal.class.isAssignableFrom(userPrincipalClass)) {
57 throw new IllegalArgumentException("Specified class '" +
58 aUserClassName + "' is not a subclass of '" +
59 Principal.class.getName());
61 } catch (ClassNotFoundException e) {
62 throw new RuntimeException(e);
69 * @see org.wamblee.usermgt.UserAccessor#getCurrentUser()
71 public User getCurrentUser() {
72 Subject subject = Subject.getSubject(AccessController.getContext());
74 if (subject == null) {
78 Principal userPrincipal = getUserPrincipal(subject);
80 return admin.getUser(userPrincipal.getName());
84 * Gets the user principal from the subject.
89 * @return User principal.
91 * @throws IllegalArgumentException
92 * In case there is a duplicate principal or the principal was
95 private Principal getUserPrincipal(Subject aSubject) {
96 Set<Principal> principals = aSubject.getPrincipals();
97 Principal userPrincipal = null;
99 for (Principal principal : principals) {
100 if (principal.getClass().equals(userPrincipalClass)) {
101 if (userPrincipal != null) {
102 throw new IllegalArgumentException(
103 "Multiple principals for class '" + userPrincipalClass +
104 "', subject: " + aSubject);
107 userPrincipal = principal;
111 if (userPrincipal == null) {
112 throw new IllegalArgumentException(
113 "No user principal found for class '" + userPrincipalClass +
114 "', subject: " + aSubject);
117 return userPrincipal;