2013-08-30 73 views
8

Tôi có trường hợp tôi muốn tự tạo mã truy cập (do đó không thông qua quy trình thông thường). Tôi đã đưa ra một cái gì đó như thế này:Spring OAuth2 - Tạo mã thông báo truy cập theo cách thủ công trong cửa hàng mã thông báo

@Inject 
private DefaultTokenServices defaultTokenServices; 

... 

OAuth2Authentication auth = xxx; 
OAuth2AccessToken token = defaultTokenServices.createAccessToken(auth); 

Vấn đề duy nhất là tôi không chắc chắn làm thế nào để tạo OAuth2Authentication (trong mã của tôi một phần với xxx). Tôi có thông tin khách hàng & của người dùng và tôi biết được Cơ quan nào tôi muốn cấp mã thông báo này.

+0

Tôi thực sự đã làm điều này gần đây, hãy cho tôi biết nếu bạn vẫn cần mã như bài đăng này là một chút cũ. – Michael

+0

vâng. i am quan tâm – checklist

+0

Đó là dọc theo dòng của những gì bạn đang tìm kiếm? – Michael

Trả lời

15

Đây là trường hợp sử dụng của bạn có thể hơi khác nhau dựa trên luồng bạn đang sử dụng. Đây là những gì làm việc cho một luồng cấp mật khẩu. Có một vài lớp tùy chỉnh như kho lưu trữ token, token enhancer ect. nhưng đó thực sự chỉ là phiên bản mở rộng của các lớp xuân được sửa đổi cho nhu cầu của chúng ta.

 HashMap<String, String> authorizationParameters = new HashMap<String, String>(); 
     authorizationParameters.put("scope", "read"); 
     authorizationParameters.put("username", "mobile_client"); 
     authorizationParameters.put("client_id", "mobile-client"); 
     authorizationParameters.put("grant", "password"); 

     DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest(authorizationParameters); 
     authorizationRequest.setApproved(true); 

     Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); 
     authorities.add(new SimpleGrantedAuthority("ROLE_UNTRUSTED_CLIENT")); 
     authorizationRequest.setAuthorities(authorities); 

     HashSet<String> resourceIds = new HashSet<String>(); 
     resourceIds.add("mobile-public"); 
     authorizationRequest.setResourceIds(resourceIds); 

     // Create principal and auth token 
     User userPrincipal = new User(user.getUserID(), "", true, true, true, true, authorities); 

     UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userPrincipal, null, authorities) ; 

     OAuth2Authentication authenticationRequest = new OAuth2Authentication(authorizationRequest, authenticationToken); 
     authenticationRequest.setAuthenticated(true); 

     CustomTokenStore tokenStore = new CustomTokenStore(); 

     // Token Enhancer 
     CustomTokenEnhancer tokenEnhancer = new CustomTokenEnhancer(user.getUserID()); 

     CustomTokenServices tokenServices = new CustomTokenServices(); 
     tokenServices.setTokenEnhancer(tokenEnhancer); 
     tokenServices.setSupportRefreshToken(true); 
     tokenServices.setTokenStore(tokenStore); 

     OAuth2AccessToken accessToken = tokenServices.createAccessTokenForUser(authenticationRequest, user); 
10

Dưới đây là làm thế nào để tạo ra một Token sử dụng giao diện TokenEndpoint (dùng để vạch trần dịch vụ REST):

@Inject 
private TokenEndpoint tokenEndpoint; 

public ResponseEntity<?> getToken(Principal principal) { 

     HashMap<String, String> parameters = new HashMap<String, String>(); 
     parameters.put("client_id", "appid"); 
     parameters.put("client_secret", "myOAuthSecret"); 
     parameters.put("grant_type", "password"); 
     parameters.put("password", myUser.getPassword()); 
     parameters.put("scope", "read write"); 
     parameters.put("username", myUser.getLogin()); 

     return tokenEndpoint.getAccessToken(principal, parameters); 
} 
4

cách khác, tự tạo ra một OAuth2 Accesss Token chúng ta có thể sử dụng một thể hiện của TokenService

@Autowired 
private AuthorizationServerEndpointsConfiguration configuration; 

@Override 
public String generateOAuth2AccessToken(User user, List<Role> roles, List<String> scopes) { 

    Map<String, String> requestParameters = new HashMap<String, String>(); 
    Map<String, Serializable> extensionProperties = new HashMap<String, Serializable>(); 

    boolean approved = true; 
    Set<String> responseTypes = new HashSet<String>(); 
    responseTypes.add("code"); 

    // Authorities 
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); 
    for(Role role: roles) 
     authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName())); 

    OAuth2Request oauth2Request = new OAuth2Request(requestParameters, "clientIdTest", authorities, approved, new HashSet<String>(scopes), new HashSet<String>(Arrays.asList("resourceIdTest")), null, responseTypes, extensionProperties); 

    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), "N/A", authorities); 

    OAuth2Authentication auth = new OAuth2Authentication(oauth2Request, authenticationToken); 

    AuthorizationServerTokenServices tokenService = configuration.getEndpointsConfigurer().getTokenServices(); 

    OAuth2AccessToken token = tokenService.createAccessToken(auth); 

    return token.getValue(); 
} 
+0

với phương pháp này, chúng tôi có thể truy cập tài nguyên bằng mã thông báo truy cập được tạo, khi mã thông báo truy cập hết hạn, nó sẽ không phát hành mã thông báo truy cập với mã thông báo làm mới. nó cung cấp cho khách hàng không được phép, ngay cả khi các chi tiết của khách hàng là chính xác –