需要手动创建oAuth2令牌而无需密码

Cha*_*ngh 7 spring-mvc spring-security oauth-2.0 spring-boot spring-security-oauth2

我已经实现了oAuth2和spring security,它对我来说很好.但现在我想手动从后端手动创建用户令牌而无需密码.因为我只有用户名.

谁能帮我.

Cha*_*ngh 16

得到答案!!!

    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);
Run Code Online (Sandbox Code Playgroud)

accessToken是您想要的令牌.

谢谢