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.
17 package org.wamblee.usermgt;
19 import java.security.AccessController;
20 import java.security.Principal;
23 import javax.security.auth.Subject;
26 * Implementation of the user accessor that retrieves user information
29 public class JaasUserAccessor implements UserAccessor {
32 * User administration to use.
34 private UserAdministration _admin;
37 * Class of the JAAS user principal.
39 private Class _userPrincipalClass;
42 * Constructs user accessor.
43 * @param aAdmin User administration.
44 * @param aUserClassName Class name of the user principal.
46 public JaasUserAccessor(UserAdministration aAdmin, String aUserClassName) {
49 _userPrincipalClass = Class.forName(aUserClassName);
50 if ( !Principal.class.isAssignableFrom(_userPrincipalClass)) {
51 throw new IllegalArgumentException("Specified class '" + aUserClassName + "' is not a subclass of '" +
52 Principal.class.getName());
54 } catch (ClassNotFoundException e) {
55 throw new RuntimeException(e);
62 * @see org.wamblee.usermgt.UserAccessor#getCurrentUser()
64 public User getCurrentUser() {
65 Subject subject = Subject.getSubject(AccessController.getContext());
66 if (subject == null) {
69 Principal userPrincipal = getUserPrincipal(subject);
71 return _admin.getUser(userPrincipal.getName());
75 * Gets the user principal from the subject.
76 * @param subject Subject.
77 * @return User principal.
78 * @throws IllegalArgumentException In case there is a duplicate principal or the principal was not found.
80 private Principal getUserPrincipal(Subject subject) {
81 Set<Principal> principals = subject.getPrincipals();
82 Principal userPrincipal = null;
83 for ( Principal principal: principals) {
84 if ( principal.getClass().equals(_userPrincipalClass)) {
85 if ( userPrincipal != null ) {
86 throw new IllegalArgumentException(
87 "Multiple principals for class '" + _userPrincipalClass + "', subject: " + subject);
89 userPrincipal = principal;
92 if ( userPrincipal == null ) {
93 throw new IllegalArgumentException(
94 "No user principal found for class '" + _userPrincipalClass + "', subject: " + subject);