天天看點

springcloud Oauth2授權,四種授權類型

springcloud Oauth2授權,四種授權類型

建立認證伺服器:

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. <artifactId>springcloud-oauth-uaa-8003</artifactId>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.cloud</groupId>
  15. <artifactId>spring-cloud-dependencies</artifactId>
  16. <version>Finchley.RELEASE</version>
  17. <type>pom</type>
  18. <scope>import</scope>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-web</artifactId>
  23. <version>2.1.4.RELEASE</version>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-test</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.cloud</groupId>
  31. <artifactId>spring-cloud-netflix-eureka-client</artifactId>
  32. </dependency>
  33. <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
  34. <dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-starter-security</artifactId>
  37. </dependency>
  38. <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-oauth2 -->
  39. <dependency>
  40. <groupId>org.springframework.cloud</groupId>
  41. <artifactId>spring-cloud-starter-oauth2</artifactId>
  42. </dependency>
  43. <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-jwt -->
  44. <dependency>
  45. <groupId>org.springframework.security</groupId>
  46. <artifactId>spring-security-jwt</artifactId>
  47. </dependency>
  48. </dependencies>
  49. </project>

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

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

建立security配置實作類WebSecurityConfigurerAdapter:

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

擷取授權碼方式:

授權碼模式:

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

springcloud Oauth2授權,四種授權類型

這個就是授權碼:

springcloud Oauth2授權,四種授權類型

然後通過授權碼擷取token:

springcloud Oauth2授權,四種授權類型

密碼模式(直接通過賬号密碼擷取token):

springcloud Oauth2授權,四種授權類型