Spring Oauth2 - 覆盖 TokenEndpoint 允许的方法

Spring Oauth2 - override TokenEndpoint allowed methods

我需要允许用户通过 grant_type=password 并使用 GET 而不是 POST 获取 OAuth 令牌。 TokenEndpoint的默认实现如下:

public class TokenEndpoint extends AbstractEndpoint {

private OAuth2RequestValidator oAuth2RequestValidator = new DefaultOAuth2RequestValidator();

private Set<HttpMethod> allowedRequestMethods = new HashSet<HttpMethod>(Arrays.asList(HttpMethod.POST));

@RequestMapping(value = "/oauth/token", method=RequestMethod.GET)
public ResponseEntity<OAuth2AccessToken> getAccessToken(Principal principal, @RequestParam
Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
    if (!allowedRequestMethods.contains(HttpMethod.GET)) {
        throw new HttpRequestMethodNotSupportedException("GET");
    }
    return postAccessToken(principal, parameters);
}

如您所见,默认只允许 POST。我正在使用 XML 配置(不是注释)。如何将 HttpMethod.GET?

添加到集合中

以下配置有效:

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints
                .requestFactory(defaultOAuth2RequestFactory)
                .authenticationManager(myUserAuthenticationManager)
                .tokenStore(myTokenStore)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);// to allow get for password grant
            ;

        }
@Override
        public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
            security
                .realm(REALM)
                .allowFormAuthenticationForClients()// to let users do password grant with username/ password on get
                ;
        }

仅 XML 配置无法配置允许的令牌端点方法。

你有两个选择:

  • 将所有内容移至 Java 配置(作为清单的答案)
  • 创建一个额外的配置 class,它将 运行 在 XML 具有 运行 之后的 @PostConstruct 方法来完成工作。

Java 配置可能是您应该为新应用使用的配置,但如果您有一个使用 XML 配置的旧应用,那么像这样的东西将起作用:

@Configuration
public class AllowedMethodConfig {
    @Autowired
    private TokenEndpoint tokenEndpoint;

    @PostConstruct
    public void reconfigure() {
        Set<HttpMethod> allowedMethods =
            new HashSet<>(Arrays.asList(HttpMethod.GET, HttpMethod.POST));
        tokenEndpoint.setAllowedRequestMethods(allowedMethods);
    }
}