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 * @author Erik Brakkee
31 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) {
51 _userPrincipalClass = Class.forName(aUserClassName);
52 if ( !Principal.class.isAssignableFrom(_userPrincipalClass)) {
53 throw new IllegalArgumentException("Specified class '" + aUserClassName + "' is not a subclass of '" +
54 Principal.class.getName());
56 } catch (ClassNotFoundException e) {
57 throw new RuntimeException(e);
64 * @see org.wamblee.usermgt.UserAccessor#getCurrentUser()
66 public User getCurrentUser() {
67 Subject subject = Subject.getSubject(AccessController.getContext());
68 if (subject == null) {
71 Principal userPrincipal = getUserPrincipal(subject);
73 return _admin.getUser(userPrincipal.getName());
77 * Gets the user principal from the subject.
78 * @param subject Subject.
79 * @return User principal.
80 * @throws IllegalArgumentException In case there is a duplicate principal or the principal was not found.
82 private Principal getUserPrincipal(Subject subject) {
83 Set<Principal> principals = subject.getPrincipals();
84 Principal userPrincipal = null;
85 for ( Principal principal: principals) {
86 if ( principal.getClass().equals(_userPrincipalClass)) {
87 if ( userPrincipal != null ) {
88 throw new IllegalArgumentException(
89 "Multiple principals for class '" + _userPrincipalClass + "', subject: " + subject);
91 userPrincipal = principal;
94 if ( userPrincipal == null ) {
95 throw new IllegalArgumentException(
96 "No user principal found for class '" + _userPrincipalClass + "', subject: " + subject);