我对 OAuth2 真的很陌生,并试图在角色 auth.server 中构建一台服务器来授权用户和一个保留受保护资源的服务器......
我遇到了需要使用 ResourceServerConfigurerAdapter 保护的问题。似乎他忽略了从 userInfoUrl 中获取的所有角色...
所以这里的代码:
认证服务器
@SpringBootApplication
@EnableAuthorizationServer
@EnableResourceServer
@RestController
public class Oa2AuthServerApplication {
@RequestMapping("/user")
public Principal user(Principal user) {
return user;
}
public static void main(String[] args) {
SpringApplication.run(Oa2AuthServerApplication.class, args);
}
}
__
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password("admin")
.roles("ADMIN", "USER")
.and()
.withUser("user")
.password("user")
.roles("USER");
}
}
__
@Configuration
public class OA2AuthConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("default")
.secret("kx")
.scopes("AUTH", "TRUST")
.autoApprove(true)
.authorities("ROLE_GUEST", "ROLE_USER", "ROLE_ADMIN")
.authorizedGrantTypes("authorization_code", "implicit", "refresh_token");
}
}
资源服务器
@SpringBootApplication
@RestController
@EnableResourceServer
public class Oa2ResourceServerApplication {
@RequestMapping("/")
public String greet() {
return UUID.randomUUID().toString() + "\r\n";
}
@RequestMapping("/forAdmin")
public String admin() {
return "hi admin!";
}
public static void main(String[] args) {
SpringApplication.run(Oa2ResourceServerApplication.class, args);
}
}
因此,从 authserver 获取令牌 + 调用“localhost:9091/”和“/forAdmin”可以使用此令牌。
但是当我这样做时:
public class WebSecurityConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/forAdmin").hasRole("USER");
}
我被拒绝访问....
可以肯定的是,角色正在到达资源服务器,我已将 geet() 从上面更改为
@RequestMapping("/")
public String greet(Principal user) {
if (user instanceof OAuth2Authentication) {
log.info("having roles: {}", ((OAuth2Authentication) user).getAuthorities());
}
return UUID.randomUUID().toString() + "\r\n";
}
控制台显示
dkauth.Oa2ResourceServerApplication :具有角色:[{authority=ROLE_USER}]
因此,当“Principal”是当前经过身份验证的用户时,我假设 resourceserverer 配置器存在错误......或者我正在做一些致命的错误......
或两者兼而有之....我不知道
有人可以帮助我解决这个问题吗?