maven引入jar包(适配jdk1.7老项目)
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.0.4.RELEASE</version>
</dependency>
需要在web.xml中增加拦截器
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
编写资源服务器
@Configuration
@EnableResourceServer //启用资源服务器
@EnableWebSecurity
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
/**
* 声明了资源服务器的TokenStore是JWT
* @param resources
* @throws Exception
*/
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
//resourceId 还未设置
resources.resourceId("serverId").tokenStore(tokenStore());
}
/**
* 配置公钥
* @return
*/
@Bean
protected JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
Resource resource = new ClassPathResource("public.cert");
String publicKey = null;
try {
publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
converter.setVerifierKey(publicKey);
return converter;
}
/**
* 配置TokenStore
*
* @return
*/
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
/**
* 配置了除了/user路径之外的请求可以匿名访问
* @param http
* @throws Exception
*/
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/user/**").authenticated()
.anyRequest().permitAll();
}
}
applicationContext.xml配置扫描该包,注入bean
<context:component-scan base-package="com.***.***"></context:component-scan>
至此,完成一个基于jwt验证的oauth2的资源服务器!
要说的坑就是!
@EnableWebSecurity,这个注解在非spring boot项目中,需要加上该注解,不然会报
No qualifying bean of type [org.springframework.security.config.annotation.ObjectPostProcessor] found....... 异常
详细说明:https://blog.csdn.net/mingtiandexia/article/details/88910370