当前位置:   article > 正文

springboot 2.1.4 集成Spring Security oauth2 —— 2.3.5.RELEASE,修复各种5.0以上坑..._spring-security-oauth2-2.3.5.release

spring-security-oauth2-2.3.5.release

oauth2 定义了下面四种授权方式:

  • 授权码模式(authorization code)
  • 简化模式(implicit)
  • 密码模式(resource owner password credentials)
  • 客户端模式(client credentials)

* response_type:表示授权类型,必选项,此处的值固定为"code"

* client_id:表示客户端的ID,必选项

* redirect_uri:表示重定向URI,可选项

* scope:表示申请的权限范围,可选项

* state:表示客户端的当前状态,可以指定任意值,认证服务器会原封不动地返回这个值。

上代码:

  1. package com.oath.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.http.HttpMethod;
  5. import org.springframework.security.authentication.AuthenticationManager;
  6. import org.springframework.security.core.userdetails.UserDetailsService;
  7. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  8. import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
  9. import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
  10. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
  11. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
  12. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
  13. @Configuration
  14. @EnableAuthorizationServer
  15. public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {
  16. @Autowired
  17. private AuthenticationManager authenticationManager;
  18. @Autowired
  19. private BCryptPasswordEncoder bCryptPasswordEncoder;
  20. @Autowired
  21. private UserDetailsService userDetailsService;
  22. @Override
  23. public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
  24. oauthServer.realm("oauth2-resources") // code授权添加
  25. .tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()") // allow check token
  26. .allowFormAuthenticationForClients();
  27. }
  28. @Override
  29. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  30. endpoints.authenticationManager(authenticationManager)
  31. // 允许 GET、POST 请求获取 token,即访问端点:oauth/token
  32. .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
  33. // 要使用refresh_token的话,需要额外配置userDetailsService
  34. endpoints.userDetailsService(userDetailsService);
  35. }
  36. @Override
  37. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  38. clients.inMemory().withClient("demoApp").secret(bCryptPasswordEncoder.encode("demoAppSecret"))
  39. .redirectUris("http://baidu.com")// code授权添加
  40. .authorizedGrantTypes("authorization_code", "client_credentials", "password", "refresh_token")
  41. .scopes("all").resourceIds("oauth2-resource").accessTokenValiditySeconds(1200)
  42. .refreshTokenValiditySeconds(50000);
  43. }
  44. }

 

 

资源服务器:

  1. package com.oath.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  4. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
  5. import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
  6. @Configuration
  7. @EnableResourceServer
  8. public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
  9. @Override
  10. public void configure(HttpSecurity http) throws Exception {
  11. http.requestMatchers().antMatchers("/api/**").and().authorizeRequests().antMatchers("/api/**").authenticated();
  12. }
  13. }

安全配置:

  1. package com.oath.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.security.authentication.AuthenticationManager;
  4. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  5. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  6. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  7. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  8. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  9. import org.springframework.security.core.userdetails.User;
  10. import org.springframework.security.core.userdetails.UserDetailsService;
  11. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  12. import org.springframework.security.provisioning.InMemoryUserDetailsManager;
  13. @EnableGlobalMethodSecurity(prePostEnabled = true)
  14. @EnableWebSecurity
  15. public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  16. @Bean
  17. public BCryptPasswordEncoder passwordEncoder() {
  18. return new BCryptPasswordEncoder();
  19. }
  20. /**
  21. * anyRequest | 匹配所有请求路径
  22. * access | SpringEl表达式结果为true时可以访问
  23. * anonymous | 匿名可以访问
  24. * denyAll | 用户不能访问
  25. * fullyAuthenticated | 用户完全认证可以访问(非remember-me下自动登录)
  26. * hasAnyAuthority | 如果有参数,参数表示权限,则其中任何一个权限可以访问
  27. * hasAnyRole | 如果有参数,参数表示角色,则其中任何一个角色可以访问
  28. * hasAuthority | 如果有参数,参数表示权限,则其权限可以访问
  29. * hasIpAddress | 如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
  30. * hasRole | 如果有参数,参数表示角色,则其角色可以访问
  31. * permitAll | 用户可以任意访问
  32. * rememberMe | 允许通过remember-me登录的用户访问
  33. * authenticated | 用户登录后可访问
  34. */
  35. @Override
  36. public void configure(HttpSecurity http) throws Exception {
  37. http.csrf().disable();
  38. http.requestMatchers().antMatchers("/oauth/**", "/login/**", "/logout/**").and().authorizeRequests()
  39. .antMatchers("/oauth/**").authenticated().and().formLogin().permitAll();
  40. }
  41. // 配置内存模式的用户
  42. @Bean
  43. @Override
  44. protected UserDetailsService userDetailsService() {
  45. InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
  46. manager.createUser(User.withUsername("demoUser1").password(this.passwordEncoder().encode("123456"))
  47. .authorities("USER").build());
  48. manager.createUser(User.withUsername("demoUser2").password(this.passwordEncoder().encode("123456"))
  49. .authorities("USER").build());
  50. return manager;
  51. }
  52. @Override
  53. @Bean
  54. public AuthenticationManager authenticationManagerBean() throws Exception {
  55. return super.authenticationManagerBean();
  56. }
  57. @Override
  58. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  59. auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
  60. }
  61. }

 

测试接口:

  1. package com.oath.controller;
  2. import org.springframework.web.bind.annotation.PathVariable;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. @RestController
  6. @RequestMapping("/api")
  7. public class HelloOath2Controller {
  8. @RequestMapping("/hello/{id}")
  9. public String helloOath2(@PathVariable long id) {
  10. System.out.println("请求的ID编码为:" + id);
  11. return "helloOath2";
  12. }
  13. }

启动类:

  1. package com.oath;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class SpingbootOath2DemoApplication {
  6. /**
  7. * *【密码授权模式-client】
  8. * 密码模式需要参数:username,password,grant_type,client_id,client_secret
  9. * http://localhost:8080/oauth/token?username=demoUser1&password=123456&grant_type=password&client_id=demoApp&client_secret=demoAppSecret
  10. *
  11. * *【客户端授权模式-password】 客户端模式需要参数:grant_type,client_id,client_secret
  12. * http://localhost:8080/oauth/token?grant_type=client_credentials&client_id=demoApp&client_secret=demoAppSecret
  13. *
  14. * *【授权码模式-code】 获取code
  15. * http://localhost:8080/oauth/authorize?response_type=code&client_id=demoApp&redirect_uri=http://baidu.com
  16. *
  17. ** 【通过code】 换token
  18. * http://localhost:8080/oauth/token?grant_type=authorization_code&code=Filepd&client_id=demoApp&client_secret=demoAppSecret&redirect_uri=http://baidu.com
  19. * 这里的code字段是授权码模式中返回的code 例如: https://www.baidu.com/?code=tsuHSh
  20. *
  21. ** 【通过refresh token】 刷新token
  22. * http://localhost:8080/oauth/token?grant_type=refresh_token&refresh_token=7ba47059-d853-4050-9c64-69d0cade71a7&client_id=demoApp&client_secret=demoAppSecret
  23. * 其中grant_type为固定值:grant_type=refresh_token , refresh_token = 通过code获取的token中的refresh_token
  24. *
  25. */
  26. public static void main(String[] args) {
  27. SpringApplication.run(SpingbootOath2DemoApplication.class, args);
  28. }
  29. }

POM依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.1.4.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.oath.demo</groupId>
  12. <artifactId>spingboot-oath2-demo</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>spingboot-oath2-demo</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-web</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.security.oauth</groupId>
  26. <artifactId>spring-security-oauth2</artifactId>
  27. <version>2.3.5.RELEASE</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-security</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.projectlombok</groupId>
  35. <artifactId>lombok</artifactId>
  36. <optional>true</optional>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-starter-test</artifactId>
  41. <scope>test</scope>
  42. </dependency>
  43. </dependencies>
  44. <build>
  45. <plugins>
  46. <plugin>
  47. <groupId>org.springframework.boot</groupId>
  48. <artifactId>spring-boot-maven-plugin</artifactId>
  49. </plugin>
  50. </plugins>
  51. </build>
  52. </project>

 

测试:

  1. 【密码授权模式-client】
  2. 密码模式需要参数:username,password,grant_type,client_id,client_secret
  3. http://localhost:8080/oauth/token?username=demoUser1&password=123456&grant_type=password&client_id=demoApp&client_secret=demoAppSecret
  4. 【客户端授权模式-password】
  5. 客户端模式需要参数:grant_type,client_id,client_secret
  6. http://localhost:8080/oauth/token?grant_type=client_credentials&client_id=demoApp&client_secret=demoAppSecret
  7. 【授权码模式-code】
  8. 获取code
  9. http://localhost:8080/oauth/authorize?response_type=code&client_id=demoApp&redirect_uri=http://baidu.com
  10. 通过code换token(注意:code参数为授权码模式返回的参数)
  11. http://localhost:8080/oauth/token?grant_type=authorization_code&code=Filepd&client_id=demoApp&client_secret=demoAppSecret&redirect_uri=http://baidu.com
  12. 【通过refresh token】 刷新token
  13. http://localhost:8080/oauth/token?grant_type=refresh_token&refresh_token=7ba47059-d853-4050-9c64-69d0cade71a7&client_id=demoApp&client_secret=demoAppSecret
  14. 其中grant_type为固定值:grant_type=refresh_token , refresh_token = 通过code获取的token中的refresh_token
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/83438
推荐阅读
相关标签
  

闽ICP备14008679号