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认证>讲解了如何在传统 ...
随机推荐
- 如何来看单片机外设A/D转换器ADC0804时序图
如图,为单片机AD转换器的一种: ADC0804单片集成A/D转换器.它采用CMOS工艺20引脚集成芯片,分辩率为8位,转换时间为100µs,输入电压范围为0-5V.芯片内具有三态输出数据锁存器,可直 ...
- android SurfaceView绘制实现原理解析
在Android系统中,有一种特殊的视图,称为SurfaceView,它拥有独立的绘图表面,即它不与其宿主窗口共享同一个绘图表面.由于拥有独立的绘图表面,因此SurfaceView的UI就可以在一个独 ...
- XMPP系列(一):OpenFire环境搭建
XMPP的服务器可以用OpenFire.ejabberd.jabberd2.x.Prosody.Tigase,其中比较常用的是OpenFire和ejabberd,还可以自己写服务器,我们公司的服务器端 ...
- GEFGWT的HelloWorld
发现一个好玩的东西,gef-gwt,使用它可以轻松的在web上建立gef程序,原文在这里http://gefgwt.org/getting-started/(文章虽然是英文,但是很容易懂,我是按部就班 ...
- javascript中的eval函数
eval()只有一个参数,如果传入的参数不是字符串,则直接返回这个参数.否则会将字符串当成js代码进行编译,如果编译失败则抛出语法错误(SyntaxError)异常.如果编译成功则开始执行这段代码,并 ...
- ELF 动态链接 - so 的 .dynamic 段
动态链接文件中最重要的段就是 .dynamic段 这个段里保存了动态链接器需要的最基本的信息 比如:1. 依赖于哪些共享对象, d_tag = DT_NEED, d_ptr 表示共享对象文件名 2 ...
- Day17 Django的基础使用和结构
整个Django的访问流程: 浏览器 urls: http://127.0.0.1:8000/timer url.py: 1, http://127.0.0.1:8000/timer GET 无请求数 ...
- Web开发问题记录
1.先说一个CSS的:CSS中带有中文(比如字体定义)的属性定义最好放在该选择器定义诸项的最后一条,为什么----编码格式问题. 2.其实自己也可以用自己写的DispatcherServlet+jsp ...
- Java自学开发编程路线图(文中有资源福利)
Java 语言入门 免费视频资源<毕向东Java基础教程>:http://yun.itheima.com/course/7.html JavaEE 学习大纲 所处阶段 主讲内容 技术要点 ...
- 详解Java的Spring框架中的注解的用法
转载:http://www.jb51.net/article/75460.htm 1. 使用Spring注解来注入属性 1.1. 使用注解以前我们是怎样注入属性的 类的实现: class UserMa ...