View Javadoc
1   /*
2    * Copyright 2006-2011 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  package org.springframework.security.oauth2.provider.client;
14  
15  import org.springframework.security.core.userdetails.User;
16  import org.springframework.security.core.userdetails.UserDetails;
17  import org.springframework.security.core.userdetails.UserDetailsService;
18  import org.springframework.security.core.userdetails.UsernameNotFoundException;
19  import org.springframework.security.crypto.password.PasswordEncoder;
20  import org.springframework.security.oauth2.provider.ClientDetails;
21  import org.springframework.security.oauth2.provider.ClientDetailsService;
22  import org.springframework.security.oauth2.provider.NoSuchClientException;
23  
24  /**
25   * @author Dave Syer
26   * 
27   */
28  public class ClientDetailsUserDetailsService implements UserDetailsService {
29  
30  	private final ClientDetailsService clientDetailsService;
31  	private String emptyPassword = "";
32  	
33  	public ClientDetailsUserDetailsService(ClientDetailsService clientDetailsService) {
34  		this.clientDetailsService = clientDetailsService;
35  	}
36  	
37  	/**
38  	 * @param passwordEncoder the password encoder to set
39  	 */
40  	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
41  		this.emptyPassword = passwordEncoder.encode("");
42  	}
43  
44  	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
45  		ClientDetails clientDetails;
46  		try {
47  			clientDetails = clientDetailsService.loadClientByClientId(username);
48  		} catch (NoSuchClientException e) {
49  			throw new UsernameNotFoundException(e.getMessage(), e);
50  		}
51  		String clientSecret = clientDetails.getClientSecret();
52  		if (clientSecret== null || clientSecret.trim().length()==0) {
53  			clientSecret = emptyPassword;
54  		}
55  		return new User(username, clientSecret, clientDetails.getAuthorities());
56  	}
57  
58  }