当前位置:   article > 正文

Spring Security 0auth2 认证服务器和资源服务器实现_preauthenticatedauthenticationprovider

preauthenticatedauthenticationprovider

一,OAuth2开放授权协议/标准

OAuth(开放授权)是⼀个开放协议/标准,允许⽤户授权第三⽅应⽤访问他们存储在另外的服务提供者

上的信息,⽽不需要将⽤户名和密码提供给第三⽅应⽤或分享他们数据的所有内容。

允许⽤户授权第三⽅应⽤访问他们存储在另外的服务提供者上的信息,⽽不需要将⽤户名和密码提供给

第三⽅应⽤或分享他们数据的所有内容

client_id :客户端id(QQ最终相当于⼀个认证授权服务器,木瓜餐饮就相当于⼀个客户端了,所以会

给 ⼀个客户端id),相当于账号

secret:相当于密码

资源所有者(Resource Owner):可以理解为⽤户⾃⼰

客户端(Client):我们想登陆的⽹站或应⽤,⽐如淘宝

认证服务器(Authorization Server):可以理解为微信或者QQ

资源服务器(Resource Server):可以理解为微信或者QQ

二、什么情况下需要使用OAuth2

第三⽅授权登录的场景:⽐如,我们经常登录⼀些⽹站或者应⽤的时候,可以选择使⽤第三⽅授权登录

的⽅式,⽐如:微信授权登录、QQ授权登录、微博授权登录等,这是典型的 OAuth2 使⽤场景。

单点登录的场景:如果项⽬中有很多微服务或者公司内部有很多服务,可以专⻔做⼀个认证中⼼(充当

认证平台⻆⾊),所有的服务都要到这个认证中⼼做认证,只做⼀次登录,就可以在多个授权范围内的

服务中⾃由串⾏。

OAuth2的颁发Token授权⽅式

1)授权码(authorization-code)2)密码式(password)提供⽤户名+密码换取token令牌

3)隐藏式(implicit)

4)客户端凭证(client credentials)

授权码模式使⽤到了回调地址,是最复杂的授权⽅式,微博、微信、QQ等第三⽅登录就是这种模式。我

们说接⼝对接中常使⽤的password密码模式(提供⽤户名+密码换取token)。

三、Spring Cloud OAuth2 + JWT 实现

Spring Cloud OAuth2 是 Spring Cloud 体系对OAuth2协议的实现,可以⽤来做多个微服务的统⼀认证

(验证身份合法性)授权(验证权限)。通过向OAuth2服务(统⼀认证授权服务)发送某个类型的

grant_type进⾏集中认证和授权,从⽽获得access_token(访问令牌),⽽这个token是受其他微服务

信任的。

注意:使⽤OAuth2解决问题的本质是,引⼊了⼀个认证授权层,认证授权层连接了资源的拥有者,在

授权层⾥⾯,资源的拥有者可以给第三⽅应⽤授权去访问我们的某些受保护资源

1,授权服务器

1,pom 导入

  1. <!--导入spring cloud oauth2依赖-->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-oauth2</artifactId>
  5. <version>2.1.0.RELEASE</version>
  6. <exclusions>
  7. <exclusion>
  8. <groupId>org.springframework.security.oauth.boot</groupId>
  9. <artifactId>spring-security-oauth2-autoconfigure</artifactId>
  10. </exclusion>
  11. </exclusions>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.springframework.security.oauth.boot</groupId>
  15. <artifactId>spring-security-oauth2-autoconfigure</artifactId>
  16. <version>2.1.11.RELEASE</version>
  17. </dependency>
  18. <!--引入security对oauth2的支持-->
  19. <dependency>
  20. <groupId>org.springframework.security.oauth</groupId>
  21. <artifactId>spring-security-oauth2</artifactId>
  22. <version>2.3.4.RELEASE</version>
  23. </dependency>
  1. package com.mugua.oauth.config;
  2. import com.mugua.oauth.service.CustomUserDetailsService;
  3. import com.mugua.oauth.service.impl.CustomTokenServices;
  4. import com.mugua.oauth.translator.CustomWebResponseExceptionTranslator;
  5. import com.mugua.oauth.wrapper.CustomUserDetailsByNameServiceWrapper;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.cloud.context.config.annotation.RefreshScope;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import org.springframework.http.HttpMethod;
  12. import org.springframework.security.authentication.AuthenticationManager;
  13. import org.springframework.security.authentication.ProviderManager;
  14. import org.springframework.security.jwt.crypto.sign.MacSigner;
  15. import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
  16. import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
  17. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
  18. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
  19. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
  20. import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
  21. import org.springframework.security.oauth2.provider.token.TokenStore;
  22. import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
  23. import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
  24. import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;
  25. import javax.sql.DataSource;
  26. import java.util.Arrays;
  27. @Configuration
  28. @EnableAuthorizationServer
  29. @RefreshScope
  30. public class OauthServerConfig extends AuthorizationServerConfigurerAdapter {
  31. @Autowired
  32. private AuthenticationManager authenticationManager;
  33. @Autowired
  34. private DataSource dataSource;
  35. @Autowired
  36. private CustomUserDetailsService usersService;
  37. @Autowired
  38. private CustomWebResponseExceptionTranslator customWebResponseExceptionTranslator;
  39. /**
  40. * jwt签名密钥
  41. */
  42. @Value("${spring.sign.key}")
  43. private String signKey;
  44. /**
  45. * 设置令牌过期时间,一般大厂会设置为2个小时 单位为秒
  46. */
  47. @Value("${token.time.tokenValidity}")
  48. private String tokenValidity;
  49. /**
  50. * 设置刷新令牌的有效时间 3天
  51. */
  52. @Value("${token.time.refreshTokenValidity}")
  53. private String refreshTokenValidity;
  54. /**
  55. * 认证服务器最终是以api对外提供服务(校验合法性,并且生成令牌,校验令牌等)
  56. * 那么,以api接口方式对外的话,就必然涉及到接口的访问权限,需要在这这里进行配置
  57. */
  58. @Override
  59. public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
  60. super.configure(security);
  61. //相当于打开endpoint访问的接口开关,这样的话后期就能访问该接口
  62. security
  63. //允许客户端表单认证
  64. //主要是让/oauth/token支持client_id和client_secret做登陆认证如果开启了allowFormAuthenticationForClients,那么就在BasicAuthenticationFilter之前
  65. //添加ClientCredentialsTokenEndpointFilter,使用ClientDetailsUserDetailsService来进行登陆认证
  66. //这个如果配置支持allowFormAuthenticationForClients的,且url中有client_id和client_secret的会走ClientCredentialsTokenEndpointFilter来保护
  67. //如果没有支持allowFormAuthenticationForClients或者有支持但是url中没有client_id和client_secret的,走basic认证保护
  68. .allowFormAuthenticationForClients()
  69. //开启端口/oauth/token_key的访问权限(允许) 可以理解为生成令牌
  70. .tokenKeyAccess("permitAll()")
  71. //开启端口/oauth/check_token的访问权限(允许) 可以理解为校验令牌
  72. .checkTokenAccess("permitAll()");
  73. }
  74. /**
  75. * 客户端详情,比如client_id,secret
  76. * 比如这个服务就如果QQ平台,腾讯邮箱作为客户端,需要QQ平台进行认证授权登录认证等,
  77. * 提前需要到QQ平台注册,QQ平台会给QQ邮箱
  78. * 颁发client_id等必要参数,表明客户端是谁
  79. */
  80. @Override
  81. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  82. super.configure(clients);
  83. // 从内存中加载客户端详情改为从数据库中加载客户端详情
  84. clients.withClientDetails(createJdbcClientDetailsService());
  85. }
  86. @Bean
  87. public JdbcClientDetailsService createJdbcClientDetailsService() {
  88. return new JdbcClientDetailsService(dataSource);
  89. }
  90. /**
  91. * 认证服务器是玩转token,那么这里配置token令牌管理相关(token此时就是一个字符串当下的token需要在服务器端存储)
  92. */
  93. @Override
  94. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  95. super.configure(endpoints);
  96. endpoints
  97. //指定token存储方法
  98. .tokenStore(tokenStore())
  99. //token服务的一个描述,可以认为是token生成的细节的描述,比如有效时间等
  100. .tokenServices(customTokenServices())
  101. .reuseRefreshTokens(true)
  102. //指定认证管理器,随后注入一个到当前类
  103. .authenticationManager(authenticationManager)
  104. .userDetailsService(usersService)
  105. //异常翻译处理
  106. .exceptionTranslator(customWebResponseExceptionTranslator)
  107. //请求类型
  108. .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
  109. }
  110. /**
  111. * 该方法用于创建tokenStore对象(令牌存储对象)token以什么形式存储
  112. */
  113. public TokenStore tokenStore() {
  114. //使用jwt令牌
  115. return new JwtTokenStore(jwtAccessTokenConverter());
  116. }
  117. /**
  118. * 返回jwt令牌转换器(帮助我们⽣成jwt令牌的)在这⾥,我们可以把签名密钥传递进去给转换器对象
  119. */
  120. public JwtAccessTokenConverter jwtAccessTokenConverter() {
  121. //签名密钥
  122. JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
  123. jwtAccessTokenConverter.setSigningKey(signKey);
  124. //验证时使⽤的密钥,和签名密钥保持⼀致
  125. jwtAccessTokenConverter.setVerifier(new MacSigner(signKey));
  126. return jwtAccessTokenConverter;
  127. }
  128. public CustomTokenServices customTokenServices() {
  129. CustomTokenServices tokenServices = new CustomTokenServices();
  130. //令牌存在哪里
  131. tokenServices.setTokenStore(tokenStore());
  132. //开启令牌刷新
  133. tokenServices.setSupportRefreshToken(true);
  134. tokenServices.setReuseRefreshToken(true);
  135. tokenServices.setClientDetailsService(createJdbcClientDetailsService());
  136. //针对jwt令牌的添加
  137. tokenServices.setTokenEnhancer(jwtAccessTokenConverter());
  138. // 设置自定义的CustomUserDetailsByNameServiceWrapper
  139. if (usersService != null) {
  140. PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
  141. provider.setPreAuthenticatedUserDetailsService(new CustomUserDetailsByNameServiceWrapper(usersService));
  142. tokenServices.setAuthenticationManager(new ProviderManager(Arrays.asList(provider)));
  143. }
  144. //设置令牌过期时间,一般大厂会设置为2个小时 单位为秒
  145. tokenServices.setAccessTokenValiditySeconds(Integer.parseInt(tokenValidity));
  146. //设置刷新令牌的有效时间 //3天
  147. tokenServices.setRefreshTokenValiditySeconds(Integer.parseInt(refreshTokenValidity));
  148. return tokenServices;
  149. }
  150. }
  1. package com.mugua.oauth.service;
  2. import org.springframework.security.core.userdetails.UserDetails;
  3. import org.springframework.security.core.userdetails.UserDetailsService;
  4. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  5. /**
  6. * 继承原来的UserDetailsService新增自定义方法
  7. *
  8. * @author liwenchao
  9. */
  10. public interface CustomUserDetailsService extends UserDetailsService {
  11. UserDetails loadUserByUsername(String username, String userType) throws UsernameNotFoundException;
  12. @Override
  13. default UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  14. return null;
  15. }
  16. }
  1. package com.mugua.oauth.translator;
  2. import com.mugua.oauth.entity.DmpResult;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.apache.commons.lang3.StringUtils;
  5. import org.springframework.http.HttpStatus;
  6. import org.springframework.http.ResponseEntity;
  7. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  8. import org.springframework.security.oauth2.common.exceptions.*;
  9. import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
  10. import org.springframework.stereotype.Component;
  11. /**
  12. * 异常翻译
  13. * 就返回了500 没有返回具体的参数code码
  14. *
  15. * @author lwc
  16. */
  17. @Slf4j
  18. @Component
  19. @SuppressWarnings("all")
  20. public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator {
  21. @Override
  22. public ResponseEntity<?> translate(Exception e) {
  23. ResponseEntity.BodyBuilder status = ResponseEntity.status(HttpStatus.BAD_REQUEST);
  24. String code = null;
  25. String message = "认证失败";
  26. log.error(message, e);
  27. if (e instanceof UnsupportedGrantTypeException) {
  28. code = String.valueOf(((UnsupportedGrantTypeException) e).getHttpErrorCode());
  29. message = "不支持该认证类型";
  30. return status.body(DmpResult.data(code, message));
  31. }
  32. if (e instanceof InvalidTokenException
  33. && StringUtils.containsIgnoreCase(e.getMessage(), "Invalid refresh token (expired)")) {
  34. code = String.valueOf(((InvalidTokenException) e).getHttpErrorCode());
  35. message = "刷新令牌已过期,请重新登录";
  36. status = ResponseEntity.status(HttpStatus.UNAUTHORIZED);
  37. return status.body(DmpResult.data(code, message));
  38. }
  39. if (e instanceof InvalidScopeException) {
  40. code = String.valueOf(((InvalidScopeException) e).getHttpErrorCode());
  41. message = "不是有效的scope值";
  42. return status.body(DmpResult.data(code, message));
  43. }
  44. if (e instanceof RedirectMismatchException) {
  45. code = String.valueOf(((RedirectMismatchException) e).getHttpErrorCode());
  46. message = "redirect_uri值不正确";
  47. return status.body(DmpResult.data(code, message));
  48. }
  49. if (e instanceof BadClientCredentialsException) {
  50. code = String.valueOf(((BadClientCredentialsException) e).getHttpErrorCode());
  51. message = "client值不合法";
  52. status = ResponseEntity.status(HttpStatus.UNAUTHORIZED);
  53. return status.body(DmpResult.data(code, message));
  54. }
  55. if (e instanceof UnsupportedResponseTypeException) {
  56. code = String.valueOf(((UnsupportedResponseTypeException) e).getHttpErrorCode());
  57. String codeMessage = StringUtils.substringBetween(e.getMessage(), "[", "]");
  58. message = codeMessage + "不是合法的response_type值";
  59. return status.body(DmpResult.data(code, message));
  60. }
  61. if (e instanceof InvalidGrantException) {
  62. code = String.valueOf(((InvalidGrantException) e).getHttpErrorCode());
  63. if (StringUtils.containsIgnoreCase(e.getMessage(), "Invalid refresh token")) {
  64. message = "refresh token无效";
  65. return status.body(DmpResult.data(code, message));
  66. }
  67. if (StringUtils.containsIgnoreCase(e.getMessage(), "Invalid authorization code")) {
  68. code = String.valueOf(((InvalidGrantException) e).getHttpErrorCode());
  69. String codeMessage = StringUtils.substringAfterLast(e.getMessage(), ": ");
  70. message = "授权码" + codeMessage + "不合法";
  71. return status.body(DmpResult.data(code, message));
  72. }
  73. if (StringUtils.containsIgnoreCase(e.getMessage(), "locked")) {
  74. message = "用户已被锁定,请联系管理员";
  75. return status.body(DmpResult.data(code, message));
  76. }
  77. message = "用户名或密码错误";
  78. return status.body(DmpResult.data(code, message));
  79. }
  80. if (e instanceof UsernameNotFoundException) {
  81. message = e.getMessage();
  82. code = String.valueOf(HttpStatus.UNAUTHORIZED.value());
  83. return status.body(DmpResult.data(code, message));
  84. }
  85. //没翻译到的用默认
  86. if (e instanceof Exception) {
  87. code = String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value());
  88. return status.body(DmpResult.data(code, message));
  89. }
  90. code = String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value());
  91. return status.body(DmpResult.data(code, message));
  92. }
  93. }
  1. /*
  2. * Copyright 2002-2016 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.mugua.oauth.wrapper;
  17. import com.mugua.oauth.service.CustomUserDetailsService;
  18. import org.springframework.beans.factory.InitializingBean;
  19. import org.springframework.security.authentication.AbstractAuthenticationToken;
  20. import org.springframework.security.core.Authentication;
  21. import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
  22. import org.springframework.security.core.userdetails.UserDetails;
  23. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  24. import org.springframework.util.Assert;
  25. import java.util.Map;
  26. /**
  27. * This implementation for AuthenticationUserDetailsService wraps a regular Spring
  28. * Security UserDetailsService implementation, to retrieve a UserDetails object based on
  29. * the user name contained in an <tt>Authentication</tt> object.
  30. *
  31. * @author Ruud Senden
  32. * @author Scott Battaglia
  33. * @since 2.0
  34. */
  35. public class CustomUserDetailsByNameServiceWrapper<T extends Authentication> implements AuthenticationUserDetailsService<T>, InitializingBean {
  36. private CustomUserDetailsService userDetailsService = null;
  37. /**
  38. * Constructs an empty wrapper for compatibility with Spring Security 2.0.x's method
  39. * of using a setter.
  40. */
  41. public CustomUserDetailsByNameServiceWrapper() {
  42. // constructor for backwards compatibility with 2.0
  43. }
  44. /**
  45. * Constructs a new wrapper using the supplied
  46. * {@link org.springframework.security.core.userdetails.UserDetailsService} as the
  47. * service to delegate to.
  48. *
  49. * @param userDetailsService the UserDetailsService to delegate to.
  50. */
  51. public CustomUserDetailsByNameServiceWrapper(final CustomUserDetailsService userDetailsService) {
  52. Assert.notNull(userDetailsService, "userDetailsService cannot be null.");
  53. this.userDetailsService = userDetailsService;
  54. }
  55. /**
  56. * Check whether all required properties have been set.
  57. *
  58. * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
  59. */
  60. @Override
  61. public void afterPropertiesSet() {
  62. Assert.notNull(this.userDetailsService, "UserDetailsService must be set");
  63. }
  64. /**
  65. * Get the UserDetails object from the wrapped UserDetailsService implementation
  66. */
  67. @Override
  68. public UserDetails loadUserDetails(T authentication) throws UsernameNotFoundException {
  69. // ----------添加自定义的内容----------
  70. AbstractAuthenticationToken principal = (AbstractAuthenticationToken) authentication.getPrincipal();
  71. Map<String, String> map = (Map<String, String>) principal.getDetails();
  72. String userType = map.get("userType");
  73. // ----------添加自定义的内容----------
  74. return this.userDetailsService.loadUserByUsername(authentication.getName(), userType); // 使用自定义的userDetailsService
  75. }
  76. /**
  77. * Set the wrapped UserDetailsService implementation
  78. *
  79. * @param aUserDetailsService The wrapped UserDetailsService to set
  80. */
  81. public void setUserDetailsService(CustomUserDetailsService aUserDetailsService) {
  82. this.userDetailsService = aUserDetailsService;
  83. }
  84. }
  1. package com.mugua.oauth.encoder;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.mugua.oauth.utils.DecodeUtils;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.springframework.security.crypto.password.PasswordEncoder;
  7. import java.nio.charset.StandardCharsets;
  8. import java.util.Base64;
  9. /**
  10. * @author liwenchao
  11. */
  12. @Slf4j
  13. public class CustomPasswordEncoder implements PasswordEncoder {
  14. /**
  15. * 加密(外面调用一般在注册的时候加密前端传过来的密码保存进数据库)
  16. * 注册不在这里进行所以这里暂时不进行操作保持明文
  17. * rawPassword == userNotFoundPassword 防止计时攻击
  18. *
  19. * @param rawPassword 前端传过来的密码
  20. */
  21. @Override
  22. public String encode(CharSequence rawPassword) {
  23. return rawPassword.toString();
  24. }
  25. /**
  26. * 加密前后对比(一般用来比对前端提交过来的密码和数据库存储密码, 也就是明文和密文的对比)
  27. *
  28. * @param rawPassword 前端传过来的密码
  29. * @param encodedPassword 数据库取出的密码
  30. */
  31. @Override
  32. public boolean matches(CharSequence rawPassword, String encodedPassword) {
  33. if (rawPassword == null) {
  34. throw new IllegalArgumentException("rawPassword cannot be null");
  35. }
  36. if (encodedPassword == null || encodedPassword.length() == 0) {
  37. log.info("Empty encoded password");
  38. return false;
  39. }
  40. //判断是否base64
  41. boolean b = DecodeUtils.checkBase64(rawPassword.toString());
  42. if (!b) {
  43. return rawPassword.toString().equalsIgnoreCase(encodedPassword);
  44. }
  45. String passwordJson = null;
  46. try {
  47. passwordJson = new String(Base64.getDecoder().decode(rawPassword.toString()), StandardCharsets.UTF_8);
  48. } catch (Exception e) {
  49. log.error("rawPassword {} decoder fail", passwordJson);
  50. }
  51. JSONObject jsonObject = JSON.parseObject(passwordJson);
  52. String type = jsonObject.getString("p1");
  53. String password = jsonObject.getString("p2");
  54. if("webDefault".equalsIgnoreCase(type)){
  55. return true;
  56. }
  57. JSONObject json = JSON.parseObject(encodedPassword);
  58. String returnPwd = json.getString("p2");
  59. String salt = json.getString("p3");
  60. return !"default".equalsIgnoreCase(type) || DecodeUtils.matchesForUser(password, returnPwd, salt);
  61. }
  62. }
  1. /*
  2. * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.mugua.oauth.provider;
  17. import com.mugua.oauth.service.CustomUserDetailsService;
  18. import org.springframework.security.authentication.AuthenticationProvider;
  19. import org.springframework.security.authentication.BadCredentialsException;
  20. import org.springframework.security.authentication.InternalAuthenticationServiceException;
  21. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  22. import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
  23. import org.springframework.security.core.Authentication;
  24. import org.springframework.security.core.AuthenticationException;
  25. import org.springframework.security.core.userdetails.UserDetails;
  26. import org.springframework.security.core.userdetails.UserDetailsPasswordService;
  27. import org.springframework.security.core.userdetails.UserDetailsService;
  28. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  29. import org.springframework.security.crypto.factory.PasswordEncoderFactories;
  30. import org.springframework.security.crypto.password.PasswordEncoder;
  31. import org.springframework.util.Assert;
  32. import java.util.Map;
  33. /**
  34. * An {@link AuthenticationProvider} implementation that retrieves user details from a
  35. * {@link UserDetailsService}.
  36. *
  37. * @author Ben Alex
  38. * @author Rob Winch
  39. */
  40. public class CustomAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
  41. // ~ Static fields/initializers
  42. // =====================================================================================
  43. /**
  44. * The plaintext password used to perform
  45. * PasswordEncoder#matches(CharSequence, String)} on when the user is
  46. * not found to avoid SEC-2056.
  47. */
  48. private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
  49. // ~ Instance fields
  50. // ================================================================================================
  51. private PasswordEncoder passwordEncoder;
  52. /**
  53. * The password used to perform
  54. * {@link PasswordEncoder#matches(CharSequence, String)} on when the user is
  55. * not found to avoid SEC-2056. This is necessary, because some
  56. * {@link PasswordEncoder} implementations will short circuit if the password is not
  57. * in a valid format.
  58. */
  59. private volatile String userNotFoundEncodedPassword;
  60. private CustomUserDetailsService userDetailsService;
  61. private UserDetailsPasswordService userDetailsPasswordService;
  62. public CustomAuthenticationProvider() {
  63. setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
  64. }
  65. // ~ Methods
  66. // ========================================================================================================
  67. @Override
  68. @SuppressWarnings("deprecation")
  69. protected void additionalAuthenticationChecks(UserDetails userDetails,
  70. UsernamePasswordAuthenticationToken authentication)
  71. throws AuthenticationException {
  72. if (authentication.getCredentials() == null) {
  73. logger.debug("Authentication failed: no credentials provided");
  74. throw new BadCredentialsException(messages.getMessage(
  75. "AbstractUserDetailsAuthenticationProvider.badCredentials",
  76. "Bad credentials"));
  77. }
  78. String presentedPassword = authentication.getCredentials().toString();
  79. if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
  80. logger.debug("Authentication failed: password does not match stored value");
  81. throw new BadCredentialsException(messages.getMessage(
  82. "AbstractUserDetailsAuthenticationProvider.badCredentials",
  83. "Bad credentials"));
  84. }
  85. }
  86. @Override
  87. protected void doAfterPropertiesSet() {
  88. Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");
  89. }
  90. @Override
  91. protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
  92. this.prepareTimingAttackProtection();
  93. // 自定义添加
  94. Map<String, String> map = (Map<String, String>) authentication.getDetails();
  95. try {
  96. // 自定义添加
  97. String userType = map.get("userType");
  98. // 自定义添加userType参数
  99. UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username, userType);
  100. if (loadedUser == null) {
  101. throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
  102. } else {
  103. return loadedUser;
  104. }
  105. } catch (UsernameNotFoundException ex) {
  106. mitigateAgainstTimingAttack(authentication);
  107. throw ex;
  108. } catch (InternalAuthenticationServiceException ex) {
  109. throw ex;
  110. } catch (Exception ex) {
  111. throw new InternalAuthenticationServiceException(ex.getMessage(), ex);
  112. }
  113. }
  114. @Override
  115. protected Authentication createSuccessAuthentication(Object principal,
  116. Authentication authentication, UserDetails user) {
  117. boolean upgradeEncoding = this.userDetailsPasswordService != null
  118. && this.passwordEncoder.upgradeEncoding(user.getPassword());
  119. if (upgradeEncoding) {
  120. String presentedPassword = authentication.getCredentials().toString();
  121. String newPassword = this.passwordEncoder.encode(presentedPassword);
  122. user = this.userDetailsPasswordService.updatePassword(user, newPassword);
  123. }
  124. return super.createSuccessAuthentication(principal, authentication, user);
  125. }
  126. private void prepareTimingAttackProtection() {
  127. if (this.userNotFoundEncodedPassword == null) {
  128. this.userNotFoundEncodedPassword = this.passwordEncoder.encode(USER_NOT_FOUND_PASSWORD);
  129. }
  130. }
  131. private void mitigateAgainstTimingAttack(UsernamePasswordAuthenticationToken authentication) {
  132. if (authentication.getCredentials() != null) {
  133. String presentedPassword = authentication.getCredentials().toString();
  134. this.passwordEncoder.matches(presentedPassword, this.userNotFoundEncodedPassword);
  135. }
  136. }
  137. /**
  138. * Sets the PasswordEncoder instance to be used to encode and validate passwords. If
  139. * not set, the password will be compared using {@link PasswordEncoderFactories#createDelegatingPasswordEncoder()}
  140. *
  141. * @param passwordEncoder must be an instance of one of the {@code PasswordEncoder}
  142. * types.
  143. */
  144. public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
  145. Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
  146. this.passwordEncoder = passwordEncoder;
  147. this.userNotFoundEncodedPassword = null;
  148. }
  149. protected PasswordEncoder getPasswordEncoder() {
  150. return passwordEncoder;
  151. }
  152. public void setUserDetailsService(CustomUserDetailsService userDetailsService) {
  153. this.userDetailsService = userDetailsService;
  154. }
  155. protected CustomUserDetailsService getUserDetailsService() {
  156. return userDetailsService;
  157. }
  158. public void setUserDetailsPasswordService(
  159. UserDetailsPasswordService userDetailsPasswordService) {
  160. this.userDetailsPasswordService = userDetailsPasswordService;
  161. }
  162. }
  1. package com.mugua.oauth.utils;
  2. import com.alibaba.nacos.common.utils.Md5Utils;
  3. import org.apache.shiro.crypto.hash.SimpleHash;
  4. import java.nio.charset.StandardCharsets;
  5. import java.util.Base64;
  6. /**
  7. * @author liwenchao
  8. */
  9. public class DecodeUtils {
  10. /**
  11. * 解密原业务线账户密码是否正确的方法
  12. */
  13. public static boolean matchesForUser(String paramPwd, String userPwd, String salt) {
  14. //拿到用户密码(明文)进行三次md5
  15. for (int i = 0; i < 3; i++) {
  16. paramPwd = Md5Utils.getMD5(paramPwd.getBytes(StandardCharsets.UTF_8));
  17. }
  18. SimpleHash md5 = new SimpleHash("MD5", paramPwd, salt, 5);
  19. return md5.toString().equalsIgnoreCase(userPwd);
  20. }
  21. /**
  22. * 解密openid方式密码
  23. * @param paramPwd
  24. * @param userPwd
  25. * @return
  26. */
  27. public static boolean matchesForEquals(String paramPwd,String userPwd){
  28. return paramPwd.trim().equalsIgnoreCase(userPwd);
  29. }
  30. /**
  31. * 判断字符串是否为base64编码
  32. * Ascii码说明:共95个可读字符
  33. * 0~31及127(共33个)是控制字符或通信专用字符(其余为可显示字符)
  34. * 32~126(共95个)是字符(32是空格),其中48~57为0到9十个阿拉伯数字。
  35. * 65~90为26个大写英文字母,97~122号为26个小写英文字母,其余为一些标点符号、运算符号等。
  36. */
  37. public static boolean checkBase64(String str) {
  38. //使用正则来判断是否符合base64编码的特征(但是无法排除类似于root这种特殊情况)
  39. String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
  40. boolean isLegal = str.matches(base64Pattern);
  41. if (isLegal) {
  42. //对于某些字符可能符合base64编码特征,但是却不是base64编码格式,进行进一步判断,如果解码后含有乱码(即Ascii码不在32~126),
  43. //说明虽然符合base64编码特征,但是不是base64编码,如:root
  44. try {
  45. String decStr = new String(Base64.getDecoder().decode(str.getBytes()), StandardCharsets.UTF_8);
  46. char[] passArr = decStr.toCharArray();
  47. for (char c : passArr) {
  48. if (charToByteAscii2(c) < 32 || charToByteAscii2(c) > 126) {
  49. return false;
  50. }
  51. }
  52. } catch (Exception e) {
  53. return false;
  54. }
  55. } else {
  56. return false;
  57. }
  58. return true;
  59. }
  60. private static byte charToByteAscii2(char ch) {
  61. return (byte) ch;
  62. }
  63. }
  1. package com.mugua.oauth.entity;
  2. import com.fasterxml.jackson.annotation.JsonIgnore;
  3. import java.io.Serializable;
  4. /**
  5. * 普通返回
  6. *
  7. * @author lwc
  8. */
  9. public class DmpResult<T> implements Serializable {
  10. private static final long serialVersionUID = 771836922595187944L;
  11. //返回数据
  12. protected T data;
  13. //返回错误码
  14. protected String code;
  15. //返回消息
  16. protected String msg;
  17. public DmpResult() {
  18. }
  19. public DmpResult(T t, String code, String msg) {
  20. this.data = t;
  21. this.code = code;
  22. this.msg = msg;
  23. }
  24. /**
  25. * 成功返回的默认方法
  26. */
  27. public static DmpResult success() {
  28. return new DmpResult(null, StatusCodeEnum.SUC.getCode(), "result_success");
  29. }
  30. public static DmpResult success(String msg) {
  31. return new DmpResult(null, StatusCodeEnum.SUC.getCode(), msg);
  32. }
  33. /**
  34. * 数据返回的默认方法
  35. */
  36. public static <T> DmpResult data(T t) {
  37. return new DmpResult(t, StatusCodeEnum.SUC.getCode(), "result_success");
  38. }
  39. public static <T> DmpResult data(T t, String msg) {
  40. return new DmpResult(t, StatusCodeEnum.SUC.getCode(), msg);
  41. }
  42. public static DmpResult data(String retCode, String msg) {
  43. return new DmpResult(null, retCode, msg);
  44. }
  45. /**
  46. * 错误的默认方法
  47. */
  48. public static DmpResult failed() {
  49. return new DmpResult(null, StatusCodeEnum.ERROR.getCode(), "result_fail");
  50. }
  51. public static DmpResult failed(String msg) {
  52. return new DmpResult(null, StatusCodeEnum.ERROR.getCode(), msg);
  53. }
  54. public static DmpResult failed(StatusCodeEnum statusCodeEnum) {
  55. return new DmpResult(null, statusCodeEnum.getCode(), "result_fail");
  56. }
  57. public static DmpResult failed(StatusCodeEnum statusCodeEnum, String msg) {
  58. return new DmpResult(null, statusCodeEnum.getCode(), msg);
  59. }
  60. public static DmpResult status(boolean status) {
  61. return status ? success() : failed();
  62. }
  63. @JsonIgnore
  64. public Boolean isSuccess() {
  65. return StatusCodeEnum.SUC.getCode().equals(this.code);
  66. }
  67. @JsonIgnore
  68. public Boolean isRetData() {
  69. return isSuccess() && this.getData() != null;
  70. }
  71. public T getData() {
  72. return data;
  73. }
  74. public void setData(T data) {
  75. this.data = data;
  76. }
  77. public String getCode() {
  78. return code;
  79. }
  80. public void setCode(String code) {
  81. this.code = code;
  82. }
  83. public String getMsg() {
  84. return msg;
  85. }
  86. public void setMsg(String msg) {
  87. this.msg = msg;
  88. }
  89. }
  1. package com.mugua.oauth.entity;
  2. /**
  3. * 新增枚举字段需要按照范围来申请
  4. * <p>
  5. *
  6. * @author liwenchao
  7. */
  8. public enum StatusCodeEnum {
  9. // 成功
  10. SUC("200", "result_success"),
  11. // 失败
  12. ERROR("500", "result_fail"),
  13. ;
  14. //值
  15. private String code;
  16. //描述
  17. private String desc;
  18. StatusCodeEnum(String code, String desc) {
  19. this.code = code;
  20. this.desc = desc;
  21. }
  22. public String getCode() {
  23. return code;
  24. }
  25. public String getDesc() {
  26. return desc;
  27. }
  28. }
  1. package com.mugua.oauth.config;
  2. import com.mugua.oauth.encoder.CustomPasswordEncoder;
  3. import com.mugua.oauth.provider.CustomAuthenticationProvider;
  4. import com.mugua.oauth.service.impl.UsersServiceImpl;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.security.authentication.AuthenticationManager;
  9. import org.springframework.security.authentication.AuthenticationProvider;
  10. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  11. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  12. import org.springframework.security.crypto.password.PasswordEncoder;
  13. @Configuration
  14. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  15. @Autowired
  16. private UsersServiceImpl usersService;
  17. /**
  18. * 注册一个认证管理器对象给容器
  19. */
  20. @Bean
  21. @Override
  22. public AuthenticationManager authenticationManagerBean() throws Exception {
  23. return super.authenticationManagerBean();
  24. }
  25. /**
  26. * 密码编码对象(暂不对密码进行加密处理),如果有加密就直接往容器里面扔,就不用这个了
  27. */
  28. @Bean
  29. public PasswordEncoder passwordEncoder() {
  30. return new CustomPasswordEncoder();
  31. }
  32. /**
  33. * 处理用户名和密码的验证事宜
  34. * 1.客户端传递username和password 参数到认证服务器
  35. * 2.username 和password 会存在数据库中
  36. * 3.根据用户表中的数据,验证当前传递过来的用户信息的合法性
  37. */
  38. @Override
  39. protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
  40. //实例化一个用户对象(相当于数据表中的一条用户记录)
  41. authenticationManagerBuilder.authenticationProvider(customAuthenticationProvider());
  42. }
  43. /**
  44. * 用户信息提供者
  45. */
  46. @Bean(name = "customAuthenticationProvider")
  47. public AuthenticationProvider customAuthenticationProvider() {
  48. CustomAuthenticationProvider customAuthenticationProvider = new CustomAuthenticationProvider();
  49. //实例化一个用户对象(相当于数据表中的一条用户记录)
  50. customAuthenticationProvider.setUserDetailsService(usersService);
  51. customAuthenticationProvider.setHideUserNotFoundExceptions(false);
  52. customAuthenticationProvider.setPasswordEncoder(passwordEncoder());
  53. return customAuthenticationProvider;
  54. }
  55. }
  1. package com.mugua.oauth.config;
  2. import org.springframework.beans.factory.ObjectProvider;
  3. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  4. import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.http.converter.HttpMessageConverter;
  8. import java.util.stream.Collectors;
  9. /**
  10. * @author liwenchao
  11. */
  12. @Configuration
  13. public class MessageConverterConfig {
  14. @Bean
  15. @ConditionalOnMissingBean
  16. public HttpMessageConverters messageConverters(ObjectProvider<HttpMessageConverter<?>> converters) {
  17. return new HttpMessageConverters(converters.orderedStream().collect(Collectors.toList()));
  18. }
  19. }
  1. /*
  2. Navicat Premium Data Transfer
  3. Source Server : nj-cdb-aaxjptkx.sql.tencentcdb.com
  4. Source Server Type : MySQL
  5. Source Server Version : 50736
  6. Source Host : nj-cdb-aaxjptkx.sql.tencentcdb.com:63901
  7. Source Schema : oauth
  8. Target Server Type : MySQL
  9. Target Server Version : 50736
  10. File Encoding : 65001
  11. Date: 07/02/2023 22:26:59
  12. */
  13. SET NAMES utf8mb4;
  14. SET FOREIGN_KEY_CHECKS = 0;
  15. -- ----------------------------
  16. -- Table structure for oauth_client_details
  17. -- ----------------------------
  18. DROP TABLE IF EXISTS `oauth_client_details`;
  19. CREATE TABLE `oauth_client_details` (
  20. `client_id` varchar(48) NOT NULL COMMENT '主键,必须唯一,不能为空.\n用于唯一标识每一个客户端(client); 在注册时必须填写(也可由服务端自动生成).\n对于不同的grant_type,该字段都是必须的. 在实际应用中的另一个名称叫appKey,与client_id是同一个概念.',
  21. `resource_ids` varchar(256) DEFAULT NULL COMMENT '客户端所能访问的资源id集合,多个资源时用逗号(,)分隔,如: "unity-resource,mobile-resource".\n该字段的值必须来源于与security.xml中标签‹oauth2:resource-server的属性resource-id值一致. 在security.xml配置有几个‹oauth2:resource-server标签, 则该字段可以使用几个该值.\n在实际应用中, 我们一般将资源进行分类,并分别配置对应的‹oauth2:resource-server,如订单资源配置一个‹oauth2:resource-server, 用户资源又配置一个‹oauth2:resource-server. 当注册客户端时,根据实际需要可选择资源id,也可根据不同的注册流程,赋予对应的资源id.',
  22. `client_secret` varchar(256) DEFAULT NULL COMMENT '用于指定客户端(client)的访问密匙; 在注册时必须填写(也可由服务端自动生成).\n对于不同的grant_type,该字段都是必须的. 在实际应用中的另一个名称叫appSecret,与client_secret是同一个概念.',
  23. `scope` varchar(256) DEFAULT NULL COMMENT '指定客户端申请的权限范围,可选值包括read,write,trust;若有多个权限范围用逗号(,)分隔,如: "read,write".\nscope的值与security.xml中配置的‹intercept-url的access属性有关系. 如‹intercept-url的配置为\n‹intercept-url pattern="/m/**" access="ROLE_MOBILE,SCOPE_READ"/>\n则说明访问该URL时的客户端必须有read权限范围. write的配置值为SCOPE_WRITE, trust的配置值为SCOPE_TRUST.\n在实际应该中, 该值一般由服务端指定, 常用的值为read,write.',
  24. `authorized_grant_types` varchar(256) DEFAULT NULL COMMENT '指定客户端支持的grant_type,可选值包括authorization_code,password,refresh_token,implicit,client_credentials, 若支持多个grant_type用逗号(,)分隔,如: "authorization_code,password".\n在实际应用中,当注册时,该字段是一般由服务器端指定的,而不是由申请者去选择的,最常用的grant_type组合有: "authorization_code,refresh_token"(针对通过浏览器访问的客户端); "password,refresh_token"(针对移动设备的客户端).\nimplicit与client_credentials在实际中很少使用.',
  25. `web_server_redirect_uri` varchar(256) DEFAULT NULL COMMENT '客户端的重定向URI,可为空, 当grant_type为authorization_code或implicit时, 在Oauth的流程中会使用并检查与注册时填写的redirect_uri是否一致. 下面分别说明:\n当grant_type=authorization_code时, 第一步 从 spring-oauth-server获取 ''code''时客户端发起请求时必须有redirect_uri参数, 该参数的值必须与 web_server_redirect_uri的值一致. 第二步 用 ''code'' 换取 ''access_token'' 时客户也必须传递相同的redirect_uri.\n在实际应用中, web_server_redirect_uri在注册时是必须填写的, 一般用来处理服务器返回的code, 验证state是否合法与通过code去换取access_token值.\n在spring-oauth-client项目中, 可具体参考AuthorizationCodeController.java中的authorizationCodeCallback方法.\n当grant_type=implicit时通过redirect_uri的hash值来传递access_token值.如:\nhttp://localhost:7777/spring-oauth-client/implicit#access_token=dc891f4a-ac88-4ba6-8224-a2497e013865&token_type=bearer&expires_in=43199\n然后客户端通过JS等从hash值中取到access_token值.',
  26. `authorities` varchar(256) DEFAULT NULL COMMENT '指定客户端所拥有的Spring Security的权限值,可选, 若有多个权限值,用逗号(,)分隔, 如: "ROLE_UNITY,ROLE_USER".\n对于是否要设置该字段的值,要根据不同的grant_type来判断, 若客户端在Oauth流程中需要用户的用户名(username)与密码(password)的(authorization_code,password),\n则该字段可以不需要设置值,因为服务端将根据用户在服务端所拥有的权限来判断是否有权限访问对应的API.\n但如果客户端在Oauth流程中不需要用户信息的(implicit,client_credentials),\n则该字段必须要设置对应的权限值, 因为服务端将根据该字段值的权限来判断是否有权限访问对应的API.\n(请在spring-oauth-client项目中来测试不同grant_type时authorities的变化)',
  27. `access_token_validity` int(11) DEFAULT NULL COMMENT '设定客户端的access_token的有效时间值(单位:秒),可选, 若不设定值则使用默认的有效时间值(60 * 60 * 12, 12小时).\n在服务端获取的access_token JSON数据中的expires_in字段的值即为当前access_token的有效时间值.\n在项目中, 可具体参考DefaultTokenServices.java中属性accessTokenValiditySeconds.\n在实际应用中, 该值一般是由服务端处理的, 不需要客户端自定义.',
  28. `refresh_token_validity` int(11) DEFAULT NULL COMMENT '设定客户端的refresh_token的有效时间值(单位:秒),可选, 若不设定值则使用默认的有效时间值(60 * 60 * 24 * 30, 30天).\n若客户端的grant_type不包括refresh_token,则不用关心该字段 在项目中, 可具体参考DefaultTokenServices.java中属性refreshTokenValiditySeconds.\n\n在实际应用中, 该值一般是由服务端处理的, 不需要客户端自定义.',
  29. `additional_information` varchar(4096) DEFAULT NULL COMMENT '这是一个预留的字段,在Oauth的流程中没有实际的使用,可选,但若设置值,必须是JSON格式的数据,如:\n{"country":"CN","country_code":"086"}\n按照spring-security-oauth项目中对该字段的描述\nAdditional information for this client, not need by the vanilla OAuth protocol but might be useful, for example,for storing descriptive information.\n(详见ClientDetails.java的getAdditionalInformation()方法的注释)在实际应用中, 可以用该字段来存储关于客户端的一些其他信息,如客户端的国家,地区,注册时的IP地址等等.',
  30. `autoapprove` varchar(256) DEFAULT NULL COMMENT '设置用户是否自动Approval操作, 默认值为 ''false'', 可选值包括 ''true'',''false'', ''read'',''write''.\n该字段只适用于grant_type="authorization_code"的情况,当用户登录成功后,若该值为''true''或支持的scope值,则会跳过用户Approve的页面, 直接授权.\n该字段与 trusted 有类似的功能, 是 spring-security-oauth2 的 2.0 版本后添加的新属性.',
  31. PRIMARY KEY (`client_id`) USING BTREE
  32. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
  33. -- ----------------------------
  34. -- Records of oauth_client_details
  35. -- ----------------------------
  36. BEGIN;
  37. INSERT INTO `oauth_client_details` VALUES ('mugua123', 'release,s-supply-chain-service,server-linux-service,s-supply-chain-crm,pay-gateway-service,consumption-report-statistics,marketing-activities', 'abcxyz', 'all', 'password,refresh_token', NULL, NULL, 6048000, 6048000, NULL, NULL);
  38. COMMIT;
  39. SET FOREIGN_KEY_CHECKS = 1;

2,资源服务器

pom

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-oauth2</artifactId>
  4. <version>2.1.0.RELEASE</version>
  5. <exclusions>
  6. <exclusion>
  7. <groupId>org.springframework.security.oauth.boot</groupId>
  8. <artifactId>spring-security-oauth2-autoconfigure</artifactId>
  9. </exclusion>
  10. </exclusions>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework.security.oauth.boot</groupId>
  14. <artifactId>spring-security-oauth2-autoconfigure</artifactId>
  15. <version>2.1.11.RELEASE</version>
  16. </dependency>
  17. <!--引入security对oauth2的支持-->
  18. <dependency>
  19. <groupId>org.springframework.security.oauth</groupId>
  20. <artifactId>spring-security-oauth2</artifactId>
  21. <version>2.3.4.RELEASE</version>
  22. </dependency>
  1. package com.mugua.release.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  4. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  5. import org.springframework.security.config.http.SessionCreationPolicy;
  6. import org.springframework.security.jwt.crypto.sign.MacSigner;
  7. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
  8. import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
  9. import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
  10. import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
  11. import org.springframework.security.oauth2.provider.token.TokenStore;
  12. import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
  13. import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
  14. /**
  15. * @Description
  16. * @Author lwc
  17. * @Data 2022/8/29 22:26
  18. */
  19. @Configuration
  20. @EnableResourceServer //开启资源服务器功能
  21. @EnableWebSecurity //开启web访问安全
  22. public class ResourceServerConfiger extends ResourceServerConfigurerAdapter {
  23. // private String sign_key = "imugua20220829"; //jwt签名密钥
  24. private String sign_key = "ee7dcc6cad12f7d7ef9642e680fdbc4d"; //jwt签名密钥
  25. /**
  26. * @Description 该⽅法⽤于定义资源服务器向远程认证服务器发起请求,进⾏token校验
  27. * 等事宜
  28. * @Param resources
  29. * @Return
  30. * @Author lwc
  31. * @Date 22:29
  32. */
  33. @Override
  34. public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
  35. /*// 设置当前资源服务的资源id
  36. resources.resourceId("release");
  37. // 定义token服务对象(token校验就应该靠token服务对象)
  38. RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
  39. // 校验端点/接⼝设置
  40. remoteTokenServices.setCheckTokenEndpointUrl("http://localhost:9999/oauth/check_token");
  41. // 携带客户端id和客户端安全码
  42. remoteTokenServices.setClientId("clientmugua");
  43. remoteTokenServices.setClientSecret("zbcxyz");
  44. resources.tokenServices(remoteTokenServices);*/
  45. //使用jwt令牌
  46. resources.resourceId("release").tokenStore(tokenStore()).stateless(true);//无状态设置
  47. }
  48. /**
  49. * @Description 场景:⼀个服务中可能有很多资源(API接⼝)
  50. * * 某⼀些API接⼝,需要先认证,才能访问
  51. * * 某⼀些API接⼝,压根就不需要认证,本来就是对外开放的接⼝
  52. * * 我们就需要对不同特点的接⼝区分对待(在当前configure⽅法中
  53. * 完成),设置是否需要经过认证
  54. * @Param http
  55. * @Return
  56. * @Author lwc
  57. * @Date 22:59
  58. */
  59. @Override
  60. public void configure(HttpSecurity http) throws Exception{
  61. http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and().authorizeRequests()
  62. .antMatchers("/release/**").authenticated() //需要认证
  63. .antMatchers("/demo/**").authenticated() //需要认证
  64. .anyRequest().permitAll(); //其余不需要认证
  65. }
  66. /**
  67. * @Description 该⽅法⽤于创建tokenStore对象(令牌存储对象)
  68. * token以什么形式存储
  69. * @Param
  70. * @Return {@link TokenStore}
  71. * @Author lwc
  72. * @Date 23:14
  73. */
  74. public TokenStore tokenStore(){
  75. //return new InMemoryTokenStore();
  76. // 使⽤jwt令牌
  77. return new JwtTokenStore(jwtAccessTokenConverter());
  78. }
  79. /**
  80. * @Description * 返回jwt令牌转换器(帮助我们⽣成jwt令牌的)
  81. * * 在这⾥,我们可以把签名密钥传递进去给转换器对象
  82. * @Param
  83. * @Return {@link JwtAccessTokenConverter}
  84. * @Author lwc
  85. * @Date 23:14
  86. */
  87. public JwtAccessTokenConverter jwtAccessTokenConverter() {
  88. JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
  89. jwtAccessTokenConverter.setSigningKey(sign_key); // 签名密钥
  90. jwtAccessTokenConverter.setVerifier(new MacSigner(sign_key)); // 验证时使⽤的密钥,
  91. // 和签名密钥保持⼀致3.3.5 从数据库加载Oauth2客户端信息
  92. // 创建数据表并初始化数据(表名及字段保持固定)
  93. return jwtAccessTokenConverter;
  94. }
  95. }
  1. 获取token AND 刷新token
  2. http://地址:端口/oauth/token?
  3. client_secret=abcxyz&grant_type=password&username=muguauser&password=iuxyzds&client_id=mugua123
  4. 获取token携带的参数
  5. client_id:客户端id
  6. password:密码客户单密码
  7. grant_type:指定使⽤哪种颁发类型,password
  8. username:⽤户名
  9. password:密码

、验证

刷新token

这里是没有指定用户名和密码的,并把grant_type改为了refresh_token

验证token

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

闽ICP备14008679号