【问题标题】:spring rest security oauth unsupported grant typespring rest security oauth 不支持的授权类型
【发布时间】:2015-10-30 21:57:24
【问题描述】:

我在自己的项目中苦苦挣扎,试图配置 Spring Rest 安全性和 oauth。有人可能会说这个简单的项目不需要 oauth,但我想实践一下。

我想从端点获取刷新和访问令牌,但出现错误: 不支持的授权类型:密码。 我在互联网上搜索,但找不到针对我的具体问题的解决方案。

curl -u client:123456 http://localhost:8080/artwork/oauth/token -d 'grant_type=password&username=rest&password=rest' -X POST -H "Content-Type:application/x-www-form-urlencoded" -v

但是当我使用授权类型调用它时:client_credentials 它会返回访问令牌,但正如我所提到的,我也需要刷新令牌。

这是我不完全理解整个oauth的az选项,但我正在阅读它。

@Autowired
private CustomUsersDetailService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
    .withUser("rest")  
        .password("rest")
        .roles("REST")
        .and()
    .withUser("historian") 
        .password("historian")
        .roles("HIS");
}

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}   

private static final String RESOURCE_ID = "restservice";

@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends
        ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {         
        resources
            .resourceId(RESOURCE_ID);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {         
        http
        .authorizeRequests().antMatchers("/oauth/token").permitAll()
        .and()
        .authorizeRequests().antMatchers("/**").access("hasRole('ROLE_HIS') or hasRole('ROLE_REST')");                          
    }

}

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends
        AuthorizationServerConfigurerAdapter {

    private TokenStore tokenStore = new InMemoryTokenStore();

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

    @Autowired
    private CustomUsersDetailService userDetailsService;

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

    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
            .inMemory()
                .withClient("client")
                    .authorizedGrantTypes("password","refresh_token","client_credentials","authorization_code")
                    .authorities("ROLE_REST")
                    .scopes("read", "write")
                    .resourceIds(RESOURCE_ID)
                    .secret("123456");
    }

前端的代码,就是post方法:

 $scope.post = function() {

        var config = {
                 method: 'POST',
                 url: 'http://localhost:8080/artwork/oauth/token',
                 headers: {
                     'Content-Type': 'application/x-www-form-urlencoded',
                     'Authorization' : "Basic " + Base64.encode("client:123456")
                 },
                 params: {                      
                     grant_type: "password",
                     username: "rest",
                     password: "rest"
                 }
        }

        $http(config).success(onsuc).error(error);
    };

如果你看到了什么,请告诉我。 谢谢!

【问题讨论】:

  • 您找到问题的答案了吗?我现在面临同样的问题。
  • 我也想知道,我也面临同样的问题@Maksim

标签: spring rest oauth


【解决方案1】:

您可以定义应包含 RefreshTokenGranter 的复合令牌授予者。此示例可以帮助您。

@Configuration
@EnableAuthorizationServer
public class SecurityOauth2Config extends AuthorizationServerConfigurerAdapter  { 

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

        endpoints
            .tokenServices(authorizationServerTokenServices())
            .tokenStore(tokenStore())
            .tokenGranter(tokenGranter())
            .requestFactory(oAuth2RequestFactory())
            .setClientDetailsService(clientDetailsJdbcService());

    }


    @Bean
    public TokenGranter tokenGranter() {

        ClientDetailsService clientDetails = clientDetailsJdbcService();
        AuthorizationServerTokenServices tokenServices = authorizationServerTokenServices();
        AuthenticationManager authenticationManager = authenticationManagerOauth2User();

        OAuth2RequestFactory oAuth2RequestFactory = oAuth2RequestFactory();

        List<TokenGranter> tokenGranters = new ArrayList<TokenGranter>();

        tokenGranters.add(new RefreshTokenGranter(tokenServices, clientDetails, oAuth2RequestFactory));
        tokenGranters.add(new ImplicitTokenGranter(tokenServices, clientDetails, oAuth2RequestFactory));
        tokenGranters.add(new ClientCredentialsTokenGranter(tokenServices, clientDetails, oAuth2RequestFactory));

        tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices,
                    clientDetails, oAuth2RequestFactory));

        return new CompositeTokenGranter(tokenGranters);
    }
...

【讨论】:

    【解决方案2】:

    为了获得刷新令牌,您需要将您的客户端配置为refresh_token 授权类型。

    @Override
            public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
                // TODO Auto-generated method stub
                clients.inMemory()
                .withClient("foo")
                .secret("{noop}bar")
                .authorizedGrantTypes("password", "authorization_code", "refresh_token","client_credentials")
    
                .authorities("ROLE_CLIENT","ROLE_TRUSTED_CLIENT")
    
                .scopes("read", "write","trust","openid")
    
                .accessTokenValiditySeconds(120).//Access token is only valid for 2 minutes.
    
                refreshTokenValiditySeconds(600);//Refresh token is only valid for 10 minutes.
    
            }
    

    以上代码摘自another stackoverflow question

    【讨论】:

      猜你喜欢
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 2013-12-01
      • 2013-03-15
      • 2018-09-07
      • 1970-01-01
      • 2017-09-18
      • 1970-01-01
      相关资源
      最近更新 更多