【发布时间】:2015-11-14 07:05:46
【问题描述】:
可能我在这里做错了什么,我只是不知道是什么......
我在同一个应用程序中有一个 Oauth2 身份验证服务器和一个资源服务器。
资源服务器配置:
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER-1)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
public static final String RESOURCE_ID = "resources";
@Override
public void configure(final ResourceServerSecurityConfigurer resources) {
resources
.resourceId(RESOURCE_ID);
}
@Override
public void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/**").access("#oauth2.hasScope('read')")
.antMatchers(HttpMethod.POST, "/**").access("#oauth2.hasScope('write')")
.antMatchers(HttpMethod.PUT, "/**").access("#oauth2.hasScope('write')")
.antMatchers(HttpMethod.PATCH, "/**").access("#oauth2.hasScope('write')")
.antMatchers(HttpMethod.DELETE, "/**").access("#oauth2.hasScope('write')")
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers(HttpMethod.GET, "/health").permitAll();
}
}
认证服务器配置:
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
public void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and().httpBasic().realmName("OAuth Server");
}
}
当我尝试访问 /health 时,我得到了 HTTP/1.1 401 Unauthorized。
如何说服 Spring Boot 让 /health 匿名访问?
【问题讨论】:
-
在 SecurityConfig 中,我认为您错过了添加: .antMatchers(HttpMethod.GET, "/health").permitAll();
-
您指定映射的顺序也是查询它们的顺序。第一场比赛获胜......因为
/**匹配所有你的/health映射是无用的。将其移至/**映射上方以使其正常运行。 -
@M.Deinum 谢谢,这解决了问题。如果您将此添加为答案,我很乐意接受。
标签: java spring spring-security spring-boot spring-security-oauth2