springcloud Oauth2授權,四種授權型別

1024小神發表於2020-11-14

建立認證伺服器:

pom依賴:

 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>springcloud1</artifactId>
  7. <groupId>org.example</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11.  
  12. <artifactId>springcloud-oauth-uaa-8003</artifactId>
  13.  
  14.  
  15. <dependencies>
  16.  
  17. <dependency>
  18. <groupId>org.springframework.cloud</groupId>
  19. <artifactId>spring-cloud-dependencies</artifactId>
  20. <version>Finchley.RELEASE</version>
  21. <type>pom</type>
  22. <scope>import</scope>
  23. </dependency>
  24.  
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-web</artifactId>
  28. <version>2.1.4.RELEASE</version>
  29. </dependency>
  30.  
  31. <dependency>
  32. <groupId>org.springframework.boot</groupId>
  33. <artifactId>spring-boot-test</artifactId>
  34. </dependency>
  35.  
  36. <dependency>
  37. <groupId>org.springframework.cloud</groupId>
  38. <artifactId>spring-cloud-netflix-eureka-client</artifactId>
  39. </dependency>
  40.  
  41. <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
  42. <dependency>
  43. <groupId>org.springframework.boot</groupId>
  44. <artifactId>spring-boot-starter-security</artifactId>
  45. </dependency>
  46.  
  47. <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-oauth2 -->
  48. <dependency>
  49. <groupId>org.springframework.cloud</groupId>
  50. <artifactId>spring-cloud-starter-oauth2</artifactId>
  51. </dependency>
  52.  
  53. <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-jwt -->
  54. <dependency>
  55. <groupId>org.springframework.security</groupId>
  56. <artifactId>spring-security-jwt</artifactId>
  57. </dependency>
  58.  
  59.  
  60.  
  61. </dependencies>
  62.  
  63.  
  64. </project>

 

建立認證伺服器配置類AuthorizationServerConfigurerAdapter:

 
  1. package com.shen.config;
  2.  
  3. import jdk.nashorn.internal.parser.Token;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.http.HttpMethod;
  8. import org.springframework.security.authentication.AuthenticationManager;
  9. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  10. import org.springframework.security.crypto.factory.PasswordEncoderFactories;
  11. import org.springframework.security.crypto.password.PasswordEncoder;
  12. import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
  13. import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
  14. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
  15. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
  16. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
  17. import org.springframework.security.oauth2.provider.ClientDetailsService;
  18. import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
  19. import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
  20. import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
  21. import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
  22. import org.springframework.security.oauth2.provider.token.TokenStore;
  23. import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
  24.  
  25. @Configuration
  26. @EnableAuthorizationServer
  27. public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
  28.  
  29. @Bean
  30. public PasswordEncoder passwordEncoder() {
  31. return new BCryptPasswordEncoder();
  32. }
  33.  
  34. @Bean
  35. public AuthorizationCodeServices authorizationCodeServices(){
  36. // 配置授權碼服務
  37. return new InMemoryAuthorizationCodeServices();
  38. }
  39.  
  40. @Bean
  41. public TokenStore tokenStore(){
  42. return new InMemoryTokenStore();
  43. }
  44.  
  45. @Autowired
  46. private TokenStore tokenStore;
  47.  
  48. @Autowired
  49. private AuthorizationCodeServices authorizationCodeServices;
  50.  
  51. @Autowired
  52. private AuthenticationManager authenticationManager;
  53.  
  54. @Override
  55. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  56. clients.inMemory()
  57. .withClient("client1")
  58. .secret(new BCryptPasswordEncoder().encode("secret"))
  59. .authorizedGrantTypes("client_credentials", "password", "refresh_token", "authorization_code")
  60. .scopes("all")
  61. .resourceIds("all")
  62. .autoApprove(false)
  63. .redirectUris("http://www.baidu.com")
  64. .accessTokenValiditySeconds(1200)
  65. .refreshTokenValiditySeconds(50000);
  66. }
  67.  
  68. @Autowired
  69. private ClientDetailsService clientDetailsService;
  70.  
  71. @Bean
  72. public AuthorizationServerTokenServices tokenServices(){
  73. DefaultTokenServices services = new DefaultTokenServices();
  74. services.setClientDetailsService(clientDetailsService);
  75. services.setSupportRefreshToken(true);
  76. services.setTokenStore(tokenStore);
  77. services.setAccessTokenValiditySeconds(7200);
  78. services.setRefreshTokenValiditySeconds(36000);
  79. return services;
  80. }
  81.  
  82. @Override
  83. public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
  84. oauthServer
  85. .tokenKeyAccess("permitAll()")
  86. //allow check token
  87. .checkTokenAccess("permitAll()")
  88. .allowFormAuthenticationForClients();
  89. }
  90.  
  91.  
  92. @Override
  93. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  94. endpoints.
  95. authenticationManager(authenticationManager)
  96. .authorizationCodeServices(authorizationCodeServices)
  97. .tokenServices(tokenServices())
  98. .allowedTokenEndpointRequestMethods(HttpMethod.POST);
  99. }
  100.  
  101.  
  102. }

建立security配置實現類WebSecurityConfigurerAdapter:

 
  1. package com.shen.config;
  2.  
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.security.authentication.AuthenticationManager;
  6. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  7. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  8. import org.springframework.security.config.annotation.web.builders.WebSecurity;
  9. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  10. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  11. import org.springframework.security.crypto.password.PasswordEncoder;
  12.  
  13. @Configuration
  14. public class MySecurityConfig extends WebSecurityConfigurerAdapter {
  15.  
  16. private PasswordEncoder passwordEncoder() {
  17. return new BCryptPasswordEncoder();
  18. }
  19.  
  20. @Override
  21. @Bean
  22. public AuthenticationManager authenticationManagerBean() throws Exception {
  23. return super.authenticationManagerBean();
  24. }
  25.  
  26. @Override
  27. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  28. // Spring Security提供了一套基於記憶體的驗證
  29. auth.inMemoryAuthentication()
  30. .passwordEncoder(new BCryptPasswordEncoder())
  31. .withUser("admin").password(new BCryptPasswordEncoder()
  32. .encode("123456")).roles("r1");
  33. }
  34.  
  35. @Override
  36. protected void configure(HttpSecurity http) throws Exception {
  37. // 決定那些請求被攔截
  38. http
  39. .authorizeRequests()
  40. .antMatchers("/css/**", "/js/**", "/fonts/**", "/index").permitAll() //都可以訪問
  41. // .antMatchers("").permitAll()// 主路徑放行
  42. .anyRequest().permitAll()// 其他請求需經過驗證
  43. .and()
  44. .formLogin()
  45. .loginProcessingUrl("/login")
  46. .permitAll()// 表單登入允許任意許可權訪問
  47. .and()
  48. .logout().permitAll();// 登出操作允許任意許可權訪問
  49. http.csrf().disable();// 關閉預設的csrf認證
  50. }
  51.  
  52. // @Override
  53. // public void configure(WebSecurity web) throws Exception {
  54. // web.ignoring().antMatchers("/js'/**", "/css/**", "/images/**");// 對js、css、images不做攔截
  55. // }
  56. }

 

獲取授權碼方式:

授權碼模式:

訪問此連結獲取授權碼:http://localhost:8003/oauth/authorize?response_type=code&client_id=client1&redirect_uri=http://www.baidu.com

這個就是授權碼:

 

然後通過授權碼獲取token:

 

密碼模式(直接通過賬號密碼獲取token):

相關文章