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 {
34 * Class of the JAAS user principal.
36 private Class userPrincipalClass;
39 * Constructs user accessor.
42 * User administration.
43 * @param aUserClassName
44 * Class name of the user principal.
46 public JaasUserAccessor(String aUserClassName) {
48 userPrincipalClass = Class.forName(aUserClassName);
50 if (!Principal.class.isAssignableFrom(userPrincipalClass)) {
51 throw new IllegalArgumentException("Specified class '" +
52 aUserClassName + "' is not a subclass of '" +
53 Principal.class.getName());
55 } catch (ClassNotFoundException e) {
56 throw new RuntimeException(e);
61 public String getCurrentUser() {
62 Subject subject = Subject.getSubject(AccessController.getContext());
64 if (subject == null) {
68 Principal userPrincipal = getUserPrincipal(subject);
70 return userPrincipal.getName();
74 * Gets the user principal from the subject.
79 * @return User principal.
81 * @throws IllegalArgumentException
82 * In case there is a duplicate principal or the principal was
85 private Principal getUserPrincipal(Subject aSubject) {
86 Set<Principal> principals = aSubject.getPrincipals();
87 Principal userPrincipal = null;
89 for (Principal principal : principals) {
90 if (principal.getClass().equals(userPrincipalClass)) {
91 if (userPrincipal != null) {
92 throw new IllegalArgumentException(
93 "Multiple principals for class '" + userPrincipalClass +
94 "', subject: " + aSubject);
97 userPrincipal = principal;
101 if (userPrincipal == null) {
102 throw new IllegalArgumentException(
103 "No user principal found for class '" + userPrincipalClass +
104 "', subject: " + aSubject);
107 return userPrincipal;