gpt4 book ai didi

java - 带有 Spring Boot REST 应用程序的 OAuth2 - 无法使用 token 访问资源

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:40:10 25 4
gpt4 key购买 nike

我想为我的 REST spring boot 项目使用 OAuth2。使用一些示例,我为 OAuth2 创建了配置:

@Configuration
public class OAuth2Configuration {

private static final String RESOURCE_ID = "restservice";

@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends
ResourceServerConfigurerAdapter {

@Override
public void configure(ResourceServerSecurityConfigurer resources) {
// @formatter:off
resources
.resourceId(RESOURCE_ID);
// @formatter:on
}

@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.anonymous().disable()
.authorizeRequests().anyRequest().authenticated();
// @formatter:on
}

}

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends
AuthorizationServerConfigurerAdapter {

private TokenStore tokenStore = new InMemoryTokenStore();

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

@Autowired
private UserDetailsServiceImpl userDetailsService;

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
// @formatter:off
endpoints
.tokenStore(this.tokenStore)
.authenticationManager(this.authenticationManager)
.userDetailsService(userDetailsService);
// @formatter:on
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// @formatter:off
clients
.inMemory()
.withClient("clientapp")
.authorizedGrantTypes("password", "refresh_token", "trust")
.authorities("USER")
.scopes("read", "write")
.resourceIds(RESOURCE_ID)
.secret("clientsecret")
.accessTokenValiditySeconds(1200)
.refreshTokenValiditySeconds(3600);
// @formatter:on
}

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

这是我的 SecurityConfiguration 类:

@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http
.authorizeRequests().antMatchers("/api/register").permitAll()
.and()
.authorizeRequests().antMatchers("/api/free").permitAll()
.and()
.authorizeRequests().antMatchers("/oauth/token").permitAll()
.and()
.authorizeRequests().antMatchers("/api/secured").hasRole("USER")
.and()
.authorizeRequests().anyRequest().authenticated();
}

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

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

}

我尝试通过 2 个简单的请求来检查我的应用程序:

@RequestMapping(value = "/api/secured", method = RequestMethod.GET)
public String checkSecured(){
return "Authorization is ok";
}

@RequestMapping(value = "/api/free", method = RequestMethod.GET)
public String checkFree(){
return "Free from authorization";
}

首先我检查了两个请求:

/api/free 返回代码 200 和字符串“Free from authorization”

/api/secured 返回 {"timestamp":1487451065106,"status":403,"error":"Forbidden","message":"Access Denied","path":"/api/安全”

看起来它们工作正常。

然后我得到了 access_token(使用我的用户数据库中的凭据)

/oauth/token?grant_type=password&username=emaila&password=emailo

响应:

{"access_token":"3344669f-c66c-4161-9516-d7e2f31a32e8","token_type":"bearer","re​​fresh_token":"c71c17e4-45ba-458c-9d98-574de33d1859","expires_in":1199, “范围”:“读写”

然后我尝试为需要身份验证的资源发送请求(使用我获得的 token ):

/api/secured?access_token=3344669f-c66c-4161-9516-d7e2f31a32e8

这是回应:

{"timestamp":1487451630224,"status":403,"error":"Forbidden","message":"Access Denied","path":"/api/secured"}

我不明白为什么访问被拒绝。我不确定配置,而且它们似乎不正确。此外,我仍然不清楚扩展 WebSecurityConfigurerAdapter 的类和扩展 ResourceServerConfigurerAdapter 的类中方法 configure(HttpSecurity http) 的关系。感谢您的帮助!

最佳答案

如果您使用的是 spring boot 1.5.1 或最近更新到它,请注意它们更改了 spring security oauth2 ( Spring Boot 1.5 Release Notes ) 的过滤器顺序。

根据发行说明,尝试将以下属性添加到 application.properties/yml,之后资源服务器过滤器将在您的其他过滤器之后用作回退 - 这应该会导致授权在失败之前被接受到资源服务器:

security.oauth2.resource.filter-order = 3

您可以在这里找到其他问题的良好答案:https://stackoverflow.com/questions/28537181

关于java - 带有 Spring Boot REST 应用程序的 OAuth2 - 无法使用 token 访问资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42320756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com