Spring 2.0.4 + OAuth2(2.0.1)/ JWT 1 +自定义userDetailsS​​ervice-> userDetailsS​​ervice的端点未被调用

时间:2018-08-15 03:51:59

标签: java rest spring-boot oauth-2.0 jwt

我正在尝试使用我自己的Custom UserDetailsS​​ervice在我的RestServices上实现spring OAuth2。我配置了所有要使用的东西,但它没有命中端点,总是给我响应:

{
    "timestamp": 1534303933352,
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/oauth/token"
}

在我的配置文件下面:

SecurityConfig

@Autowired
private UserService userDetailsService;

public SecurityConfig() {

    super(true);
}

@Bean
public PasswordEncoder passwordEncoder() {

    return new PasswordConverter();
}

@Override
protected void configure( final HttpSecurity http ) throws Exception {

    // @formatter:off
    http
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
        .and()
        .formLogin().disable()
        .httpBasic().disable()
        .csrf().disable()
        .headers().frameOptions().disable()
        .and()
        .authorizeRequests()
            .antMatchers(
                  "/"
                , "/h2-console/**"
                , "/login"
                , "/version"
                , "/sysinfo"
                , "/signup"
                , "/oauth/token" ).permitAll()
            .antMatchers("/api/**").authenticated()
    ;
    // @formatter:on
}

@Override
protected void configure( final AuthenticationManagerBuilder auth ) throws Exception {

    // @formatter:off
    auth
        .userDetailsService( userDetailsService )
        .passwordEncoder( passwordEncoder() )
    ;
    // @formatter:on
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {

    AuthenticationManager manager = super.authenticationManager();

    return manager;
}

ResourceServerConfig

@Value( "resource-id:restservice" )
private String resourceId;

@Value( "${token-validity:3600}" )
private Integer tokenValidity;

@Value( "${refresh-validity:260000}" )
private Integer refreshValidity;

@Autowired
private DefaultTokenServices tokenServices;

@Autowired
private TokenStore tokenStore;


@Override
public void configure( final ResourceServerSecurityConfigurer resources ) throws Exception {

    tokenServices.setAccessTokenValiditySeconds(tokenValidity);
    tokenServices.setRefreshTokenValiditySeconds(refreshValidity);
    // @formatter:off
    resources
        .resourceId("restservice")
        .tokenServices(tokenServices)
        .tokenStore(tokenStore)
    ;
    // @formatter:on
}

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

    // @formatter:off
    http
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
        .and()
        .formLogin().disable()
        .httpBasic().disable()
        .csrf().disable()
        .headers().frameOptions().disable()
        .and()
        .authorizeRequests()
            .antMatchers(
                  "/"
                , "/h2-console/**"
                , "/login"
                , "/version"
                , "/sysinfo"
                , "/signup"
                , "/oauth/token" ).permitAll()
            .antMatchers("/api/**").authenticated()
    ;
    // @formatter:on
}

AuthorizationServerConfig

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Value( "${singleProfileApiUIClientId:live-test}" )
private String singleProfileApiUIClientId;

@Value( "${singleProfileApiUISecret:123}" )
private String singleProfileApiUISecret;

@Value( "${signing-key:1234567890abcdef}" )
private String siginingKey;

@Value( "${token-validity:3600}" )
private Integer tokenValidity;

@Value( "${refresh-validity:260000}" )
private Integer refreshValidity;

@Value( "resource-id:restservice" )
private String resourceId;

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

@Autowired
private UserService userDetailsService;

@Override
public void configure( AuthorizationServerSecurityConfigurer serverSecurity ) throws Exception {

    // @formatter:off
    serverSecurity
        .tokenKeyAccess("permitAll()")
        .checkTokenAccess("isAuthenticated()")
    ;
    // @formatter:on
}

@Override
public void configure( final ClientDetailsServiceConfigurer clients ) throws Exception {

    // @formatter:off
    clients
        .inMemory()
            .withClient( "test" )
                .authorizedGrantTypes(
                      SysGrantTypes.PASSWORD.getType()
                    , SysGrantTypes.REFRESH_TOKEN.getType()
                    , SysGrantTypes.CLIENT_CREDENTIALS.getType())
//              .authorities( 
//                    AuthRole.ROLE_USER.getName()
//                  , AuthRole.ROLE_VIP.getName()
//                  , AuthRole.ROLE_ADMIN.getName() )
                .scopes(
                      SysScopes.READ.getName()
                    , SysScopes.WRITE.getName()
                    , SysScopes.TRUST.getName())
                .resourceIds( "restservice" )
                .secret( "123" )
                .accessTokenValiditySeconds( tokenValidity )
                .refreshTokenValiditySeconds( refreshValidity )
    ;
    // @formatter:on
}

@Override
public void configure( final AuthorizationServerEndpointsConfigurer endpoints ) throws Exception {

    // @formatter:off
    endpoints
        .authenticationManager(authenticationManager)
        .userDetailsService(userDetailsService)
        .tokenServices(tokenServices())
        .accessTokenConverter(accessTokenConverter())
    ;
    // @formatter:on
}

@Bean
@Primary
public TokenStore tokenStore() {

    JwtTokenStore tokenStore = new JwtTokenStore( accessTokenConverter() );

    return tokenStore;
}

@Bean
@Primary
public DefaultTokenServices tokenServices() {

    DefaultTokenServices tokenServices = new DefaultTokenServices();
    tokenServices.setTokenStore( tokenStore() );
    tokenServices.setSupportRefreshToken( true );
    tokenServices.setTokenEnhancer( accessTokenConverter() );

    return tokenServices;
}

@Bean
@Primary
public JwtAccessTokenConverter accessTokenConverter() {

    JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
    accessTokenConverter.setSigningKey( siginingKey );

    return accessTokenConverter;
}

要访问端点,我在Postman上使用以下有效负载:

{
    "grant_type": "password",
    "username": "test",
    "password": "123"
}

以及基本身份验证:

Authorization: Basic dGVzdDoxMjM=

我尝试使用GET和url参数获取令牌,但是我的userDetailsS​​erver从未被点击过。取而代之的是,它使用内置的Dao提供程序以及以下服务:org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsS​​ervice代替我的。

我们非常感谢您的帮助。 /年

0 个答案:

没有答案