2 * Copyright (C) 2007-2012 Argeo GmbH
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
.argeo
.security
.ui
.internal
;
18 import java
.security
.AccessController
;
19 import java
.security
.Principal
;
20 import java
.util
.Collections
;
21 import java
.util
.HashSet
;
24 import javax
.security
.auth
.Subject
;
26 import org
.argeo
.ArgeoException
;
27 import org
.springframework
.security
.Authentication
;
28 import org
.springframework
.security
.GrantedAuthority
;
31 * Retrieves information about the current user. Not an API, can change without
34 public class CurrentUser
{
35 public final static String
getUsername() {
36 Subject subject
= getSubject();
39 Principal principal
= subject
.getPrincipals().iterator().next();
40 return principal
.getName();
44 public final static Set
<String
> roles() {
45 Set
<String
> roles
= Collections
.synchronizedSet(new HashSet
<String
>());
46 Authentication authentication
= getAuthentication();
47 for (GrantedAuthority ga
: authentication
.getAuthorities()) {
48 roles
.add(ga
.getAuthority());
50 return Collections
.unmodifiableSet(roles
);
53 public final static Authentication
getAuthentication() {
54 Set
<Authentication
> authens
= getSubject().getPrincipals(
55 Authentication
.class);
56 if (authens
!= null && !authens
.isEmpty()) {
57 Principal principal
= authens
.iterator().next();
58 Authentication authentication
= (Authentication
) principal
;
59 return authentication
;
61 throw new ArgeoException("No authentication found");
64 public final static Subject
getSubject() {
65 Subject subject
= Subject
.getSubject(AccessController
.getContext());
67 throw new ArgeoException("Not authenticated.");