我正在尝试使用 @EnableAuthorizationServer
和内存客户端在 Spring Boot 中为 OAuth2 授权服务器开发一个简单的 POC。
我的网络安全配置类如下所示:
package com.example.authservice;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**")
.authorizeRequests().
antMatchers("/", "/login**", "/oauth/authorize", "/oauth/authorize**")
.permitAll().
anyRequest()
.authenticated();
}
}
授权服务器配置如下:
package com.example.authservice;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().
withClient("auth-client").
secret("secret-key").
authorizedGrantTypes("authorization_code").
scopes("openid");
}
}
这是基于授权代码授予流程,当我尝试获取代码(将在下一次调用中使用以获取访问 token )时,我收到未经授权的错误。
curl -X GET \
'http://localhost:8080/oauth/authorize?client_id=auth-client&client_secret=secret-key&grant_type=authorization_code&response_type=code'
错误:
{
"timestamp": "2019-03-20T15:35:41.009+0000",
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/oauth/authorize"
}
我假设由于我的网络安全配置中允许 /oauth/authorize
,因此它应该返回一个可用于获取访问 token 的代码。有谁知道可能出了什么问题吗?
最佳答案
/oauth/authorize
是默认的授权服务器端点,这意味着它具有高优先级安全级别。
authorizeRequests().antMatchers("/oauth/authorize").permitAll()
不适用于 spring security 默认 api。如果您使用浏览器进行测试,例如
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication().passwordEncoder(new PasswordEncoder() {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence.toString());
}
})
.withUser("gig")
.password("123456")
.roles("USER");
}
此外,最好在范围后添加一个redirectUris。 我的测试网址
http://localhost:8080/oauth/authorize?response_type=code&client_id=auth-client-&redirect_uri=http://www.baidu.com&scope=all
关于java - Spring Boot授权服务器/oauth/authorize上出现未经授权的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55265344/