java - Neo4J TokenStore Spring oauth2

标签 java spring-security neo4j oauth-2.0 spring-security-oauth2

我正在研究使用 oauth2 保护的 Spring REST Web 服务。我想使用两个不同的应用程序将 AuthorizationServer 与 ResourceServer 分开 - AuthorizationServer 是 oauth2 SSO(单点登录),ResourceServer 是业务 REST 服务的第二个应用程序。这样我就无法使用内存 token 存储,因为我的应用程序将驻留在不同的主机上。我需要一些 TokenStore 的共享机制,例如数据库。 Spring 框架中有 JdbcTokenStore 实现,但在我的项目中我使用 Neo4J 图形数据库。

所以,我有一个问题 - 我应该尝试在 Neo4J 中存储 oauth2 token (例如创建 Neo4JTokenStore 的自定义实现(已经存在?))还是在其他数据库中?此案例的最佳实践是什么?

最佳答案

我成功实现了 Neo4j 的 token 存储。

AbstractDomainEntity.java

@NodeEntity
public abstract class AbstractDomainEntity implements DomainEntity {
    private static final long serialVersionUID = 1L;

@GraphId
private Long nodeId;

@Indexed(unique=true)
String id;

private Date createdDate;
@Indexed
private Date lastModifiedDate;
@Indexed
private String createduser;
private String lastModifieduser;

protected AbstractDomainEntity(String id) {
    this.id = id;
}

protected AbstractDomainEntity() {
}
//gets sets

OAuth2AuthenticationAccessToken.java

@NodeEntity
public class OAuth2AuthenticationAccessToken extends AbstractDomainEntity {
    private static final long serialVersionUID = -3919074495651349876L;

@Indexed
private String tokenId;
@GraphProperty(propertyType = String.class)
private OAuth2AccessToken oAuth2AccessToken;
@Indexed
private String authenticationId;
@Indexed
private String userName;
@Indexed
private String clientId;
@GraphProperty(propertyType = String.class)
private OAuth2Authentication authentication;
@Indexed
private String refreshToken;

public OAuth2AuthenticationAccessToken(){
    super();
}

public OAuth2AuthenticationAccessToken(final OAuth2AccessToken oAuth2AccessToken, final OAuth2Authentication authentication, final String authenticationId) {
    super(UUID.randomUUID().toString());
    this.tokenId = oAuth2AccessToken.getValue();
    this.oAuth2AccessToken = oAuth2AccessToken;
    this.authenticationId = authenticationId;
    this.userName = authentication.getName();
    this.clientId = authentication.getOAuth2Request().getClientId();
    this.authentication = authentication;
    this.refreshToken = oAuth2AccessToken.getRefreshToken() != null ? 

oAuth2AccessToken.getRefreshToken().getValue() : null;
    }
//getters setters

OAuth2AuthenticationRefreshToken.java

@NodeEntity
public class OAuth2AuthenticationRefreshToken extends AbstractDomainEntity {
    private static final long serialVersionUID = -3269934495553717378L;

    @Indexed
    private String tokenId;

    @GraphProperty(propertyType = String.class)
    private OAuth2RefreshToken oAuth2RefreshToken;

    @GraphProperty(propertyType = String.class)
    private OAuth2Authentication authentication;

    public OAuth2AuthenticationRefreshToken(){
        super();
    }

    public OAuth2AuthenticationRefreshToken(final OAuth2RefreshToken oAuth2RefreshToken, final OAuth2Authentication authentication) {
        super(UUID.randomUUID().toString());
        this.oAuth2RefreshToken = oAuth2RefreshToken;
        this.authentication = authentication;
        this.tokenId = oAuth2RefreshToken.getValue();
    }
//gets sets

OAuth2AccessTokenRepository.java

public interface OAuth2AccessTokenRepository extends GraphRepository<OAuth2AuthenticationAccessToken>, CypherDslRepository<OAuth2AuthenticationAccessToken>, OAuth2AccessTokenRepositoryCustom {
    public OAuth2AuthenticationAccessToken findByTokenId(String tokenId);
    public OAuth2AuthenticationAccessToken findByRefreshToken(String refreshToken);
    public OAuth2AuthenticationAccessToken findByAuthenticationId(String authenticationId);
    public List<OAuth2AuthenticationAccessToken> findByClientIdAndUserName(String clientId, String userName);
    public List<OAuth2AuthenticationAccessToken> findByClientId(String clientId);
}

OAuth2RefreshTokenRepository.java

public interface OAuth2RefreshTokenRepository extends GraphRepository<OAuth2AuthenticationRefreshToken>, CypherDslRepository<OAuth2AuthenticationRefreshToken>, OAuth2RefreshTokenRepositoryCustom {
    public OAuth2AuthenticationRefreshToken findByTokenId(String tokenId);
}

OAuth2TokenStoreRepositoryImpl.java

public class OAuth2TokenStoreRepositoryImpl implements TokenStore {
    @Autowired
    private OAuth2AccessTokenRepository oAuth2AccessTokenRepository;
    @Autowired
    private OAuth2RefreshTokenRepository oAuth2RefreshTokenRepository;
    private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator();

    /* (non-Javadoc)
     * @see org.springframework.security.oauth2.provider.token.TokenStore#readAuthentication(org.springframework.security.oauth2.common.OAuth2AccessToken)
     */
    @Override
    public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
        return readAuthentication(token.getValue());
    }

    /* (non-Javadoc)
     * @see org.springframework.security.oauth2.provider.token.TokenStore#readAuthentication(java.lang.String)
     */
    @Override
    public OAuth2Authentication readAuthentication(String tokenId) {
        OAuth2AuthenticationAccessToken accessToken = oAuth2AccessTokenRepository.findByTokenId(tokenId);
        OAuth2Authentication oauth2Authentication = null;
        if(accessToken != null){
            oauth2Authentication = accessToken.getAuthentication();
        }
        return oauth2Authentication;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.oauth2.provider.token.TokenStore#storeAccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken, org.springframework.security.oauth2.provider.OAuth2Authentication)
     */
    @Override
    public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
        // remove existing token & add new
        removeAccessToken(token);

        OAuth2AuthenticationAccessToken oAuth2AuthenticationAccessToken = new OAuth2AuthenticationAccessToken(token,
                authentication, authenticationKeyGenerator.extractKey(authentication));
        oAuth2AccessTokenRepository.save(oAuth2AuthenticationAccessToken);
    }

    /* (non-Javadoc)
     * @see org.springframework.security.oauth2.provider.token.TokenStore#readAccessToken(java.lang.String)
     */
    @Override
    public OAuth2AccessToken readAccessToken(String tokenValue) {
        OAuth2AuthenticationAccessToken token = oAuth2AccessTokenRepository.findByTokenId(tokenValue);
        if(token == null) {
            return null; //let spring security handle the invalid token
        }
        OAuth2AccessToken accessToken = token.getoAuth2AccessToken();
        return accessToken;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.oauth2.provider.token.TokenStore#removeAccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken)
     */
    @Override
    public void removeAccessToken(OAuth2AccessToken token) {
        OAuth2AuthenticationAccessToken accessToken = oAuth2AccessTokenRepository.findByTokenId(token.getValue());
        if(accessToken != null) {
            oAuth2AccessTokenRepository.delete(accessToken);
        }

    }

    /* (non-Javadoc)
     * @see org.springframework.security.oauth2.provider.token.TokenStore#storeRefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken, org.springframework.security.oauth2.provider.OAuth2Authentication)
     */
    @Override
    public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
        oAuth2RefreshTokenRepository.save(new OAuth2AuthenticationRefreshToken(refreshToken, authentication));

    }

    /* (non-Javadoc)
     * @see org.springframework.security.oauth2.provider.token.TokenStore#readRefreshToken(java.lang.String)
     */
    @Override
    public OAuth2RefreshToken readRefreshToken(String tokenValue) {
        OAuth2AuthenticationRefreshToken refreshAuth = oAuth2RefreshTokenRepository.findByTokenId(tokenValue);
        OAuth2RefreshToken refreshToken = null;
        if(refreshAuth != null){
            refreshToken = refreshAuth.getoAuth2RefreshToken();
        }
        return refreshToken;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.oauth2.provider.token.TokenStore#readAuthenticationForRefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken)
     */
    @Override
    public OAuth2Authentication readAuthenticationForRefreshToken( OAuth2RefreshToken token) {
        OAuth2AuthenticationRefreshToken refreshAuth = oAuth2RefreshTokenRepository.findByTokenId(token.getValue());
        OAuth2Authentication oAuth2Authentication = null;
        if(refreshAuth != null){
            oAuth2Authentication = refreshAuth.getAuthentication();
        }
        return oAuth2Authentication;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.oauth2.provider.token.TokenStore#removeRefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken)
     */
    @Override
    public void removeRefreshToken(OAuth2RefreshToken token) {
        OAuth2AuthenticationRefreshToken refreshAuth = oAuth2RefreshTokenRepository.findByTokenId(token.getValue());
        if(refreshAuth != null){
            oAuth2RefreshTokenRepository.delete(refreshAuth);
        }
    }

    /* (non-Javadoc)
     * @see org.springframework.security.oauth2.provider.token.TokenStore#removeAccessTokenUsingRefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken)
     */
    @Override
    public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
        OAuth2AuthenticationAccessToken accessToken = oAuth2AccessTokenRepository.findByRefreshToken(refreshToken.getValue());
        if(accessToken != null){
            oAuth2AccessTokenRepository.delete(accessToken);
        }
    }

    /* (non-Javadoc)
     * @see org.springframework.security.oauth2.provider.token.TokenStore#getAccessToken(org.springframework.security.oauth2.provider.OAuth2Authentication)
     */
    @Override
    public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
        OAuth2AuthenticationAccessToken token =  oAuth2AccessTokenRepository.findByAuthenticationId(authenticationKeyGenerator.extractKey(authentication));
        return token == null ? null : token.getoAuth2AccessToken();
    }

    /* (non-Javadoc)
     * @see org.springframework.security.oauth2.provider.token.TokenStore#findTokensByClientIdAndUserName(java.lang.String, java.lang.String)
     */
    @Override
    public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
        List<OAuth2AuthenticationAccessToken> tokens = oAuth2AccessTokenRepository.findByClientIdAndUserName(clientId, userName);
        return extractAccessTokens(tokens);
    }

    /* (non-Javadoc)
     * @see org.springframework.security.oauth2.provider.token.TokenStore#findTokensByClientId(java.lang.String)
     */
    @Override
    public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
        List<OAuth2AuthenticationAccessToken> tokens = oAuth2AccessTokenRepository.findByClientId(clientId);
        return extractAccessTokens(tokens);
    }

    private Collection<OAuth2AccessToken> extractAccessTokens(List<OAuth2AuthenticationAccessToken> tokens) {
        List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>();
        for(OAuth2AuthenticationAccessToken token : tokens) {
            accessTokens.add(token.getoAuth2AccessToken());
        }
        return accessTokens;
    }
}

我使用 GraphProperty 将 OAuth2AuthenticationAccessToken.java 和 OAuth2AuthenticationAccessToken.java 中的两个对象 OAuth2AccessToken 和 OAuth2Authentication 的 String 转换如下。

@GraphProperty(propertyType = String.class)
private OAuth2AccessToken oAuth2AccessToken;

@GraphProperty(propertyType = String.class)
private OAuth2Authentication authentication;

所以,我为它们实现了四个转换器

public class OAuth2AccessTokenToStringConverter implements Converter<OAuth2AccessToken, String> {

    @Override
    public String convert(final OAuth2AccessToken source) {
        //some code that takes your object and returns a String
        ObjectMapper mapper = new ObjectMapper();
        String json = null;
        try {
            json = mapper.writeValueAsString(source);
            //remove white space
            json = json.replace("\"scope\":\" ","\"scope\":\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }
}

public class OAuth2AuthenticationToStringConverter implements Converter<OAuth2Authentication, String> {

    @Override
    public  String convert(final OAuth2Authentication source) {
        //some code that takes your object and returns a String
        ObjectMapper mapper = new ObjectMapper();
        String json = null;
        try {
            json = mapper.writeValueAsString(source);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }
}


public class StringToOAuth2AccessTokenConverter implements Converter<String, OAuth2AccessToken> {

    @Override
    public OAuth2AccessToken convert(final String source) {
        //some code that takes a String and returns an object of your type
        ObjectMapper mapper = new ObjectMapper();
        OAuth2AccessToken deserialised = null;
        try {
            deserialised = mapper.readValue(source, OAuth2AccessToken.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return deserialised;
    }
}


public class StringToOAuth2AuthenticationConverter implements Converter<String, OAuth2Authentication> {

    @Override
    public OAuth2Authentication convert(final String source) {
        // some code that takes a String and returns an object of your type
        OAuth2Authentication oAuth2Authentication = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode  rootNode = mapper.readTree(source);
            OAuth2Request oAuth2Request = getOAuth2Request(rootNode.get("oauth2Request"), mapper);
            JsonNode userAuthentication = rootNode.get("userAuthentication");
            JsonNode principal = userAuthentication.get("principal");
            UserAccount userAccount = mapper.readValue(principal.get("userAccount"), UserAccount.class);
            CTGUserDetails userDetails = new CTGUserDetails(userAccount);
            List<Map<String, String>> authorities = mapper.readValue(userAuthentication.get("authorities"), new TypeReference<List<Map<String, String>>>() {});
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, getAuthorities(authorities));
            oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return oAuth2Authentication;
    }

    private OAuth2Request getOAuth2Request(final JsonNode jsonNode, ObjectMapper mapper) throws JsonParseException, JsonMappingException, IOException{
        Map<String, String> requestParameters = mapper.readValue(jsonNode.get("requestParameters"),new TypeReference<Map<String, String>>() {});
        String clientId = jsonNode.get("clientId").getTextValue();
        List<Map<String, String>> authorities = mapper.readValue(jsonNode.get("authorities"), new TypeReference<List<Map<String, String>>>() {});
        Set<String> scope = mapper.readValue(jsonNode.get("scope"), new TypeReference<HashSet<String>>() {});
        Set<String> resourceIds =   mapper.readValue(jsonNode.get("resourceIds"), new TypeReference<HashSet<String>>() {});
        return new OAuth2Request(requestParameters, clientId, getAuthorities(authorities) , true, scope, resourceIds, null, null, null);
    }

    private Collection<? extends GrantedAuthority> getAuthorities(
            List<Map<String, String>> authorities) {
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(authorities.size());
        for (Map<String, String> authority : authorities) {
            grantedAuthorities.add(new SimpleGrantedAuthority(authority.get("authority")));
        }
        return grantedAuthorities;
    }

}

在bean xml中,我向Spring声明如下:

<bean id="conversionService" 
      class="org.springframework.context.support.ConversionServiceFactoryBean">
      <property name="converters">
        <set>
          <bean class="com.<yourpackage>.convertor.OAuth2AuthenticationToStringConverter"/>
          <bean class="com.<yourpackage>.convertor.OAuth2AccessTokenToStringConverter"/>
          <bean class="com.<yourpackage>.convertor.StringToOAuth2AccessTokenConverter"/>
          <bean class="com.<yourpackage>.convertor.StringToOAuth2AuthenticationConverter"/>
        </set>
      </property>
    </bean>

结束。 :) 欢迎任何反馈。

关于java - Neo4J TokenStore Spring oauth2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28399712/

相关文章:

java - 无法在 Play 框架中加载项目

java - 如何从另一台服务器获取请求url到spring mvc Controller 中

Java字符串操作

java - Spring data neo4j无法连接neo4j 2.2.1

java - java中解析json数组字符串

grails - 如何从失败的登录尝试中获取 url 参数

Spring Security 阻塞 Rest Controller

java - spring security Rest API错误-403禁止

java - 如何为嵌入式 Neo4j 数据库执行 Gremlin 脚本?

neo4j - 如何通过 REST API 查看 Neo4j 的 DELETE 是否成功?