当前位置:   article > 正文

Spring Boot + Spring Security + OAuth2 搭建 (一)_springboot springsecurity-oauth2-autoconfig

springboot springsecurity-oauth2-autoconfig

源代码地址:https://download.csdn.net/download/wllovar/10963011

具体那里有疑问可以给我发邮件1044560183@qq.com

最近应项目需求想搞一些类似微信公众平台那样的提供第三方访问的API,这就要用到OAuth2,具体OAuth2的认证流程如下图所示

好了废话不多说,我们开始干活

1.打开我们新建的SpringBoot项目,打开pom.xml,引入maven依赖包

  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.1.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.pdl</groupId>
  12. <artifactId>springboot</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>SpringBoot</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.boot</groupId>
  26. <artifactId>spring-boot-starter-test</artifactId>
  27. <scope>test</scope>
  28. </dependency>
  29. <!-- 加载postgresql驱动 -->
  30. <dependency>
  31. <groupId>org.postgresql</groupId>
  32. <artifactId>postgresql</artifactId>
  33. <scope>runtime</scope>
  34. </dependency>
  35. <!--加载postgresql驱动-->
  36. <dependency>
  37. <groupId>mysql</groupId>
  38. <artifactId>mysql-connector-java</artifactId>
  39. <scope>runtime</scope>
  40. </dependency>
  41. <!-- 加载jdbc连接数据库 -->
  42. <dependency>
  43. <groupId>org.springframework.boot</groupId>
  44. <artifactId>spring-boot-starter-jdbc</artifactId>
  45. </dependency>
  46. <!-- 加载mybatis jar包 -->
  47. <dependency>
  48. <groupId>org.mybatis.spring.boot</groupId>
  49. <artifactId>mybatis-spring-boot-starter</artifactId>
  50. <version>1.3.2</version>
  51. </dependency>
  52. <!-- aop依赖 jar包 -->
  53. <dependency>
  54. <groupId>org.springframework.boot</groupId>
  55. <artifactId>spring-boot-starter-aop</artifactId>
  56. </dependency>
  57. <!-- alibaba的druid数据库连接池 -->
  58. <dependency>
  59. <groupId>com.alibaba</groupId>
  60. <artifactId>druid-spring-boot-starter</artifactId>
  61. <version>1.1.9</version>
  62. </dependency>
  63. <!-- 分页插件 -->
  64. <dependency>
  65. <groupId>com.github.pagehelper</groupId>
  66. <artifactId>pagehelper-spring-boot-starter</artifactId>
  67. <version>1.2.5</version>
  68. </dependency>
  69. <!--json插件-->
  70. <dependency>
  71. <groupId>com.fasterxml.jackson.core</groupId>
  72. <artifactId>jackson-core</artifactId>
  73. </dependency>
  74. <dependency>
  75. <groupId>com.fasterxml.jackson.core</groupId>
  76. <artifactId>jackson-databind</artifactId>
  77. </dependency>
  78. <dependency>
  79. <groupId>com.fasterxml.jackson.datatype</groupId>
  80. <artifactId>jackson-datatype-joda</artifactId>
  81. </dependency>
  82. <dependency>
  83. <groupId>com.fasterxml.jackson.module</groupId>
  84. <artifactId>jackson-module-parameter-names</artifactId>
  85. </dependency>
  86. <dependency>
  87. <groupId>org.springframework.boot</groupId>
  88. <artifactId>spring-boot-starter-jta-atomikos</artifactId>
  89. </dependency>
  90. <dependency>
  91. <groupId>org.springframework.boot</groupId>
  92. <artifactId>spring-boot-starter-redis</artifactId>
  93. <version>1.4.7.RELEASE</version>
  94. </dependency>
  95. <!--安全框架 security-->
  96. <dependency>
  97. <groupId>org.springframework.boot</groupId>
  98. <artifactId>spring-boot-starter-security</artifactId>
  99. </dependency>
  100. <dependency>
  101. <groupId>org.springframework.security.oauth.boot</groupId>
  102. <artifactId>spring-security-oauth2-autoconfigure</artifactId>
  103. <version>2.0.3.RELEASE</version>
  104. </dependency>
  105. <!-- redis中 不用可以去除-->
  106. <dependency>
  107. <groupId>org.springframework.boot</groupId>
  108. <artifactId>spring-boot-starter-data-redis</artifactId>
  109. </dependency>
  110. <dependency>
  111. <groupId>commons-lang</groupId>
  112. <artifactId>commons-lang</artifactId>
  113. <version>2.6</version>
  114. </dependency>
  115. <dependency>
  116. <groupId>org.projectlombok</groupId>
  117. <artifactId>lombok</artifactId>
  118. <optional>true</optional>
  119. </dependency>
  120. <!-- mybatis-plus -->
  121. <dependency>
  122. <groupId>com.baomidou</groupId>
  123. <artifactId>mybatis-plus-boot-starter</artifactId>
  124. <version>3.0.4</version>
  125. </dependency>
  126. <!--swagger start-->
  127. <dependency>
  128. <groupId>io.springfox</groupId>
  129. <artifactId>springfox-swagger2</artifactId>
  130. <version>2.9.2</version>
  131. </dependency>
  132. <dependency>
  133. <groupId>io.springfox</groupId>
  134. <artifactId>springfox-swagger-ui</artifactId>
  135. <version>2.9.2</version>
  136. </dependency>
  137. <dependency>
  138. <groupId>org.springframework.boot</groupId>
  139. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  140. </dependency>
  141. <!--swagger end-->
  142. </dependencies>
  143. <build>
  144. <plugins>
  145. <plugin>
  146. <groupId>org.springframework.boot</groupId>
  147. <artifactId>spring-boot-maven-plugin</artifactId>
  148. </plugin>
  149. </plugins>
  150. </build>
  151. </project>

2.在config目录下新建认证服务端配置AuthorizationServerConfiguration.java

  1. package com.pdl.config;
  2. import com.pdl.security.BootClientDetailsService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.data.redis.connection.RedisConnectionFactory;
  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.password.PasswordEncoder;
  10. import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
  11. import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
  12. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
  13. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
  14. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
  15. import org.springframework.security.oauth2.provider.token.TokenStore;
  16. import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
  17. @Configuration
  18. @EnableAuthorizationServer
  19. public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
  20. @Autowired
  21. private AuthenticationManager authenticationManager;
  22. @Autowired
  23. private PasswordEncoder passwordEncoder;
  24. @Autowired
  25. private BootClientDetailsService clientDetailsService;
  26. @Override
  27. public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
  28. // 允许表单登录
  29. security.allowFormAuthenticationForClients();
  30. }
  31. @Override
  32. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  33. clients.withClientDetails(clientDetailsService);
  34. }
  35. @Override
  36. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  37. endpoints
  38. // tonken 存储于内存中
  39. .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)// add get method
  40. .tokenStore(new InMemoryTokenStore())
  41. .authenticationManager(authenticationManager);
  42. }
  43. }

3.在config目录下新建认证资源配置ResourceServerConfiguration.java

  1. package com.pdl.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  4. import org.springframework.security.config.http.SessionCreationPolicy;
  5. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
  6. import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
  7. import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
  8. @Configuration
  9. @EnableResourceServer
  10. public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
  11. @Override
  12. public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
  13. super.configure(resources);
  14. }
  15. @Override
  16. public void configure(HttpSecurity http) throws Exception {
  17. http
  18. .authorizeRequests()
  19. .antMatchers("/register").permitAll()
  20. .antMatchers("/druid/*").permitAll()
  21. .anyRequest()
  22. .authenticated();
  23. }
  24. }

注:如果需要开放某个接口不许认证操作时应该在ResourceServerConfiguration放开该方法的认证,具体实现是

.antMatchers("/register").permitAll()

如果不加这句话访问/register会一直报

{
    "error": "unauthorized",
    "error_description": "Full authentication is required to access this resource"
}

这个坑坑我了一天,解决后特此标注一下,以便小伙伴们不再趟坑

4.在config目录下新建WebSecurity 配置

  1. package com.pdl.config;
  2. import com.pdl.security.BootUserDetailService;
  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.core.annotation.Order;
  7. import org.springframework.security.authentication.AuthenticationManager;
  8. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  9. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  10. import org.springframework.security.config.annotation.web.builders.WebSecurity;
  11. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  12. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  13. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  14. import org.springframework.security.crypto.password.PasswordEncoder;
  15. /**
  16. * Created by wangle on 2018/12/28.
  17. */
  18. @Configuration
  19. @EnableWebSecurity
  20. @Order(1)
  21. public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  22. @Autowired
  23. private BootUserDetailService userDetailService;
  24. /**
  25. * 让Security 忽略这些url,不做拦截处理
  26. * @param web
  27. * @throws Exception
  28. */
  29. @Override
  30. public void configure(WebSecurity web) throws Exception {
  31. web.ignoring().antMatchers
  32. ("/swagger-ui.html/**", "/webjars/**",
  33. "/swagger-resources/**", "/v2/api-docs/**",
  34. "/swagger-resources/configuration/ui/**", "/swagger-resources/configuration/security/**",
  35. "/images/**");
  36. }
  37. @Override
  38. protected void configure(HttpSecurity http) throws Exception {
  39. http
  40. .formLogin().and()
  41. .requestMatchers()
  42. .antMatchers("/login","/oauth/authorize")
  43. .and()
  44. .authorizeRequests()
  45. .anyRequest()
  46. .authenticated();
  47. http.httpBasic().disable();
  48. }
  49. @Override
  50. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  51. auth.userDetailsService(userDetailService);
  52. }
  53. @Override
  54. @Bean
  55. public AuthenticationManager authenticationManager() throws Exception {
  56. return super.authenticationManager();
  57. }
  58. @Bean
  59. public PasswordEncoder passwordEncoder() {
  60. return new BCryptPasswordEncoder();
  61. }
  62. }

5.自定义自定义 UserDetailsService 和 BootClientDetailsService

  1. package com.pdl.security;
  2. import com.pdl.domain.User;
  3. import com.pdl.service.AdminService;
  4. import com.pdl.service.UserService;
  5. import org.apache.commons.lang.StringUtils;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.security.core.GrantedAuthority;
  10. import org.springframework.security.core.authority.AuthorityUtils;
  11. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  12. import org.springframework.security.core.userdetails.UserDetails;
  13. import org.springframework.security.core.userdetails.UserDetailsService;
  14. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  15. import org.springframework.stereotype.Component;
  16. import java.util.ArrayList;
  17. import java.util.List;
  18. @Component
  19. public class BootUserDetailService implements UserDetailsService {
  20. @Autowired
  21. private UserService userService;
  22. private Logger logger = LoggerFactory.getLogger(getClass());
  23. @Override
  24. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  25. User user= this.userService.selectUserByUsername(username);
  26. if(user==null) {
  27. throw new UsernameNotFoundException("用户名不存在");
  28. }
  29. GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
  30. List <GrantedAuthority>authorities = new ArrayList<>();
  31. authorities.add(authority);
  32. user.setAuthorities(authorities);
  33. return user;
  34. }
  35. }

新建类 BootClientDetailsService 实现ClientDetailsService 接口,覆盖loadClientByClientId(String clientId)方法,将其声明为spring组件,方便后面配置使用

  1. package com.pdl.security;
  2. import com.pdl.domain.Client;
  3. import com.pdl.service.AdminService;
  4. import com.pdl.service.UserService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.security.oauth2.provider.ClientDetails;
  7. import org.springframework.security.oauth2.provider.ClientDetailsService;
  8. import org.springframework.security.oauth2.provider.ClientRegistrationException;
  9. import org.springframework.stereotype.Component;
  10. @Component
  11. public final class BootClientDetailsService implements ClientDetailsService {
  12. @Autowired
  13. private UserService userService;
  14. @Override
  15. public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
  16. Client client = userService.selectClientByClientId(clientId);
  17. if(client==null){
  18. throw new ClientRegistrationException("客户端不存在");
  19. }
  20. return new BootClientDetails(client);
  21. }
  22. }
  1. package com.pdl.security;
  2. import com.pdl.domain.Client;
  3. import com.pdl.util.CommonUtils;
  4. import lombok.Data;
  5. import org.springframework.security.core.GrantedAuthority;
  6. import org.springframework.security.core.authority.AuthorityUtils;
  7. import org.springframework.security.oauth2.provider.ClientDetails;
  8. import java.util.Collection;
  9. import java.util.Map;
  10. import java.util.Set;
  11. /**
  12. * @author wangle
  13. * @date 2018/10/16 15:36
  14. *
  15. **/
  16. @Data
  17. @SuppressWarnings("unchecked")
  18. public final class BootClientDetails implements ClientDetails {
  19. private Client client;
  20. private Set<String> scope;
  21. public BootClientDetails(Client client) {
  22. this.client = client;
  23. }
  24. public BootClientDetails() {
  25. }
  26. @Override
  27. public String getClientId() {
  28. return client.getClientId();
  29. }
  30. @Override
  31. public Set<String> getResourceIds() {
  32. return client.getResourceIds()!=null?
  33. CommonUtils.transformStringToSet(client.getResourceIds(),String.class):null;
  34. }
  35. @Override
  36. public boolean isSecretRequired() {
  37. return client.getIsSecretRequired();
  38. }
  39. @Override
  40. public String getClientSecret() {
  41. return client.getClientSecret();
  42. }
  43. @Override
  44. public boolean isScoped() {
  45. return client.getIsScoped();
  46. }
  47. @Override
  48. public Set<String> getScope() {
  49. this.scope = client.getScope()!=null?
  50. CommonUtils.transformStringToSet(client.getScope(),String.class):null;
  51. return client.getScope()!=null?
  52. CommonUtils.transformStringToSet(client.getScope(),String.class):null;
  53. }
  54. @Override
  55. public Set<String> getAuthorizedGrantTypes() {
  56. return client.getAuthorizedGrantTypes()!=null?
  57. CommonUtils.transformStringToSet(client.getAuthorizedGrantTypes(),String.class):null;
  58. }
  59. @Override
  60. public Set<String> getRegisteredRedirectUri() {
  61. return client.getRegisteredRedirectUri()!=null?
  62. CommonUtils.transformStringToSet(client.getRegisteredRedirectUri(),String.class):null;
  63. }
  64. @Override
  65. public Collection<GrantedAuthority> getAuthorities() {
  66. return (client.getAuthorities()!=null&&client.getAuthorities().trim().length()>0)?
  67. AuthorityUtils.commaSeparatedStringToAuthorityList(client.getAuthorities()):null;
  68. }
  69. @Override
  70. public Integer getAccessTokenValiditySeconds() {
  71. return client.getAccessTokenValiditySeconds();
  72. }
  73. @Override
  74. public Integer getRefreshTokenValiditySeconds() {
  75. return client.getRefreshTokenValiditySeconds();
  76. }
  77. @Override
  78. public boolean isAutoApprove(String scope) {
  79. return this.client.getIsAutoApprove()==null ? false: this
  80. .client.getIsAutoApprove();
  81. }
  82. @Override
  83. public Map<String, Object> getAdditionalInformation() {
  84. return null;
  85. }
  86. }

6.在DAO层新建UserMapper.java

  1. package com.pdl.dao.crm;
  2. import com.pdl.domain.Client;
  3. import com.pdl.domain.User;
  4. import org.apache.ibatis.annotations.Mapper;
  5. import org.apache.ibatis.annotations.Param;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. @Mapper
  9. public interface UserMapper {
  10. List<User> selectAllUser();
  11. void insert(HashMap params);
  12. User selectUserByUserName( @Param("username") String username);
  13. Client selectClientByClientId(@Param("clientId") String clientId);
  14. int insertClient(Client client);
  15. }

7.在domain层新建实体类Client.java和User.java

  1. package com.pdl.domain;
  2. import com.baomidou.mybatisplus.annotation.TableField;
  3. import com.baomidou.mybatisplus.annotation.TableId;
  4. import com.baomidou.mybatisplus.annotation.TableName;
  5. import lombok.Data;
  6. import javax.validation.constraints.NotNull;
  7. /**
  8. * @author wangle
  9. * @date 2018/10/16 9:23
  10. *
  11. **/
  12. @Data
  13. @TableName("clients")
  14. public class Client {
  15. @TableId
  16. private String id;
  17. @TableField("clientId")
  18. @NotNull
  19. private String clientId;
  20. @TableField("resourceIds")
  21. private String resourceIds;
  22. @TableField("isSecretRequired")
  23. private Boolean isSecretRequired;
  24. @TableField("clientSecret")
  25. @NotNull
  26. private String clientSecret;
  27. @TableField("isScoped")
  28. private Boolean isScoped;
  29. @TableField("scope")
  30. private String scope;
  31. @TableField("authorizedGrantTypes")
  32. @NotNull
  33. private String authorizedGrantTypes;
  34. @TableField("registeredRedirectUri")
  35. @NotNull
  36. private String registeredRedirectUri;
  37. @TableField("authorities")
  38. private String authorities;
  39. @TableField("isAutoApprove")
  40. private Boolean isAutoApprove;
  41. @TableField("accessTokenValiditySeconds")
  42. @NotNull
  43. private Integer accessTokenValiditySeconds;
  44. @TableField("refreshTokenValiditySeconds")
  45. @NotNull
  46. private Integer refreshTokenValiditySeconds;
  47. @TableField("createTime")
  48. @NotNull
  49. private String createTime;
  50. @TableField("modifyTime")
  51. @NotNull
  52. private String modifyTime;
  53. }
  1. package com.pdl.domain;
  2. import com.baomidou.mybatisplus.annotation.TableField;
  3. import com.baomidou.mybatisplus.annotation.TableId;
  4. import com.baomidou.mybatisplus.annotation.TableName;
  5. import lombok.Data;
  6. import org.springframework.security.core.GrantedAuthority;
  7. import org.springframework.security.core.userdetails.UserDetails;
  8. import java.util.Collection;
  9. import java.util.List;
  10. /**
  11. * @author wangle
  12. * @date 2018/10/9 15:43
  13. *
  14. **/
  15. @Data
  16. @TableName("user")
  17. public class User implements UserDetails {
  18. @TableId
  19. private String id;
  20. private String username;
  21. private String email;
  22. @TableField("isEnable")
  23. private Boolean isEnable;
  24. @TableField("isExpired")
  25. private Boolean isExpired;
  26. @TableField("isLocked")
  27. private Boolean isLocked;
  28. private String password;
  29. private String gender;
  30. @TableField(exist = false)
  31. private List<GrantedAuthority> authorities;
  32. @Override
  33. public List<? extends GrantedAuthority> getAuthorities() {
  34. return authorities;
  35. }
  36. @Override
  37. public String getPassword() {
  38. return password;
  39. }
  40. @Override
  41. public String getUsername() {
  42. return username;
  43. }
  44. @Override
  45. public boolean isAccountNonExpired() {
  46. return true;
  47. }
  48. @Override
  49. public boolean isAccountNonLocked() {
  50. return this.isLocked;
  51. }
  52. @Override
  53. public boolean isCredentialsNonExpired() {
  54. return true;
  55. }
  56. @Override
  57. public boolean isEnabled() {
  58. return this.isEnable;
  59. }
  60. }

8.在service层新建UserService类

  1. package com.pdl.service;
  2. import com.pdl.dao.crm.UserMapper;
  3. import com.pdl.domain.Client;
  4. import com.pdl.domain.User;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import java.util.HashMap;
  8. import java.util.List;
  9. import java.util.Map;
  10. @Service
  11. public class UserService {
  12. @Autowired
  13. private UserMapper userMapper;
  14. public Map selectUser(){
  15. Map data = new HashMap();
  16. List<User> userList = userMapper.selectAllUser();
  17. data.put("recordList",userList);
  18. data.put("total",userList.size());
  19. return data;
  20. }
  21. public User selectUserByUsername(String username){
  22. User user = userMapper.selectUserByUserName(username);
  23. return user;
  24. }
  25. public Client selectClientByClientId(String clientId){
  26. Client client = userMapper.selectClientByClientId(clientId);
  27. return client;
  28. }
  29. public boolean addClient(Client client){
  30. boolean flag = false;
  31. int res = userMapper.insertClient(client);
  32. if(res==1){
  33. flag = true;
  34. }
  35. return flag;
  36. }
  37. }

9.在controller层新建ClientController.java

  1. package com.pdl.controller;
  2. import com.pdl.domain.Client;
  3. import com.pdl.security.response.BaseResponse;
  4. import com.pdl.security.response.HttpResponse;
  5. import com.pdl.service.UserService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.security.crypto.password.PasswordEncoder;
  8. import org.springframework.web.bind.annotation.PostMapping;
  9. import org.springframework.web.bind.annotation.RequestBody;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RestController;
  12. import javax.validation.Valid;
  13. import java.util.UUID;
  14. @RestController
  15. public class ClientController {
  16. @Autowired
  17. private UserService userService;
  18. @Autowired
  19. private PasswordEncoder passwordEncoder;
  20. @PostMapping("/register")
  21. public BaseResponse clientRegistered(@RequestBody @Valid Client client){
  22. client.setId(UUID.randomUUID().toString());
  23. client.setClientSecret(passwordEncoder.encode(client.getClientSecret()));
  24. boolean i = userService.addClient(client);
  25. return HttpResponse.baseResponse(200);
  26. }
  27. }

10.配置application.yml文件

  1. server:
  2. port: 8060
  3. spring:
  4. datasource:
  5. druid:
  6. crm:
  7. #配置监控统计拦截的filters,去掉后监控界面SQL无法进行统计,'wall'用于防火墙
  8. filters: stat,wall
  9. driver-class-name: com.mysql.jdbc.Driver
  10. url: jdbc:mysql://localhost:3306/pdl_oauth?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=GMT%2B8
  11. username: root
  12. password: 123456
  13. #初始化大小
  14. initial-size: 50
  15. #最小连接数
  16. min-idle: 50
  17. #最大连接数
  18. max-active: 200
  19. #获取连接等待超时时间
  20. max-wait: 60000
  21. #间隔多久才进行一次检测,检测需要关闭的空闲连接,单位毫秒
  22. time-between-eviction-runs-millis: 60000
  23. #一个连接在池中最小生存的时间,单位是毫秒
  24. min-evictable-idle-time-millis: 30000
  25. #测试语句是否执行正确
  26. validation-query: SELECT 'x'
  27. #指明连接是否被空闲连接回收器(如果有)进行检验.如果检测失败,则连接将被从池中去除.
  28. test-while-idle: true
  29. #借出连接时不要测试,否则很影响性能
  30. test-on-borrow: false
  31. test-on-return: false
  32. #打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
  33. pool-prepared-statements: false
  34. #与Oracle数据库PSCache有关,再druid下可以设置的比较高
  35. max-pool-prepared-statement-per-connection-size: 20
  36. #数据源2
  37. hr:
  38. filters: stat,wall
  39. driver-class-name: org.postgresql.Driver
  40. url: jdbc:postgresql://localhost:5432/pdl_hr?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
  41. username: postgres
  42. password: 123456
  43. initial-size: 50
  44. min-idle: 50
  45. max-active: 200
  46. max-wait: 60000
  47. time-between-eviction-runs-millis: 60000
  48. min-evictable-idle-time-millis: 30000
  49. validation-query: SELECT 'x'
  50. test-while-idle: true
  51. test-on-borrow: false
  52. test-on-return: false
  53. pool-prepared-statements: false
  54. max-pool-prepared-statement-per-connection-size: 20
  55. redis:
  56. host: 127.0.0.1
  57. port: 6379
  58. jedis:
  59. pool:
  60. max-active: 8
  61. max-wait: -1s
  62. min-idle: 0
  63. max-idle: 8
  64. security:

到此为止我们的项目搭建工作已经完成

访问http://localhost:8060/oauth/authorize?response_type=code&client_id=lovar&redirect_uri=http://www.baidu.com&scope=all

输入账号:admin ,密码:123qwe,进行登录进入授权页面

授权完成后会获得授权码https://www.baidu.com/?code=OJN1hB

接下来在postman上进行操作

授权码的操作已完成,下面我们开始测试注册客户端,打开http://localhost:8060/swagger-ui.html

访问/register接口进行客户端注册

  1. {
  2.   "accessTokenValiditySeconds": 1800,
  3.   "authorities": "ADMIN",
  4.   "authorizedGrantTypes": "refresh_token,authorization_code",
  5.   "clientId": "lovar",
  6.   "clientSecret": "123456",
  7.   "isAutoApprove": false,
  8.   "isSecretRequired": true,
  9.   "refreshTokenValiditySeconds": 3600,
  10.   "registeredRedirectUri": "http://localhost:8060",
  11.   "scope": "all",
  12.   "scoped": true,
  13.   "secretRequired": true,
  14. "createTime": "2019-02-18 00:12:10",
  15.   "modifyTime": "2019-02-18 00:12:10",
  16.   "resourceIds": "boot-server"
  17. }

 

 

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号