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.security.authentication;
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);
67 public String getCurrentUser() {
68 Subject subject = Subject.getSubject(AccessController.getContext());
70 if (subject == null) {
74 Principal userPrincipal = getUserPrincipal(subject);
76 return userPrincipal.getName();
80 * Gets the user principal from the subject.
85 * @return User principal.
87 * @throws IllegalArgumentException
88 * In case there is a duplicate principal or the principal was
91 private Principal getUserPrincipal(Subject aSubject) {
92 Set<Principal> principals = aSubject.getPrincipals();
93 Principal userPrincipal = null;
95 for (Principal principal : principals) {
96 if (principal.getClass().equals(userPrincipalClass)) {
97 if (userPrincipal != null) {
98 throw new IllegalArgumentException(
99 "Multiple principals for class '" + userPrincipalClass +
100 "', subject: " + aSubject);
103 userPrincipal = principal;
107 if (userPrincipal == null) {
108 throw new IllegalArgumentException(
109 "No user principal found for class '" + userPrincipalClass +
110 "', subject: " + aSubject);
113 return userPrincipal;