spring-attic / spring-social

Allows you to connect your applications with SaaS providers such as Facebook and Twitter.

Home Page:http://projects.spring.io/spring-social

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Spring Boot OAuth2 manually create new JWT token

Artgit opened this issue · comments

At my Spring Boot application I have configured Spring OAuth2 server with JWT tokens.

Also I have added Spring Social configuration in order to be able authenticate users via various Social Networks like Twitter, Facebook and so on.

This is my SpringSocial config:

@Configuration
@EnableSocial
public class SocialConfig extends SocialConfigurerAdapter {

	@Bean
	public ProviderSignInController providerSignInController(ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository usersConnectionRepository) {
	    return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new SimpleSignInAdapter(authTokenServices, "client_id", userService));
	}

...

}

Also, based on the folksinging answer http://stackoverflow.com/questions/32313821/integrate-spring-security-oauth2-and-spring-social I have implemented SimpleSignInAdapter in order to handle successful authentication with 3rdparty Social Networks:

public class SimpleSignInAdapter implements SignInAdapter {
	
	final static Logger logger = LoggerFactory.getLogger(SimpleSignInAdapter.class);

	public static final String REDIRECT_PATH_BASE = "/#/login";
    public static final String FIELD_TOKEN = "access_token";
    public static final String FIELD_EXPIRATION_SECS = "expires_in";
	
    private final AuthorizationServerTokenServices authTokenServices;
    private final String localClientId;
    private final UserService userService;
    
    public SimpleSignInAdapter(AuthorizationServerTokenServices authTokenServices, String localClientId, UserService userService){
        this.authTokenServices = authTokenServices;
        this.localClientId = localClientId;
		this.userService = userService;
    }
    
	@Override
	public String signIn(String userId, Connection<?> connection, NativeWebRequest request) {
		
		UserDetails userDetails = loadUserById(Long.parseLong(userId));
		
		OAuth2AccessToken oauth2Token = authTokenServices.createAccessToken(convertAuthentication(userDetails)); 
        String redirectUrl = new StringBuilder(REDIRECT_PATH_BASE)
            .append("?").append(FIELD_TOKEN).append("=")
            .append(encode(oauth2Token.getValue()))
            .append("&").append(FIELD_EXPIRATION_SECS).append("=")
            .append(oauth2Token.getExpiresIn())
            .toString();	
        
		return redirectUrl;
	}

	private OAuth2Authentication convertAuthentication(UserDetails userDetails) {
		OAuth2Request request = new OAuth2Request(null, localClientId, null, true, null, null, null, null, null);
		return new OAuth2Authentication(request, new UsernamePasswordAuthenticationToken(userDetails, "N/A", userDetails.getAuthorities()));
	}
	
	private String encode(String in) {
        String res = in;
        try {
            res = UriUtils.encode(in, "UTF-8");
        } catch(UnsupportedEncodingException e){
        	logger.error("ERROR: unsupported encoding: " + "UTF-8", e);
        }
        return res;
    }
	
	public UserDetails loadUserById(Long id) throws UsernameNotFoundException {
		User user = userService.findUserById(id);
		if (user == null) {
			throw new UsernameNotFoundException("User " + id + " not found.");
		}

		Set<Permission> permissions = userService.getUserPermissions(user);
		return new DBUserDetails(user, permissions);
	}

}

Everything works fine except one thing - the following line of code produces plain OAuth2 access token:

OAuth2AccessToken oauth2Token = authTokenServices.createAccessToken(convertAuthentication(userDetails));

but I need to create JWT token instead.

How to create or convert this token to JWT based ? I suppose I can use JwtAccessTokenConverter class for this purpose but don't know how at this moment. Please help. Thanks!

Quite late I guess but .. did you found how to do it? ;)

Never mind, solved it on my own :)

Haha :))