Spring Boot Oauth2安全性
这篇文章是对我以前的文章的增强,该文章讨论了如何使用Spring security oauth2保护REST API。
万一您错过了它,可以在这里领取: http : //blog.rajithdelantha.com/2015/09/secure-your-rest-api-with-spring.html
Spring Boot是Spring框架的一项新发明,它使开发人员在构建大规模应用程序时的工作更加轻松。 这是抓住概念的好地方。
如果您查看我之前有关oauth2安全的文章,那么您知道在Spring端需要做一些配置。 但是另一方面,Spring boot将完成所有艰苦的工作,我们只需要通过简单的注释告诉他们该怎么做。
因此,本文是关于如何使用Spring安全性和Oauth2配置Spring引导项目的。 实际上,我们不能真正说出configure,因为所有大多数配置都是由Spring boot本身完成的。
- 源代码: https : //github.com/rajithd/spring-boot-oauth2
步骤1
对于这个项目,我在内存数据库中使用H2。 因此,您无需在运行时创建任何数据库和表。 但是,如果您希望该项目使用MySQL作为数据源,则首先创建数据库,然后创建表。
CREATE TABLE user ( username VARCHAR(50) NOT NULL PRIMARY KEY, email VARCHAR(50), password VARCHAR(500), activated BOOLEAN DEFAULT FALSE, activationkey VARCHAR(50) DEFAULT NULL, resetpasswordkey VARCHAR(50) DEFAULT NULL ); CREATE TABLE authority ( name VARCHAR(50) NOT NULL PRIMARY KEY ); CREATE TABLE user_authority ( username VARCHAR(50) NOT NULL, authority VARCHAR(50) NOT NULL, FOREIGN KEY (username) REFERENCES user (username), FOREIGN KEY (authority) REFERENCES authority (name), UNIQUE INDEX user_authority_idx_1 (username, authority) ); CREATE TABLE oauth_access_token ( token_id VARCHAR(256) DEFAULT NULL, token BLOB, authentication_id VARCHAR(256) DEFAULT NULL, user_name VARCHAR(256) DEFAULT NULL, client_id VARCHAR(256) DEFAULT NULL, authentication BLOB, refresh_token VARCHAR(256) DEFAULT NULL ); CREATE TABLE oauth_refresh_token ( token_id VARCHAR(256) DEFAULT NULL, token BLOB, authentication BLOB );
- 用户表–系统用户
- 权威–角色
- user_authority –用户和角色的多对多表
- oauth_access_token –存放access_token
- oauth_refresh_token –保持refresh_token
添加一些种子数据。
INSERT INTO user (username,email, password, activated) VALUES ('admin', 'admin@mail.me', 'b8f57d6d6ec0a60dfe2e20182d4615b12e321cad9e2979e0b9f81e0d6eda78ad9b6dcfe53e4e22d1', true); INSERT INTO user (username,email, password, activated) VALUES ('user', 'user@mail.me', 'd6dfa9ff45e03b161e7f680f35d90d5ef51d243c2a8285aa7e11247bc2c92acde0c2bb626b1fac74', true); INSERT INTO user (username,email, password, activated) VALUES ('rajith', 'rajith@abc.com', 'd6dfa9ff45e03b161e7f680f35d90d5ef51d243c2a8285aa7e11247bc2c92acde0c2bb626b1fac74', true); INSERT INTO authority (name) VALUES ('ROLE_USER'); INSERT INTO authority (name) VALUES ('ROLE_ADMIN'); INSERT INTO user_authority (username,authority) VALUES ('rajith', 'ROLE_USER'); INSERT INTO user_authority (username,authority) VALUES ('user', 'ROLE_USER'); INSERT INTO user_authority (username,authority) VALUES ('admin', 'ROLE_USER'); INSERT INTO user_authority (username,authority) VALUES ('admin', 'ROLE_ADMIN');
第2步
配置WebSecurityAdapter
@Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Bean public PasswordEncoder passwordEncoder() { return new StandardPasswordEncoder(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder()); } @Override public void configure(WebSecurity web) throws Exception { web .ignoring() .antMatchers("/h2console/**") .antMatchers("/api/register") .antMatchers("/api/activate") .antMatchers("/api/lostpassword") .antMatchers("/api/resetpassword"); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true) private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration { @Override protected MethodSecurityExpressionHandler createExpressionHandler() { return new OAuth2MethodSecurityExpressionHandler(); } } }
第三步
Oauth2的配置
@Configuration public class OAuth2Configuration { @Configuration @EnableResourceServer protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { @Autowired private CustomAuthenticationEntryPoint customAuthenticationEntryPoint; @Autowired private CustomLogoutSuccessHandler customLogoutSuccessHandler; @Override public void configure(HttpSecurity http) throws Exception { http .exceptionHandling() .authenticationEntryPoint(customAuthenticationEntryPoint) .and() .logout() .logoutUrl("/oauth/logout") .logoutSuccessHandler(customLogoutSuccessHandler) .and() .csrf() .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize")) .disable() .headers() .frameOptions().disable() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/hello/**").permitAll() .antMatchers("/secure/**").authenticated(); } } @Configuration @EnableAuthorizationServer protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware { private static final String ENV_OAUTH = "authentication.oauth."; private static final String PROP_CLIENTID = "clientid"; private static final String PROP_SECRET = "secret"; private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds"; private RelaxedPropertyResolver propertyResolver; @Autowired private DataSource dataSource; @Bean public TokenStore tokenStore() { return new JdbcTokenStore(dataSource); } @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .tokenStore(tokenStore()) .authenticationManager(authenticationManager); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients .inMemory() .withClient(propertyResolver.getProperty(PROP_CLIENTID)) .scopes("read", "write") .authorities(Authorities.ROLE_ADMIN.name(), Authorities.ROLE_USER.name()) .authorizedGrantTypes("password", "refresh_token") .secret(propertyResolver.getProperty(PROP_SECRET)) .accessTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 1800)); } @Override public void setEnvironment(Environment environment) { this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH); } } }
就是这个。 尝试通过mvn spring-boot:run运行Spring Boot应用程序
然后通过执行以下curl检查oauth2的安全性:
- https://github.com/rajithd/spring-boot-oauth2
翻译自: https://www.javacodegeeks.com/2015/10/spring-boot-oauth2-security.html
Spring Boot Oauth2安全性相关推荐
- thymeltesys-基于Spring Boot Oauth2的扫码登录框架
thymeltesys thymelte是一个基于Spring Boot Oauth2的扫码登录框架,使用PostgreSQL存储数据,之后会慢慢支持其他关系型数据库.即使你不使用整个框架,只使用其中 ...
- spring boot oauth2 facebook
前言 最近网站要接入facebook以及google两种第三方登录.查阅了很多的资料,终于算是勉强将facebook登录接入到了我们自己的项目中,这里记录整个facebook接入的整个流程和遇到的坑, ...
- filter java oauth_java – 带有自定义安全过滤器的Spring Boot OAuth2
我有一个带有OAuth2授权和资源服务器的 spring boot设置.用户可以通过向/ oauth / token发出POST请求来获取令牌.到现在为止还挺好. 但是,我不想通过BASIC auth ...
- Spring Boot+OAuth2使用GitHub登录自己的服务
网站利用 OAuth2 提供第三方登录(GitHub) 授权码模式 A 网站让用户跳转到 GitHub GitHub 要求用户登录,然后询问"A 网站要求获得 xx 权限,你是否同意?&qu ...
- Spring Boot + OAuth2.0 实现微信扫码登录,这才叫优雅
点击"终码一生",关注,置顶公众号 每日技术干货,第一时间送达! 微信开放平台:微信扫码登录功能 官方文档:https://developers.weixin.qq.com/doc ...
- Spring Boot + OAuth2.0 实现微信扫码登录,这才叫优雅!!
微信开放平台:微信扫码登录功能 官方文档:https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_ ...
- Spring Boot OAuth2 使用实践
一.添加依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>sp ...
- 【Spring Boot】Spring Boot @EnableOAuth2Sso | 启用 OAuth2 单点登录
文章目录 演示工具版本 Maven 依赖 使用 @EnableOAuth2Sso OAuth2 配置 登出 完整示例 输出 参考文献 源码下载 本页将介绍Spring Security OAuth2 ...
- 面试那点小事,你从未见过的spring boot面试集锦(附详细答案)
一, 什么是spring boot? 多年来,随着新功能的增加,spring变得越来越复杂.只需访问页面https://spring.io/projects,我们将看到所有在应用程序中使用的不同功能的 ...
最新文章
- elasticsearch 客户端工具_ELK集群部署 - elasticsearch-7.9.3
- 我们离DevOps有多远--持续集成思想的延伸
- 糊涂的教授【拓扑排序】
- 游侠原创:手机电子商务与社交隐私--网络安全的下一个关注点
- 信噪比:高端科研级相机的核心参数
- mysql备份之lvm
- 老司机 iOS 周报 #42 | 2018-11-05
- NWT失败反省:明明是自己把公司搞死,却说别人水平不行
- 军用加固便携式计算机,PCI/PCIe
- PCB线路板上的电子元件你认识多少?
- linux的dd命令与cp,dd命令中seek和skip的用法-Linux下挂载 windows 共享的命令-学习history命令的使用方法_169IT.COM...
- CNKI知网查重账号和密码怎么申请
- Fundamentals Of Computer Graphics (4th Ed)
- webpack5 css打包压缩
- 安卓模拟器的使用--皇室战争免费快速成长之路
- 手绘与码绘的比较---模拟风吹树动
- 上海小黑鱼Android技术,小黑鱼旗下社交电商平台-环球好货超级合伙人全球发布会2月23日上海重磅启...
- 同程旅游缓存系统(凤凰)打造 Redis 时代的完美平台实践
- 无法访问指定计算机,windows无法访问指定设备如何解决
- html加载m3u8
热门文章
- 《走遍中国》珍藏版(十三)
- sql server简单查询
- MyBatisPlus分页
- python一图带你精通time类型转换
- OkHttp上传Json嵌套对象
- 车提示检测轮胎气压_水淹车估价中心_辽宁中车检
- String path = request.getContextPath()和String basePath = request.getScheme()
- hashmap应用场景_工作中常用到的Java集合有哪些?应用场景是什么?
- 转:IDEA 创建类注释模板和方法注释模板
- java集合——遗留的集合