Spring Boot 2.0 利用 Spring Security 实现简单的OAuth2.0认证方式1
0. 前言
之前帐号认证用过自己写的进行匹配,现在要学会使用标准了。准备了解和使用这个OAuth2.0协议。
1. 配置
1.1 配置pom.xml
有些可能会用不到,我把我项目中用到的所有包都贴出来。
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-data-redis</artifactId> 4 </dependency> 5 <dependency> 6 <groupId>org.springframework.boot</groupId> 7 <artifactId>spring-boot-starter-security</artifactId> 8 </dependency> 9 <dependency> 10 <groupId>org.springframework.security.oauth</groupId> 11 <artifactId>spring-security-oauth2</artifactId> 12 <version>2.3.3.RELEASE</version> 13 </dependency> 14 <dependency> 15 <groupId>org.springframework.boot</groupId> 16 <artifactId>spring-boot-starter-web</artifactId> 17 </dependency> 18 <dependency> 19 <groupId>org.mybatis.spring.boot</groupId> 20 <artifactId>mybatis-spring-boot-starter</artifactId> 21 <version>1.3.2</version> 22 </dependency> 23 <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter --> 24 <dependency> 25 <groupId>com.github.pagehelper</groupId> 26 <artifactId>pagehelper-spring-boot-starter</artifactId> 27 <version>1.2.5</version> 28 </dependency> 29 <dependency> 30 <groupId>org.springframework.cloud</groupId> 31 <artifactId>spring-cloud-starter-oauth2</artifactId> 32 </dependency> 33 <dependency> 34 <groupId>org.springframework.cloud</groupId> 35 <artifactId>spring-cloud-starter-security</artifactId> 36 </dependency> 37 38 <dependency> 39 <groupId>org.springframework.boot</groupId> 40 <artifactId>spring-boot-devtools</artifactId> 41 <scope>runtime</scope> 42 </dependency> 43 <dependency> 44 <groupId>org.postgresql</groupId> 45 <artifactId>postgresql</artifactId> 46 <scope>runtime</scope> 47 </dependency> 48 <dependency> 49 <groupId>org.springframework.boot</groupId> 50 <artifactId>spring-boot-starter-test</artifactId> 51 <scope>test</scope> 52 </dependency> 53 <dependency> 54 <groupId>org.springframework.security</groupId> 55 <artifactId>spring-security-test</artifactId> 56 <scope>test</scope> 57 </dependency>
1.2 配置application.properties
1 #server 2 server.port=8080 3 server.servlet.session.timeout=2520000 4 #redis 5 spring.redis.database=0 6 spring.redis.host=172.16.23.203 7 spring.redis.port=6379 8 spring.redis.password= 9 spring.redis.jedis.pool.max-active=8 10 spring.redis.jedis.pool.max-wait=60 11 spring.redis.jedis.pool.max-idle=8 12 spring.redis.jedis.pool.min-idle=0 13 spring.redis.timeout=10000
1.3 资源服务器配置
1 /** 2 * OAuth 资源服务器配置 3 * @author 4 * @date 2018-05-29 5 */ 6 @Configuration 7 @EnableResourceServer 8 public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { 9 10 private static final String DEMO_RESOURCE_ID = "order"; 11 12 @Override 13 public void configure(ResourceServerSecurityConfigurer resources) { 14 resources.resourceId(DEMO_RESOURCE_ID).stateless(true); 15 } 16 17 @Override 18 public void configure(HttpSecurity http) throws Exception { 19 // Since we want the protected resources to be accessible in the UI as well we need 20 // session creation to be allowed (it's disabled by default in 2.0.6) 21 http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) 22 .and() 23 .requestMatchers().anyRequest() 24 .and() 25 .anonymous() 26 .and() 27 .authorizeRequests() 28 .antMatchers("/order/**").authenticated();//配置order访问控制,必须认证过后才可以访问 29 } 30 }
1.4 授权服务器配置
1 /** 2 * OAuth 授权服务器配置 3 * @author 4 * @date 2018-05-29 5 */ 6 @Configuration 7 @EnableAuthorizationServer 8 public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { 9 10 private static final String DEMO_RESOURCE_ID = "order"; 11 12 @Autowired 13 AuthenticationManager authenticationManager; 14 @Autowired 15 RedisConnectionFactory redisConnectionFactory; 16 17 @Override 18 public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 19 String finalSecret = "{bcrypt}"+new BCryptPasswordEncoder().encode("123456"); 20 //配置两个客户端,一个用于password认证一个用于client认证 21 clients.inMemory() 22 .withClient("client_1") 23 .resourceIds(DEMO_RESOURCE_ID) 24 .authorizedGrantTypes("client_credentials", "refresh_token") 25 .scopes("select") 26 .authorities("oauth2") 27 .secret(finalSecret) 28 .and() 29 .withClient("client_2") 30 .resourceIds(DEMO_RESOURCE_ID) 31 .authorizedGrantTypes("password", "refresh_token") 32 .scopes("select") 33 .authorities("oauth2") 34 .secret(finalSecret); 35 } 36 37 @Override 38 public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 39 endpoints 40 .tokenStore(new RedisTokenStore(redisConnectionFactory)) 41 .authenticationManager(authenticationManager) 42 .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); 43 } 44 45 @Override 46 public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { 47 //允许表单认证 48 oauthServer.allowFormAuthenticationForClients(); 49 } 50 }
1.5 Spring Security配置
1 /** 2 * Spring-Security 配置<br> 3 * 具体参考: https://github.com/lexburner/oauth2-demo 4 * @author 5 * @date 2018-05-28 6 */ 7 @Configuration 8 @EnableWebSecurity 9 public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 10 11 @Bean 12 @Override 13 protected UserDetailsService userDetailsService(){ 14 InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); 15 BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); 16 String finalPassword = "{bcrypt}"+bCryptPasswordEncoder.encode("123456"); 17 manager.createUser(User.withUsername("user_1").password(finalPassword).authorities("USER").build()); 18 finalPassword = "{noop}123456"; 19 manager.createUser(User.withUsername("user_2").password(finalPassword).authorities("USER").build()); 20 return manager; 21 } 22 23 @Override 24 protected void configure(HttpSecurity http) throws Exception { 25 http 26 .requestMatchers().anyRequest() 27 .and() 28 .authorizeRequests() 29 .antMatchers("/oauth/*").permitAll(); 30 } 31 32 /** 33 * Spring Boot 2 配置,这里要bean 注入 34 */ 35 @Bean 36 @Override 37 public AuthenticationManager authenticationManagerBean() throws Exception { 38 AuthenticationManager manager = super.authenticationManagerBean(); 39 return manager; 40 } 41 42 @Bean 43 PasswordEncoder passwordEncoder() { 44 return PasswordEncoderFactories.createDelegatingPasswordEncoder(); 45 }
1.6 定义一个资源点
1 @RestController 2 @RequestMapping(value="/") 3 public class TestController { 4 5 @RequestMapping(value="order/demo") 6 public YYModel getDemo() { 7 Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 8 System.out.println(auth); 9 YYModel yy = new YYModel(); 10 yy.setYy("中文"); 11 yy.setZz(3); 12 return yy; 13 } 14 15 @GetMapping("/test") 16 public String getTest() { 17 YYModel yy = new YYModel(); 18 yy.setYy("中文"); 19 yy.setZz(3); 20 return yy.toJSONString(); 21 } 22 }
2. 工具测试
参考: http://blog.didispace.com/spring-security-oauth2-xjf-1/
作者:无脑仔的小明 出处:http://www.cnblogs.com/wunaozai/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 如果文中有什么错误,欢迎指出。以免更多的人被误导。有需要沟通的,可以站内私信,文章留言,或者关注“无脑仔的小明”公众号私信我。一定尽力回答。 |