5

Tôi đã triển khai oAuth2 với bảo mật mùa xuân và mã này hoạt động tốt cho tôi. Nhưng bây giờ tôi muốn tạo mã thông báo người dùng từ back-end bằng tay mà không cần mật khẩu. Bởi vì tôi chỉ có tên người dùng của người dùng.Cần tạo mã thông báo oAuth2 theo cách thủ công mà không cần mật khẩu

Bất kỳ ai cũng có thể giúp tôi.

+0

Bạn đã làm gì cho đến nay? Bạn đã thử làm điều đó một mình trước? – aribeiro

+0

Người dùng thông thường đăng nhập với người dùng/mật khẩu và mã thông báo oAuth2 đã được tạo thành công. Nhưng tôi cần phải tạo mã thông báo người dùng khác bằng cách sử dụng chương trình phụ trợ mà không cần mật khẩu. –

Trả lời

13

Đã trả lời !!!

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

    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); 
    authorities.add(new SimpleGrantedAuthority("ROLE_USER")); 

    Set<String> responseType = new HashSet<String>(); 
    responseType.add("password"); 

    Set<String> scopes = new HashSet<String>(); 
    scopes.add("read"); 
    scopes.add("write"); 

    OAuth2Request authorizationRequest = new OAuth2Request(
      authorizationParameters, "Client_Id", 
      authorities, true,scopes, null, "", 
      responseType, null); 

    User userPrincipal = new User("user", "", true, true, true, true, authorities); 

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

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

    OAuth2AccessToken accessToken = tokenService 
      .createAccessToken(authenticationRequest); 

accessToken là mã thông báo bạn muốn.

Cảm ơn

+0

Tuyệt vời, cảm ơn! –

+0

Cảm ơn rất nhiều @ChristiaanJanssen. Ngoài ra xin vui lòng upvote nếu nó có giá trị cho bạn. –

Các vấn đề liên quan