Java Neo4J代币存储弹簧oauth2

Java Neo4J代币存储弹簧oauth2,java,spring-security,neo4j,oauth-2.0,spring-security-oauth2,Java,Spring Security,Neo4j,Oauth 2.0,Spring Security Oauth2,我正在使用oauth2保护SpringRESTWebServices。我想用两个不同的应用程序将AuthorizationServer与ResourceServer分开—AuthorizationServer是oauth2 SSO(单点登录),ResourceServer是business REST服务的第二个应用程序。这样我就不能使用inmemory tokenstore,因为我的应用程序将位于不同的主机上。我需要一些令牌存储的共享机制,例如数据库。Spring框架中有JdbcTokenSto

我正在使用oauth2保护SpringRESTWebServices。我想用两个不同的应用程序将AuthorizationServer与ResourceServer分开—AuthorizationServer是oauth2 SSO(单点登录),ResourceServer是business REST服务的第二个应用程序。这样我就不能使用inmemory tokenstore,因为我的应用程序将位于不同的主机上。我需要一些令牌存储的共享机制,例如数据库。Spring框架中有JdbcTokenStore实现,但在我的项目中,我使用的是Neo4J图形数据库


因此,我有一个问题-我应该尝试将oauth2令牌存储在Neo4J中(例如,创建Neo4JTokenStore的自定义实现(已经存在?)还是存储在其他数据库中?这种情况下的最佳实践是什么?

如果您只想在项目中使用Neo4j,我会为Neo4j实现令牌存储(以及开源it),我认为这应该是非常简单的

如果您已经使用了其他数据库,那么您也可以使用它们的存储


问题是,您是否必须将oauth2令牌与图形中的任何东西连接起来???

我成功地为Neo4j实现了令牌存储

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
@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
OAuth2AuthenticationRefreshToken.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
@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);
}
public interface OAuth2RefreshTokenRepository extends GraphRepository<OAuth2AuthenticationRefreshToken>, CypherDslRepository<OAuth2AuthenticationRefreshToken>, OAuth2RefreshTokenRepositoryCustom {
    public OAuth2AuthenticationRefreshToken findByTokenId(String tokenId);
}
所以,我为他们实现了四个转换器

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;
    }

}
公共类OAuth2Access TokenToString Converter实现转换器{
@凌驾
公共字符串转换(最终OAuth2AccessToken源){
//获取对象并返回字符串的代码
ObjectMapper mapper=新的ObjectMapper();
字符串json=null;
试一试{
json=mapper.writeValueAsString(源代码);
//删除空白
json=json.replace(“\”范围\“:\”,“\”范围\“:\”);
}捕获(IOE异常){
e、 printStackTrace();
}
返回json;
}
}
公共类OAuth2AuthenticationToStringConverter实现转换器{
@凌驾
公共字符串转换(最终OAuth2Authentication源){
//获取对象并返回字符串的代码
ObjectMapper mapper=新的ObjectMapper();
字符串json=null;
试一试{
json=mapper.writeValueAsString(源代码);
}捕获(IOE异常){
e、 printStackTrace();
}
返回json;
}
}
公共类StringToAuth2AccessTokenConverter实现转换器{
@凌驾
公共OAuth2AccessToken转换(最终字符串源){
//一些接受字符串并返回您类型的对象的代码
ObjectMapper mapper=新的ObjectMapper();
OAuth2AccessToken反序列化=null;
试一试{
反序列化=mapper.readValue(源,OAuth2AccessToken.class);
}捕获(IOE异常){
e、 printStackTrace();
}
返回反序列化;
}
}
公共类StringToAuth2AuthenticationConverter实现转换器{
@凌驾
公共OAuth2Authentication转换(最终字符串源){
//一些接受字符串并返回您类型的对象的代码
OAuth2Authentication OAuth2Authentication=null;
试一试{
ObjectMapper mapper=新的ObjectMapper();
JsonNode rootNode=mapper.readTree(源代码);
OAuth2Request OAuth2Request=getOAuth2Request(rootNode.get(“OAuth2Request”),映射程序);
JsonNode userAuthentication=rootNode.get(“userAuthentication”);
JsonNode principal=userAuthentication.get(“principal”);
UserAccount UserAccount=mapper.readValue(principal.get(“UserAccount”),UserAccount.class);
CTGUserDetails userDetails=新的CTGUserDetails(userAccount);
List authorities=mapper.readValue(userAuthentication.get(“authorities”),new TypeReference(){});
UsernamePasswordAuthenticationToken authentication=新的UsernamePasswordAuthenticationToken(userDetails,null,GetAuthories(Authories));
oAuth2Authentication=新的oAuth2Authentication(oAuth2Request,身份验证);
}捕获(IOE异常){
e、 printStackTrace();
}
返回oAuth2Authentication;
}
私有OAuth2Request getOAuth2Request(最终JsonNode JsonNode、ObjectMapper映射器)抛出JsonParseException、JsonMappingException、IOException{
Map requestParameters=mapper.readValue(jsonNode.get(“requestParameters”),new-TypeReference(){});
字符串clientId=jsonNode.get(“clientId”).getTextValue();
List authorities=mapper.readValue(jsonNode.get(“authorities”),new TypeReference(){});
Set scope=mapper.readValue(jsonNode.get(“scope”),new TypeReference(){});
设置resourceIds=mapper.readValue(jsonNode.get(“resourceIds”),new TypeReference(){});
返回新的OAuth2Request(requestParameters、clientId、getAuthories(authorities)、true、scope、resourceId、null、null);
}
私人收藏

结束:)欢迎任何反馈。

不需要将令牌存储到数据库中。将令牌存储到内存中

请参阅我的OAuth2配置文件

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.web.context.request.RequestContextListener;

/**
 * OAuth2 authentication configuration
 */
@Configuration
public class OAuth2Configuration {

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Autowired
        private CustomLogoutSuccessHandler customLogoutSuccessHandler;

        @Override
        public void configure(HttpSecurity http) throws Exception {

            http
            .csrf().disable()
            .exceptionHandling()
            .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().logout().logoutUrl("/oauth/logout").logoutSuccessHandler(customLogoutSuccessHandler)
            .and().authorizeRequests()
            .antMatchers("/api/v1/**").access("#oauth2.clientHasAnyRole('ROLE_USER')");
        }
    }

    @Bean 
    public RequestContextListener requestContextListener(){
        return new RequestContextListener();
    } 

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        private static final String PROP_CLIENTID = "client";
        private static final String PROP_SECRET = "secret";
        private static final int PROP_TOKEN_VALIDITY_SECONDS = 60 * 60 * 12;

        @Bean
        public TokenStore tokenStore() {
            return new InMemoryTokenStore();
        }

        @Autowired
        @Qualifier("myAuthenticationManager")
        private AuthenticationManager authenticationManager;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints
                .tokenStore(tokenStore())
                .authenticationManager(authenticationManager);

        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients
                    .inMemory()
                    .withClient(PROP_CLIENTID)
                    .scopes("read", "write", "trust")
                    .authorities("ROLE_USER")
                    .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")                    
                    .secret(PROP_SECRET)
                    .accessTokenValiditySeconds(PROP_TOKEN_VALIDITY_SECONDS);
        }

        @Bean
        @Primary
        public DefaultTokenServices tokenServices() {
            DefaultTokenServices tokenServices = new DefaultTokenServices();
            tokenServices.setSupportRefreshToken(true);
            tokenServices.setTokenStore(tokenStore());
            return tokenServices;
        }
    }

}

这对我有用!!

这在集群中不起作用,在内存中应该用于测试
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.web.context.request.RequestContextListener;

/**
 * OAuth2 authentication configuration
 */
@Configuration
public class OAuth2Configuration {

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Autowired
        private CustomLogoutSuccessHandler customLogoutSuccessHandler;

        @Override
        public void configure(HttpSecurity http) throws Exception {

            http
            .csrf().disable()
            .exceptionHandling()
            .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().logout().logoutUrl("/oauth/logout").logoutSuccessHandler(customLogoutSuccessHandler)
            .and().authorizeRequests()
            .antMatchers("/api/v1/**").access("#oauth2.clientHasAnyRole('ROLE_USER')");
        }
    }

    @Bean 
    public RequestContextListener requestContextListener(){
        return new RequestContextListener();
    } 

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        private static final String PROP_CLIENTID = "client";
        private static final String PROP_SECRET = "secret";
        private static final int PROP_TOKEN_VALIDITY_SECONDS = 60 * 60 * 12;

        @Bean
        public TokenStore tokenStore() {
            return new InMemoryTokenStore();
        }

        @Autowired
        @Qualifier("myAuthenticationManager")
        private AuthenticationManager authenticationManager;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints
                .tokenStore(tokenStore())
                .authenticationManager(authenticationManager);

        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients
                    .inMemory()
                    .withClient(PROP_CLIENTID)
                    .scopes("read", "write", "trust")
                    .authorities("ROLE_USER")
                    .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")                    
                    .secret(PROP_SECRET)
                    .accessTokenValiditySeconds(PROP_TOKEN_VALIDITY_SECONDS);
        }

        @Bean
        @Primary
        public DefaultTokenServices tokenServices() {
            DefaultTokenServices tokenServices = new DefaultTokenServices();
            tokenServices.setSupportRefreshToken(true);
            tokenServices.setTokenStore(tokenStore());
            return tokenServices;
        }
    }

}