当前位置:   article > 正文

oauth2密码授权模式_/oauth2/token

/oauth2/token

Oauth2提供的默认端点

  • /oauth/authorize:授权端点
  • /oauth/token:令牌端点
  • /oauth/confirm_access:用户确认授权提交端点
  • /oauth/error:授权服务错误信息端点
  • /oauth/check_token:用于资源服务访问的令牌解析端点
  • /oauth/token_key:提供公有密匙的端点,如果使用JWT令牌的话

===============================================================================================

注:grant_type、scope、client_id需要和AuthorizationServerConfig中配置的一样

1.模式获取access_token

http://localhost:8080/oauth/token?username=user&password=123456&grant_type=password&scope=select&client_id=client_2&client_secret=123456

2.刷新access_token

http://localhost:8080/oauth/token?grant_type=refresh_token&refresh_token=8495d597-0560-4598-95ef-143c0855363c&client_id=client_2&client_secret=123456

3.访问受保护的资源

http://localhost:8080/order/1?access_token=b3d2c131-1225-45b4-9ff5-51ec17511cee

===============================================================================================

security oauth2 整合的3个核心配置类

  • 1.资源服务配置 ResourceServerConfiguration  (配置需要认证的接口)
  • 2.授权认证服务配置 AuthorizationServerConfiguration (配置认证方式和token的存储)
  • 3.security 配置 WebSecurityConfig (配置oauth2的过滤请求,如/oauth)

===============================================================================================

pom.xml

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-security</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.security.oauth</groupId>
  8. <artifactId>spring-security-oauth2</artifactId>
  9. <version>2.3.6.RELEASE</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-web</artifactId>
  14. </dependency>
  15. <dependency>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-starter-data-redis</artifactId>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-test</artifactId>
  26. <scope>test</scope>
  27. </dependency>
  28. <dependency>
  29. <groupId>mysql</groupId>
  30. <artifactId>mysql-connector-java</artifactId>
  31. <version>8.0.17</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>com.baomidou</groupId>
  35. <artifactId>mybatis-plus-boot-starter</artifactId>
  36. <version>3.1.2</version>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.projectlombok</groupId>
  40. <artifactId>lombok</artifactId>
  41. <optional>true</optional>
  42. </dependency>
  43. <dependency>
  44. <groupId>cn.hutool</groupId>
  45. <artifactId>hutool-all</artifactId>
  46. <version>4.6.1</version>
  47. <scope>test</scope>
  48. </dependency>
  49. </dependencies>

===============================================================================================

认证授权配置AuthorizationServerConfigurerAdapter.java

  1. package com.kejin.oauth2test.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.data.redis.connection.RedisConnectionFactory;
  5. import org.springframework.http.HttpMethod;
  6. import org.springframework.security.authentication.AuthenticationManager;
  7. import org.springframework.security.core.userdetails.UserDetailsService;
  8. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  9. import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
  10. import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
  11. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
  12. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
  13. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
  14. import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
  15. @Configuration
  16. @EnableAuthorizationServer
  17. public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  18. private static final String RESOURCE_IDS = "order";
  19. @Autowired
  20. AuthenticationManager authenticationManager;
  21. @Autowired
  22. RedisConnectionFactory redisConnectionFactory;
  23. @Autowired
  24. private UserDetailsService userDetailsService;
  25. @Override
  26. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  27. String finalSecret = "{bcrypt}" + new BCryptPasswordEncoder().encode("123456");
  28. //配置两个客户端,一个用于password认证一个用于client认证
  29. clients.inMemory()
  30. //client模式
  31. .withClient("client_1")
  32. .authorizedGrantTypes("client_credentials", "refresh_token")
  33. .scopes("select")
  34. .authorities("oauth2")
  35. .secret(finalSecret)
  36. .and()
  37. //密码模式
  38. .withClient("client_2")
  39. .authorizedGrantTypes("password", "refresh_token")
  40. .scopes("select")
  41. .authorities("oauth2")
  42. .secret(finalSecret);
  43. }
  44. /**
  45. * 认证服务端点配置
  46. */
  47. @Override
  48. public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
  49. endpoints
  50. //用户管理
  51. .userDetailsService(userDetailsService)
  52. //token存到redis
  53. .tokenStore(new RedisTokenStore(redisConnectionFactory))
  54. //启用oauth2管理
  55. .authenticationManager(authenticationManager)
  56. //接收GET和POST
  57. .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
  58. }
  59. @Override
  60. public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
  61. oauthServer.allowFormAuthenticationForClients();
  62. }
  63. }

===============================================================================================

security 配置 WebSecurityConfig

  1. package com.kejin.oauth2test.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.web.builders.HttpSecurity;
  6. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  7. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  8. import org.springframework.security.crypto.factory.PasswordEncoderFactories;
  9. import org.springframework.security.crypto.password.PasswordEncoder;
  10. @Configuration
  11. @EnableWebSecurity
  12. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  13. @Bean
  14. PasswordEncoder passwordEncoder() {
  15. return PasswordEncoderFactories.createDelegatingPasswordEncoder();
  16. }
  17. /**
  18. * 注入AuthenticationManager接口,启用OAuth2密码模式
  19. *
  20. * @return
  21. * @throws Exception
  22. */
  23. @Bean
  24. @Override
  25. public AuthenticationManager authenticationManagerBean() throws Exception {
  26. AuthenticationManager manager = super.authenticationManagerBean();
  27. return manager;
  28. }
  29. /**
  30. * 通过HttpSecurity实现Security的自定义过滤配置
  31. *
  32. * @param httpSecurity
  33. * @throws Exception
  34. */
  35. @Override
  36. protected void configure(HttpSecurity httpSecurity) throws Exception {
  37. httpSecurity
  38. .requestMatchers().anyRequest()
  39. .and()
  40. .authorizeRequests()
  41. .antMatchers("/oauth/**").permitAll();
  42. }
  43. }

 ===============================================================================================

AuthUser

  1. package com.kejin.oauth2test.entity;
  2. import lombok.Data;a
  3. import org.springframework.security.core.GrantedAuthority;
  4. import org.springframework.security.core.userdetails.User;
  5. import java.util.Collection;
  6. @Data
  7. public class AuthUser extends User {
  8. private Integer id;
  9. public AuthUser(Integer id,
  10. String username,
  11. String password,
  12. boolean enabled,
  13. boolean accountNonExpired,
  14. boolean credentialsNonExpired,
  15. boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
  16. super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
  17. this.id = id;
  18. }
  19. }

 =============================================================================================== 

获取用户信息UserDetailsServiceImplement

  1. package com.kejin.oauth2test.service.impl;
  2. import com.kejin.oauth2test.entity.AuthUser;
  3. import com.kejin.oauth2test.entity.User;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.security.core.GrantedAuthority;
  6. import org.springframework.security.core.userdetails.UserDetails;
  7. import org.springframework.security.core.userdetails.UserDetailsService;
  8. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  9. import org.springframework.stereotype.Service;
  10. import java.util.Collection;
  11. @Service
  12. public class UserDetailsServiceImpl implements UserDetailsService {
  13. @Autowired
  14. private UserServiceImpl userService;
  15. /**
  16. * 实现UserDetailsService中的loadUserByUsername方法,用于加载用户数据
  17. */
  18. @Override
  19. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  20. User user = userService.queryUserByUsername(username);
  21. if (user == null) {
  22. throw new UsernameNotFoundException("用户不存在");
  23. }
  24. //用户权限列表
  25. Collection<? extends GrantedAuthority> authorities = userService.queryUserAuthorities(user.getId());
  26. return new AuthUser(
  27. user.getId(),
  28. user.getUsername(),
  29. user.getPassword(),
  30. true,
  31. true,
  32. true,
  33. true,
  34. authorities);
  35. }
  36. }

 ===============================================================================================

application.yml

  1. server:
  2. port: 8080
  3. spring:
  4. thymeleaf:
  5. encoding: UTF-8
  6. cache: false
  7. datasource:
  8. driver-class-name: com.mysql.cj.jdbc.Driver
  9. url: jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC
  10. username: root
  11. password: root12
  12. redis:
  13. host: 127.0.0.1
  14. port: 6379
  15. password:
  16. logging.level.org.springframework.security: DEBUG

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/84153
推荐阅读
相关标签
  

闽ICP备14008679号