springcloud Oauth2授权,四种授权类型

叁歲伎倆 2022-12-21 04:45 306阅读 0赞

db4a039f80624659e92b7244870a0228.png

创建认证服务器:

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. springcloud1
  6. org.example
  7. 1.0-SNAPSHOT
  8. 4.0.0
  9. springcloud-oauth-uaa-8003
  10. org.springframework.cloud
  11. spring-cloud-dependencies
  12. Finchley.RELEASE
  13. pom
  14. import
  15. org.springframework.boot
  16. spring-boot-starter-web
  17. 2.1.4.RELEASE
  18. org.springframework.boot
  19. spring-boot-test
  20. org.springframework.cloud
  21. spring-cloud-netflix-eureka-client
  22. org.springframework.boot
  23. spring-boot-starter-security
  24. org.springframework.cloud
  25. spring-cloud-starter-oauth2
  26. org.springframework.security
  27. spring-security-jwt

创建认证服务器配置类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

bd17f620320d094ac15393c98792793b.png

这个就是授权码:
7310a3a497de9cb6c0aa909fee19f60a.png

然后通过授权码获取token:

0513c06d744cf510cdf8a65cfda2aa67.png

密码模式(直接通过账号密码获取token):

28ce1e0a87af842e003a4a5a45942038.png

发表评论

表情:
评论列表 (有 0 条评论,306人围观)

还没有评论,来说两句吧...

相关阅读

    相关 OAuth2授权方式

    最近在做第三方接入的,初步定下使用OAuth2协议,花了些时间对OAuth2的授权方式做了些了解。   我还记得一两年前,跟一位同事聊起互联网时,当时我说过一个想法: