Spring boot 如何在spring boot中使用访问令牌和授权页面流访问OAuth2 SSO保护的rest资源
我正在开发一个SpringBoot应用程序,它同时提供RESTfulAPI和SpringMVC网页(使用thymeleaf模板)。网页和RESTful API由Spring OAuth2 SSO保护。但是,当我在Java客户机中尝试从SpringRestTemplate访问RESTfulAPI时,我总是得到状态代码302和包含授权网页内容的响应正文。这意味着,restTemplate被“重定向”到授权页面,而不是使用访问令牌访问API 以下是代码和配置:Spring boot 如何在spring boot中使用访问令牌和授权页面流访问OAuth2 SSO保护的rest资源,spring-boot,oauth-2.0,single-sign-on,Spring Boot,Oauth 2.0,Single Sign On,我正在开发一个SpringBoot应用程序,它同时提供RESTfulAPI和SpringMVC网页(使用thymeleaf模板)。网页和RESTful API由Spring OAuth2 SSO保护。但是,当我在Java客户机中尝试从SpringRestTemplate访问RESTfulAPI时,我总是得到状态代码302和包含授权网页内容的响应正文。这意味着,restTemplate被“重定向”到授权页面,而不是使用访问令牌访问API 以下是代码和配置: server: port: 8888
server:
port: 8888
security:
basic:
enabled: false
ignored: /welcome,/favicon.ico,/index.html,/signup,/assets/**,/js/**,/css/**,/webjars/**
sessions: ALWAYS
oauth2:
sso:
loginPath: /login
....
security:
basic:
enabled: false
oauth2:
client:
accessTokenUri: http://jx201.local:8043/uaa/oauth/token
userAuthorizationUri: http://jx201.local:8043/uaa/oauth/authorize
clientId: payment-gateway
clientSecret: 123456
....
SecurityConfig.java(用@Configuration和@enableAuth2sso注释):
当我使用上面的java配置时,当尝试访问我的资源(如/payment/api/v1/status)时,restTemplate(OAuth2RestTemplate的实例)总是获取http代码302和授权页面的内容
但如果我使用以下代码:
http.antMatcher("/assets/**").anonymous()
.and().antMatcher("/**").authorizeRequests()
.and().csrf().requireCsrfProtectionMatcher(new RequestMatcher() {
private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
private RegexRequestMatcher apiMatcher = new RegexRequestMatcher("/[a-z0-9A-Z]*/api/v[0-9]*/.*", null);
@Override
public boolean matches(HttpServletRequest request) {
if(allowedMethods.matcher(request.getMethod()).matches()|| apiMatcher.matches(request)) {
return false;
}
return true;
}
})
.csrfTokenRepository(csrfTokenRepository()).and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
.logout().logoutUrl("/logout").permitAll()
.logoutSuccessUrl("/welcome");
例如,我的资源/payment/api/v1/status不受OAuth2和SSO的保护
所以问题是:如何配置spring安全性,使rest资源可以从restTemplate和SpringMVC访问
非常感谢
http.antMatcher("/assets/**").anonymous()
.and().antMatcher("/**").authorizeRequests()
.and().csrf().requireCsrfProtectionMatcher(new RequestMatcher() {
private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
private RegexRequestMatcher apiMatcher = new RegexRequestMatcher("/[a-z0-9A-Z]*/api/v[0-9]*/.*", null);
@Override
public boolean matches(HttpServletRequest request) {
if(allowedMethods.matcher(request.getMethod()).matches()|| apiMatcher.matches(request)) {
return false;
}
return true;
}
})
.csrfTokenRepository(csrfTokenRepository()).and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
.logout().logoutUrl("/logout").permitAll()
.logoutSuccessUrl("/welcome");