Spring Cloud Security:Oauth2结合JWT使用
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter;
import org.springframework.security.oauth2.server.resource.web.access.BearerTokenAccessDeniedHandler;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// ... 其他配置 ...
.exceptionHandling()
.accessDeniedHandler(new BearerTokenAccessDeniedHandler())
.and()
.addFilterAfter(new BearerTokenAuthenticationFilter(authenticationManager()),
UsernamePasswordAuthenticationFilter.class);
}
@Bean
@Override
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}
这个配置类扩展了WebSecurityConfigurerAdapter
,覆盖了configure
方法来配置HTTP安全性。它添加了一个BearerTokenAuthenticationFilter
,这是一个过滤器,用于在请求头中查找并处理Bearer Token。同时,它配置了一个BearerTokenAccessDeniedHandler
,用于处理访问被拒绝的情况。这个配置是OAuth2和JWT集成中的一个关键部分。
评论已关闭