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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/357074.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2022年最新大数据学习路线图

目录 1.JavaSE基础核心 2.Hadoop生态体系阶段 3.Spark生态体系阶段 4.Flink生态体系阶段 5.前沿技术

Node.js 官方文档中文版

这目录也是醉了 。 列出跟没列出没两样 转载于:https://www.cnblogs.com/ganmk--jy/p/5646860.html

2022年最新前端学习路线图

目录 1.前端核心基础阶段 2.前端核心高级阶段 3.JavaScript高级 4.JS后台技术阶段

Smaug Coverage

转载于:https://www.cnblogs.com/edisonxiang/p/5650656.html

图谱(学习地图)系列总结,持续更新中

目录 1.2022年最新前端学习路线图 2.2022年最新大数据学习路线图 3.2022年最新javaEE学习路线图 4.2022年最新UI/UE学习路线图 5.2022年java学习路线指南 6.JavaScript学习总结(思维导图篇) 7.思维脑图——数据分析实战(最新版&#…

最佳编码hdu_如果–否则为编码风格最佳实践

最佳编码hdu以下文章将是一个高级大括号讨论,没有对与错的答案,只是更多的“品味”。 它是关于是否将“ else”(以及其他关键字,例如“ catch”,“ finally”)放在换行符上。 有些人可能会写 if (somethin…

自定义UserProvider,更改验证方法

新建UserProvider,如果继承EloquentUserProvider,注入model是必须的,或者去继承interface,自己实现一些方法 use Illuminate\Auth\EloquentUserProvider; use Illuminate\Contracts\Auth\Authenticatable as UserContract;class M…

一些前端大牛都在学习的github库

前端知识比较杂,长时间的工作容易沉浸在业务当中,技术提升有限,这里发现了前端的新大陆,可以帮助小伙伴们巩固基础知识,完善自己的知识体系,欢迎点赞收藏,兄弟们,赶紧干起来吧! 1.JavaScript 算法和数据结构https://github.com/trekhleb/javascript-algorithms 数据结…

【TypeScript系列教程01】入门介绍

目录 什么是TypeScript? TypeScript 的过去与现在? JavaScript 与 TypeScript 的区别? 类型批注 第一个 TypeScript 实例 编译器

SQL Server 中截取字符串常用的函数

SQL Server 中截取字符串常用的函数:1.LEFT ( character_expression , integer_expression ) 函数说明:LEFT ( 源字符串 , 要截取最左边的字符数 ) 返回从字符串左边开始指定个数的字符 select LEFT(SQL_Server_2008,4 ); 返回结果:SQL_2.RI…

动态Java代码注入

在本文中,我们将研究如何将Java代码动态加载到正在运行的jvm中。 该代码可能是全新的,或者我们可能想更改程序中某些现有代码的功能。 (在开始之前,您可能想知道为什么到底有人会这样做。显而易见的示例是规则引擎之类的东西。规…

【TypeScript系列教程02】安装及使用

目录 TypeScript 安装 NPM 安装 TypeScript 测试安装结果 本教程使用VSCode TypeScript 安装 我们需要使用到 npm ,你需要安装Node.js; NPM 安装 TypeScript 如果你的本地环境已经安装了 npm 工具,可以使用以下命令来安装: npm install -g typescript

'scrapyd-deploy' 不是内部或外部命令,也不是可运行的程序 或批处理文件。

在windows上使用scrapyd-client 安装后,并不能使用相应的命令scrapyd-deploy 需要在"C:\Python27\Scripts" 目录下 增加scrapyd-deploy.bat文件 内容填充为: echo off "C:\python27\python.exe" "C:\python27\Scripts\scrapyd…

【TypeScript系列教程03】基础语法

目录 TypeScript 基础语法 空白和换行 TypeScript 区分大小写 分号是可选的 TypeScript 注释 TypeScript 支持两种类型的注释

ccxt k线数据_寻找相似的历史k线

有网友提问应该用什么样的数据库/数据结构/算法来计算某支股票的相似K线? 具体的问题描述是,假设给出某股某段行情K线(单位/日),从任何其他股票历史中匹配出与之最为相似的某段历史K线,并给出相似度值(单位…

java引用 弱引用_了解Java弱引用

java引用 弱引用我最近没来得及关注这个博客,最重要的是,我没有为与技术界的所有人保持联系而致歉。 最近,我偶然发现了自Java 1.2起可用的java.lang.ref软件包,但具有讽刺意味的是,几天前我才知道它。 在浏览了几篇有…

【TypeScript系列教程04】编译参数

目录 编辑单个 .ts 文件 编辑多个 .ts 文件 tsc 常用编译参数 编辑单个 .ts 文件 通常我们使用 .ts 作为 TypeScript 代码文件的扩展名。 然后执行以下命令将 TypeScript 转换为 JavaScript 代码: tsc sunjiaoshou.js 编辑多个 .ts 文件 我们可以同时编译多个 ts 文件: …

传递数组到 Shader

https://chengkehan.github.io/UniformArray.html 转载于:https://www.cnblogs.com/jim-game-dev/p/5658023.html

k均值例子 数据挖掘_数据挖掘的技术有很多种,常用的数据挖掘技术就这13种...

数据挖掘就是从大量的、不完全的、有噪声的、模糊的、随机的数据中,提取隐含在其中的、人们事先不知道的但又是潜在有用的信息和知识的过程。数据挖掘的任务是从数据集中发现模式,可以发现的模式有很多种,按功能可以分为两大类:预…

【TypeScript系列教程05】保留关键字

目录 TypeScript 保留关键字 TypeScript 保留关键字 TypeScript 保留关键字如下表所示: