spring security oauth2 jwt 认证和资源分离的配置文件(java类配置版)
最近再学习spring security oauth2。下载了官方的例子sparklr2和tonr2进行学习。但是例子里包含的东西太多,不知道最简单最主要的配置有哪些。所以决定自己尝试搭建简单版本的例子。学习的过程中搭建了认证和资源在一个工程的例子,将token存储在数据库的例子等等 。最后做了这个认证和资源分离的jwt tokens版本。网上找了一些可用的代码然后做了一个整理, 同时测试了哪些代码是必须的。可能仍有一些不必要的代码在,欢迎大家赐教。
一.创建三个spring boot 工程,分别添加必要的依赖。认证和资源的工程需要添加依赖 <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.0.7.RELEASE</version>
</dependency>
二资源端工程的资源配置文件:
@Configuration
@EnableResourceServer
public class OAuth2ResourceService extends ResourceServerConfigurerAdapter {
private static final String SPARKLR_RESOURCE_ID = "apple";
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.tokenServices(tokenServices()).resourceId(SPARKLR_RESOURCE_ID);
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
return converter;
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
return defaultTokenServices;
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/hello").access("#oauth2.hasScope('read') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))");
// @formatter:on
}
}
安全配置文件:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/hello").hasRole("USER")
.and().csrf().disable()
.formLogin().loginPage("/login").failureUrl("/login-error");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("hello").password("123").roles("USER");
}
}
三 认证端工程的认证配置文件:
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {
private static final String SPARKLR_RESOURCE_ID = "apple";
int accessTokenValiditySeconds = 3600;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
return converter;
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// @formatter:off
clients.inMemory().withClient("tonr")
.resourceIds(SPARKLR_RESOURCE_ID)
.authorizedGrantTypes("authorization_code", "implicit")
.authorities("ROLE_CLIENT")
.scopes("read", "write")
.secret("secret")
.accessTokenValiditySeconds(accessTokenValiditySeconds);
// @formatter:on
}
//jdbc
// @Bean
// public DataSource jdbcTokenDataSource(){
// DriverManagerDataSource dataSource = new DriverManagerDataSource();
// dataSource.setDriverClassName("com.MySQL.jdbc.Driver");
// dataSource.setUrl("jdbc:mysql://localhost/test");
// dataSource.setUsername("root");
// dataSource.setPassword("root");
// return dataSource;
// }
@Bean
public TokenStore tokenStore() {
// return new InMemoryTokenStore();
// return new JdbcTokenStore(jdbcTokenDataSource());
return new JwtTokenStore(accessTokenConverter());
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore())
.authenticationManager(this.authenticationManager)
.accessTokenConverter(accessTokenConverter());
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
defaultTokenServices.setSupportRefreshToken(true);
return defaultTokenServices;
}
}\
spring security安全配置文件:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**", "/index").permitAll()
.and()
.csrf()
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
.disable()
.formLogin().loginPage("/login").failureUrl("/login-error");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("hello").password("123").roles("USER");
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
四 客户端工程的配置文件:
@Configuration
@EnableOAuth2Client
public class ResourceConfiguration {
@Bean
public OAuth2ProtectedResourceDetails hello() {
AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
details.setId("hello");
details.setClientId("tonr");
details.setClientSecret("secret");
details.setAccessTokenUri("http://localhost:8083/auth/oauth/token");//认证服务器地址+/oauth/token
details.setUserAuthorizationUri("http://localhost:8083/auth/oauth/authorize");//认证服务器地址+/oauth/authorize
details.setScope(Arrays.asList("read", "write"));
return details;
}
@Bean
public OAuth2RestTemplate helloRestTemplate(OAuth2ClientContext oauth2Context) {//客户端的信息被封装到OAuth2RestTemplate用于请求资源
return new OAuth2RestTemplate(hello(), oauth2Context);
}
}
在业务逻辑的serviceImp类中 注入helloRestTemplate 然后:
@Autowired
private RestOperations helloRestTemplate
public String getDataFromResoureServer() {;
String data= helloRestTemplate.getForObject(URI.create("http://localhost:8080/resource/hello"), String.class);//请求资源服务器资源的路径
return data;
}
spring security安全配置文件:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**", "/index").permitAll()
.and()
.formLogin()
.loginPage("/login").failureUrl("/login-error");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("insecure").password("123").roles("USER");
}
}
http://blog.csdn.net/u010139801/article/details/68484090
spring security oauth2 jwt 认证和资源分离的配置文件(java类配置版)的更多相关文章
- Spring Security OAuth2.0认证授权六:前后端分离下的登录授权
历史文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二:搭建资源服务 Spring Security OA ...
- 【Spring Cloud & Alibaba 实战 | 总结篇】Spring Cloud Gateway + Spring Security OAuth2 + JWT 实现微服务统一认证授权和鉴权
一. 前言 hi,大家好~ 好久没更文了,期间主要致力于项目的功能升级和问题修复中,经过一年时间的打磨,[有来]终于迎来v2.0版本,相较于v1.x版本主要完善了OAuth2认证授权.鉴权的逻辑,结合 ...
- Spring Security OAuth2.0认证授权二:搭建资源服务
在上一篇文章[Spring Security OAuth2.0认证授权一:框架搭建和认证测试](https://www.cnblogs.com/kuangdaoyizhimei/p/14250374. ...
- Spring Security OAuth2.0认证授权三:使用JWT令牌
Spring Security OAuth2.0系列文章: Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二: ...
- Spring Security OAuth2.0认证授权五:用户信息扩展到jwt
历史文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二:搭建资源服务 Spring Security OA ...
- Spring Security OAuth2.0认证授权四:分布式系统认证授权
Spring Security OAuth2.0认证授权系列文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授 ...
- Spring Security + OAuth2 + JWT 基本使用
Spring Security + OAuth2 + JWT 基本使用 前面学习了 Spring Security 入门,现在搭配 oauth2 + JWT 进行测试. 1.什么是 OAuth2 OA ...
- Springboot集成Spring Security实现JWT认证
我最新最全的文章都在南瓜慢说 www.pkslow.com,欢迎大家来喝茶! 1 简介 Spring Security作为成熟且强大的安全框架,得到许多大厂的青睐.而作为前后端分离的SSO方案,JWT ...
- Springboot WebFlux集成Spring Security实现JWT认证
我最新最全的文章都在南瓜慢说 www.pkslow.com,欢迎大家来喝茶! 1 简介 在之前的文章<Springboot集成Spring Security实现JWT认证>讲解了如何在传统 ...
随机推荐
- 嵌入式C开发---用循环实现左移右移
//将n左移m位 int byte_to_left_move(int n , int m) { int i , ret = 1 ; if(n == 0 || n < 0) { return ; ...
- PS 图像调整算法— —渐变映射
这个调整简单来说就是先建立一张lookup table, 然后以图像的灰度值作为索引,映射得到相应的颜色值.图像的灰度值是由图像本身决定的,但是lookup table 却可以各种各样,所以不同的lo ...
- 能量最小化初探,graphcuts能量最小化调用
1.相对于能量函数来说,能量最小化的办法都有哪些? 梯度下降 模拟退火 图割 2.这个 跟最优化问题的求解,有什么联系跟区别呢? 基本上差不多,其实就是求出来了函数的一个最小值,我们看问题的时候不妨把 ...
- android decorView详解
摘要 一.DecorView为整个Window界面的最顶层View. 二.DecorView只有一个子元素为LinearLayout.代表整个Window界面,包含通知栏,标题栏,内容显示栏三块区域. ...
- 初探linux子系统集之led子系统(三)
世界杯结束了,德国战车夺得了大力神杯,阿根廷最终还是失败了.也许3年,5年,或者10年后,人们就不知道巴西世界杯的亚军是谁,但是总是会记得冠军是谁.就像什么考试,比赛,第一永远会被人们所记住,所以我们 ...
- rails无法使用页面缓存的解决办法
书上云在config/envirionments/development.rb中开启了缓存机制后,我们即可以使用缓存鸟: config.action_controller.perform_cach ...
- 80端口被NT kernel & System 占用
新年后正常上班的第一天,客户报告,虚拟机上的网站起不来了. 登录虚拟机的远程桌面,闪几下连接信息,后面就没了,不显示远程桌面.联系虚拟机管理,重启,远程桌面是连上了,网站还是起不来. 查看window ...
- 学习MQ(一) 感知
声明:我的文字里出现的MQ,如没有特殊指明,就是指的IBM的websphere MQ 以前对MQ一无所知! MQ是IBM websphere的系列产品之一,是很好的一个中间件产品.其实我对这列产品并不 ...
- 你不知道你不懂javascript
过去几年我注意到技术圈一个很奇怪的现象,有太多程序员将那些他们只是有过非常浅显的了解, 但其实根本就不懂的技术写到他们的简历中,这个现象几乎每种语言都有,但这其中最严重的就要数javascript了. ...
- 修改flume源码,使其HTTPSource具备访问路径功能
目前有一个需求,就是Flume可以作为一个类似于tomcat的服务器,可以通过post请求进行访问,并且路径需要:ip:port/contextPath格式. 经过一些资料获悉,httpSource只 ...