5

Ho implementato oAuth2 con la sicurezza Spring e funziona correttamente per me. Ma ora voglio creare un token utente dal back-end manualmente senza password. Perché ho solo il nome utente dell'utente.È necessario creare il token oAuth2 manualmente senza password

Qualcuno può aiutarmi.

+0

Che cosa hai fatto finora? Hai provato a farlo da solo prima? – aribeiro

+0

L'utente normale accede con utente/password e il token oAuth2 è stato creato correttamente. Ma ho bisogno di creare un altro token utente usando il back-end senza password. –

risposta

13

Hai una risposta !!!

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 è token che si desidera.

Grazie

+0

Fantastico, grazie! –

+0

Grazie mille @ChristiaanJanssen. Inoltre, si prega di upvotare se è prezioso per te. –

Problemi correlati