0. 前言

  之前帐号认证用过自己写的进行匹配,现在要学会使用标准了。准备了解和使用这个OAuth2.0协议。

1. 配置

1.1 配置pom.xml

  有些可能会用不到,我把我项目中用到的所有包都贴出来。

         <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>

1.2 配置application.properties

 #server
server.port=8080
server.servlet.session.timeout=2520000
#redis
spring.redis.database=0
spring.redis.host=172.16.23.203
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=60
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=10000

1.3 资源服务器配置

 /**
* OAuth 资源服务器配置
* @author
* @date 2018-05-29
*/
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { private static final String DEMO_RESOURCE_ID = "order"; @Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(DEMO_RESOURCE_ID).stateless(true);
} @Override
public void configure(HttpSecurity http) throws Exception {
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().anyRequest()
.and()
.anonymous()
.and()
.authorizeRequests()
.antMatchers("/order/**").authenticated();//配置order访问控制,必须认证过后才可以访问
}
}

1.4 授权服务器配置

 /**
* OAuth 授权服务器配置
* @author
* @date 2018-05-29
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { private static final String DEMO_RESOURCE_ID = "order"; @Autowired
AuthenticationManager authenticationManager;
@Autowired
RedisConnectionFactory redisConnectionFactory; @Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
String finalSecret = "{bcrypt}"+new BCryptPasswordEncoder().encode("123456");
//配置两个客户端,一个用于password认证一个用于client认证
clients.inMemory()
.withClient("client_1")
.resourceIds(DEMO_RESOURCE_ID)
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("select")
.authorities("oauth2")
.secret(finalSecret)
.and()
.withClient("client_2")
.resourceIds(DEMO_RESOURCE_ID)
.authorizedGrantTypes("password", "refresh_token")
.scopes("select")
.authorities("oauth2")
.secret(finalSecret);
} @Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(new RedisTokenStore(redisConnectionFactory))
.authenticationManager(authenticationManager)
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
} @Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
//允许表单认证
oauthServer.allowFormAuthenticationForClients();
}
}

1.5 Spring Security配置

 /**
* Spring-Security 配置<br>
* 具体参考: https://github.com/lexburner/oauth2-demo
* @author
* @date 2018-05-28
*/
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Bean
@Override
protected UserDetailsService userDetailsService(){
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String finalPassword = "{bcrypt}"+bCryptPasswordEncoder.encode("123456");
manager.createUser(User.withUsername("user_1").password(finalPassword).authorities("USER").build());
finalPassword = "{noop}123456";
manager.createUser(User.withUsername("user_2").password(finalPassword).authorities("USER").build());
return manager;
} @Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers().anyRequest()
.and()
.authorizeRequests()
.antMatchers("/oauth/*").permitAll();
} /**
* Spring Boot 2 配置,这里要bean 注入
*/
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
AuthenticationManager manager = super.authenticationManagerBean();
return manager;
} @Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

1.6 定义一个资源点

 @RestController
@RequestMapping(value="/")
public class TestController { @RequestMapping(value="order/demo")
public YYModel getDemo() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
System.out.println(auth);
YYModel yy = new YYModel();
yy.setYy("中文");
yy.setZz(3);
return yy;
} @GetMapping("/test")
public String getTest() {
YYModel yy = new YYModel();
yy.setYy("中文");
yy.setZz(3);
return yy.toJSONString();
}
}

2. 工具测试

  

  

  参考: http://blog.didispace.com/spring-security-oauth2-xjf-1/

Spring Boot 2.0 利用 Spring Security 实现简单的OAuth2.0认证方式1的更多相关文章

  1. Spring Boot 2.0 利用 Spring Security 实现简单的OAuth2.0认证方式2

    0.前言 经过前面一小节已经基本配置好了基于SpringBoot+SpringSecurity+OAuth2.0的环境.这一小节主要对一些写固定InMemory的User和Client进行扩展.实现动 ...

  2. Spring Boot 2(一):Spring Boot 2.0新特性

    Spring Boot 2(一):Spring Boot 2.0新特性 Spring Boot依赖于Spring,而Spring Cloud又依赖于Spring Boot,因此Spring Boot2 ...

  3. Spring Boot 多站点利用 Redis 实现 Session 共享

    如何在不同站点(web服务进程)之间共享会话 Session 呢,原理很简单,就是把这个 Session 独立存储在一个地方,所有的站点都从这个地方读取 Session. 通常我们使用 Redis 来 ...

  4. spring boot 是如何利用jackson进行序列化的?

    接上一篇:spring boot 是如何利用jackson进行反序列化的? @RestController public class HelloController { @RequestMapping ...

  5. spring boot rest 接口集成 spring security(2) - JWT配置

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  6. spring boot rest 接口集成 spring security(1) - 最简配置

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  7. Spring Boot配置篇(基于Spring Boot 2.0系列)

    1:概述 SpringBoot支持外部化配置,配置文件格式如下所示: properties files yaml files environment variables command-line ar ...

  8. (转)Spring Boot 2 (八):Spring Boot 集成 Memcached

    http://www.ityouknow.com/springboot/2018/09/01/spring-boot-memcached.html Memcached 介绍 Memcached 是一个 ...

  9. Spring Boot 2 (八):Spring Boot 集成 Memcached

    Spring Boot 2 (八):Spring Boot 集成 Memcached 一.Memcached 介绍 Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数 ...

随机推荐

  1. django 生成csv文件重要代码

    import csv from django.http import HttpResponse # Number of unruly passengers each year 1995 - 2005. ...

  2. 三种常用的MySQL建表语句

    MySQL建表语句是最基础的SQL语句之一,下面就为您介绍最常用的三种MySQL建表语句,如果您对MySQL建表语句方面感兴趣的话,不妨一看. 1.最简单的: CREATE TABLE t1(    ...

  3. 最长公共子序列(POJ1458)

    题目链接:http://poj.org/problem?id=1458 题目大意:给出两个字符串,求出这样的一个最长的公共子序列的长度:子序列中的每个字符都能在两个原串中找到,而且每个字符的先后顺序和 ...

  4. RHEL7 在不同的环境中使用不同的网络配置文件

    比如,我们可以设置RHEL7 系统在公司时使用一个网卡配置文件:在家时则使用另外一个配置文件(可以根据不同的环境设置多个网卡配置文件). 网卡配置信息如下: [root@rhel7 ~]# nmcli ...

  5. Ubuntu与Windows7双系统下, 系统时间不一致的问题

    Ubuntu使用的UTC时间, 而Windows使用的是Local Time, 就导致每次切换系统后, Windows时间都会正好晚8个小时. 有两种解决办法, 一个是修改Ubuntu, 另一个是修改 ...

  6. Axure快速原型教程02--创建页面和设置界面

    目录 Axure快速原型教程02--创建页面和设置界面 Axure快速原型教程01--原型说明下载和安装 首先,在左侧的面板中,我们发现有一个叫sitemap的面板,这个面板就是我们的一个个的页面了, ...

  7. iOS之ProtocolBuffer搭建

    一.环境安装:pb编译器的安装 1.从https://github.com/google/protobuf/releases下载protocolBuffer对应版本编译器包,比如目前的对应的objc最 ...

  8. C++的iostream标准库介绍+使用详解(转)

    0 为什么需要iostream 我们从一开始就一直在利用C++的输入输出在做着各种练习,输入输出是由iostream库提供的,所以讨论此标准库是有必要的,它与C语言的 stdio库不同,它从一开始就是 ...

  9. 如何在windows下安装JDK

    1:卸载 A:一定要删除注册表中的 HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft 项 B:最好用安装工具卸载JDK,如果没有的话就删除JDK文件夹然后用Wise Regis ...

  10. Linux IO系统分析(scsi篇)

    一.概述 Linux内核中SCSI子系统由SCSI上层,中间层,底层驱动模块三部分组成,负责管理SCSI资源和处理其他子系统,如文件系统,提交到SCSI子系统中的IO请求. 因此,理解SCSI子系统的 ...