問題描述
我正在使用 spring-security
和 spring-security-oauth2
(JWT 訪問令牌)進行身份驗證和授權(quán).這個想法是讓所有請求通過,但能夠區(qū)分經(jīng)過身份驗證的用戶和未經(jīng)身份驗證的用戶.一旦我啟用 @EnableResourceServer
我配置的 HttpSecurity
似乎被忽略.并且請求返回 401:
I'm using spring-security
and spring-security-oauth2
(JWT access tokens) for authentication and authorization. The idea is to let all requests through, but to be able to distinguish between authenticated users and unauthenticated users. As soon as I enable @EnableResourceServer
my configured HttpSecurity
seems to get ignored. And requests return 401:
{
"error": "unauthorized",
"error_description": "Full authentication is required to access this resource"
}
這是配置:
@SpringBootApplication
@EnableJpaRepositories
@ComponentScan
@EntityScan
@EnableWebSecurity
public class Application {
public static void main(final String[] args) {
new SpringApplicationBuilder(Application.class).bannerMode(Banner.Mode.OFF).run(args);
}
@EnableResourceServer
public static class SecurityConfig extends WebSecurityConfigurerAdapter implements JwtAccessTokenConverterConfigurer {
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().anyRequest().permitAll();
}
@Override
public void configure(final JwtAccessTokenConverter converter) {
final DefaultAccessTokenConverter conv = new DefaultAccessTokenConverter();
conv.setUserTokenConverter(userAuthenticationConverter());
converter.setAccessTokenConverter(conv);
}
@Bean
public UserAuthenticationConverter userAuthenticationConverter() {
return new ResourceAuthenticationConverter();
}
}
推薦答案
你快到了.這是一個簡單的修復(fù) - @EnableResourceServer 的 javadoc 提供了答案:
You're almost there. It's an easy fix - the javadoc of @EnableResourceServer provides the answer:
用戶應(yīng)該添加這個注解并提供一個@Bean 類型ResourceServerConfigurer(例如,通過 ResourceServerConfigurerAdapter)指定資源的詳細信息(URL 路徑和資源id).
Users should add this annotation and provide a @Bean of type ResourceServerConfigurer (e.g. via ResourceServerConfigurerAdapter) that specifies the details of the resource (URL paths and resource id).
但是,您使用的是 WebSecurityConfigurerAdapter
.只需將其改為ResourceServerConfigurerAdapter
,增強configure
的可見性:
You're using a WebSecurityConfigurerAdapter
however. Just change it to ResourceServerConfigurerAdapter
and enhance the visibility of configure
:
@EnableResourceServer
public static class SecurityConfig extends ResourceServerConfigurerAdapter implements JwtAccessTokenConverterConfigurer {
// snip
@Override
public void configure(final HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().anyRequest().permitAll();
}
// snip
這篇關(guān)于盡管 authorizeRequests().anyRequest().permitAll() spring-security 返回 401的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!