View Javadoc
1   /*
2    * Copyright 2013-2014 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5    * the License. You may obtain a copy of the License at
6    *
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10   * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11   * specific language governing permissions and limitations under the License.
12   */
13  
14  package org.springframework.security.oauth2.provider;
15  
16  import java.util.Collections;
17  import java.util.HashSet;
18  import java.util.Set;
19  
20  import org.springframework.security.core.Authentication;
21  import org.springframework.security.core.GrantedAuthority;
22  import org.springframework.security.core.context.SecurityContextHolder;
23  
24  /**
25   * Strategy for accessing useful information about the current security context.
26   * 
27   * @author Dave Syer
28   * 
29   */
30  public class DefaultSecurityContextAccessor implements SecurityContextAccessor {
31  
32  	@Override
33  	public boolean isUser() {
34  		Authentication authentication = getUserAuthentication();
35  		return authentication != null;
36  	}
37  	
38  	@Override
39  	public Set<GrantedAuthority> getAuthorities() {
40  		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
41  		if (authentication == null) {
42  			return Collections.emptySet();
43  		}
44  		return Collections.unmodifiableSet(new HashSet<GrantedAuthority>(authentication.getAuthorities()));
45  	}
46  
47  	private Authentication getUserAuthentication() {
48  		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
49  		if (authentication == null) {
50  			return null;
51  		}
52  		if (authentication instanceof OAuth2Authentication) {
53  			OAuth2Authentication oauth = (OAuth2Authentication) authentication;
54  			return oauth.getUserAuthentication();
55  		}
56  		return authentication;
57  	}
58  
59  }