当前位置:   article > 正文

SpringSecurity的OAuth2的认证并整合JWT_org.springframework.security.oauth2.jwt.jwtencoder

org.springframework.security.oauth2.jwt.jwtencoder

maven依赖:

  1. <dependencyManagement>
  2. <dependencies>
  3. <dependency>
  4. <groupId>org.springframework.cloud</groupId>
  5. <artifactId>spring-cloud-dependencies</artifactId>
  6. <version>Hoxton.SR12</version>
  7. <type>pom</type>
  8. <scope>import</scope>
  9. </dependency>
  10. </dependencies>
  11. </dependencyManagement>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-web</artifactId>
  16. <!-- 从依赖信息里移除 Tomcat配置 -->
  17. <exclusions>
  18. <exclusion>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-tomcat</artifactId>
  21. </exclusion>
  22. </exclusions>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-undertow</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.cloud</groupId>
  30. <artifactId>spring-cloud-starter-oauth2</artifactId>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework.cloud</groupId>
  34. <artifactId>spring-cloud-starter-security</artifactId>
  35. </dependency>
  36. <!--离线包-->
  37. <!-- <dependency>-->
  38. <!-- <groupId>test</groupId>-->
  39. <!-- <artifactId>testa</artifactId>-->
  40. <!-- <version>0.0.1</version>-->
  41. <!-- <scope>system</scope>-->
  42. <!-- <systemPath>${project.basedir}/src/main/resources/lib/test.jar</systemPath>-->
  43. <!-- </dependency>-->
  44. </dependencies>

 实现UserDetailsService 接口:

  1. package application.config;
  2. import org.springframework.security.core.authority.AuthorityUtils;
  3. import org.springframework.security.core.userdetails.UserDetails;
  4. import org.springframework.security.core.userdetails.UserDetailsService;
  5. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  6. import org.springframework.security.crypto.password.PasswordEncoder;
  7. import org.springframework.stereotype.Service;
  8. import javax.annotation.Resource;
  9. /**
  10. * @author: wtl
  11. * @License: (C) Copyright 2021, wtl Corporation Limited.
  12. * @Contact: 1050100468@qq.com
  13. * @Date: 2021/7/31 13:54
  14. * @Version: 1.0
  15. * @Description:
  16. */
  17. @Service
  18. public class UserService implements UserDetailsService {
  19. @Resource
  20. private PasswordEncoder passwordEncoder;
  21. @Override
  22. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  23. return new User(username,passwordEncoder.encode("123456"),
  24. AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
  25. }
  26. }

实现UserDetails 接口:

  1. package application.config;
  2. import org.springframework.security.core.GrantedAuthority;
  3. import org.springframework.security.core.userdetails.UserDetails;
  4. import java.util.Collection;
  5. import java.util.List;
  6. /**
  7. * @author: wtl
  8. * @License: (C) Copyright 2021, wtl Corporation Limited.
  9. * @Contact: 1050100468@qq.com
  10. * @Date: 2021/7/31 13:55
  11. * @Version: 1.0
  12. * @Description:
  13. */
  14. public class User implements UserDetails {
  15. private String username;
  16. private String password;
  17. private List<GrantedAuthority> authorities;
  18. public User() {
  19. }
  20. public User(String username, String password, List<GrantedAuthority> authorities) {
  21. this.username = username;
  22. this.password = password;
  23. this.authorities = authorities;
  24. }
  25. @Override
  26. public Collection<? extends GrantedAuthority> getAuthorities() {
  27. return authorities;
  28. }
  29. @Override
  30. public String getPassword() {
  31. return password;
  32. }
  33. @Override
  34. public String getUsername() {
  35. return username;
  36. }
  37. @Override
  38. public boolean isAccountNonExpired() {
  39. return true;
  40. }
  41. @Override
  42. public boolean isAccountNonLocked() {
  43. return true;
  44. }
  45. @Override
  46. public boolean isCredentialsNonExpired() {
  47. return true;
  48. }
  49. @Override
  50. public boolean isEnabled() {
  51. return true;
  52. }
  53. }

SpringSecurity的SecurityConfig类: 

  1. package application.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.SecurityConfigurerAdapter;
  6. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  7. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  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. /**
  12. * @author: wtl
  13. * @License: (C) Copyright 2021, wtl Corporation Limited.
  14. * @Contact: 1050100468@qq.com
  15. * @Date: 2021/7/31 13:53
  16. * @Version: 1.0
  17. * @Description:
  18. */
  19. @Configuration
  20. @EnableWebSecurity
  21. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  22. @Bean
  23. public PasswordEncoder passwordEncoder(){
  24. return new BCryptPasswordEncoder();
  25. }
  26. @Bean
  27. @Override
  28. protected AuthenticationManager authenticationManager() throws Exception {
  29. return super.authenticationManager();
  30. }
  31. @Override
  32. protected void configure(HttpSecurity http) throws Exception {
  33. http
  34. .csrf().disable()
  35. .authorizeRequests()
  36. .antMatchers("/oauth/**").permitAll()
  37. .antMatchers("/login/**").permitAll()
  38. .antMatchers("/logout/**").permitAll()
  39. .and()
  40. .formLogin().permitAll();
  41. }
  42. }

资源配置类ResourcesConfig : 

  1. package application.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  4. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
  5. import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
  6. /**
  7. * @author: wtl
  8. * @License: (C) Copyright 2021, wtl Corporation Limited.
  9. * @Contact: 1050100468@qq.com
  10. * @Date: 2021/7/31 14:20
  11. * @Version: 1.0
  12. * @Description:
  13. */
  14. @Configuration
  15. @EnableResourceServer
  16. public class ResourcesConfig extends ResourceServerConfigurerAdapter {
  17. @Override
  18. public void configure(HttpSecurity http) throws Exception {
  19. http
  20. .authorizeRequests()
  21. .anyRequest().authenticated()
  22. .and()
  23. .requestMatchers().antMatchers("/user/**");
  24. }
  25. }

授权服务AuthorizationServer : 

  1. package application.config;
  2. import lombok.RequiredArgsConstructor;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.security.authentication.AuthenticationManager;
  5. import org.springframework.security.crypto.password.PasswordEncoder;
  6. import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
  7. import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
  8. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
  9. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
  10. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
  11. import javax.annotation.Resource;
  12. /**
  13. * @author: wtl
  14. * @License: (C) Copyright 2021, wtl Corporation Limited.
  15. * @Contact: 1050100468@qq.com
  16. * @Date: 2021/7/31 14:05
  17. * @Version: 1.0
  18. * @Description:
  19. */
  20. @Configuration
  21. @EnableAuthorizationServer
  22. public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
  23. @Resource
  24. private PasswordEncoder passwordEncoder;
  25. @Resource
  26. private UserService userService;
  27. @Resource
  28. private AuthenticationManager authenticationManager;
  29. @Override
  30. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  31. endpoints
  32. .userDetailsService(userService)
  33. .authenticationManager(authenticationManager);
  34. }
  35. @Override
  36. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  37. clients.inMemory()
  38. //clientId
  39. .withClient("admin")
  40. //密码
  41. .secret(passwordEncoder.encode("112233"))
  42. //重定向地址,获取授权码
  43. .redirectUris("https://www.baidu.com")
  44. //授权范围
  45. .scopes("all")
  46. //授权类型
  47. .authorizedGrantTypes("authorization_code","password");
  48. }
  49. }

授权模式为 authorization_code时:

请求获取授权码的url:

http://localhost:8082/oauth/authorize?response_type=code&client_id=admin&redirect_uri=https://www.baidu.com&scope=all

首先登录鉴权:

 

 post请求:

 localhost:8082/oauth/token

 

 password模式:

localhost:8082/oauth/token

jwt官网:

https://jwt.io/

 

 JwtTokenConfig:

  1. package application.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.security.oauth2.provider.token.TokenEnhancer;
  5. import org.springframework.security.oauth2.provider.token.TokenStore;
  6. import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
  7. import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
  8. /**
  9. * @author: wtl
  10. * @License: (C) Copyright 2021, wtl Corporation Limited.
  11. * @Contact: 1050100468@qq.com
  12. * @Date: 2021/7/31 21:45
  13. * @Version: 1.0
  14. * @Description:
  15. */
  16. @Configuration
  17. public class JwtTokenConfig {
  18. @Bean
  19. public TokenStore jwtTokenStore(){
  20. return new JwtTokenStore(jwtAccessTokenConverter());
  21. }
  22. @Bean
  23. public JwtAccessTokenConverter jwtAccessTokenConverter(){
  24. JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
  25. //jwt token里的盐
  26. jwtAccessTokenConverter.setSigningKey("wtl199201180271");
  27. return jwtAccessTokenConverter;
  28. }
  29. @Bean
  30. public TokenEnhancer tokenEnhancer(){
  31. return new MineTokenEnhancer();
  32. }
  33. }

自定义的TokenEnhancer-》MineTokenEnhancer : 

  1. package application.config;
  2. import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
  3. import org.springframework.security.oauth2.common.OAuth2AccessToken;
  4. import org.springframework.security.oauth2.provider.OAuth2Authentication;
  5. import org.springframework.security.oauth2.provider.token.TokenEnhancer;
  6. import java.util.HashMap;
  7. import java.util.Map;
  8. /**
  9. * @author: wtl
  10. * @License: (C) Copyright 2021, wtl Corporation Limited.
  11. * @Contact: 1050100468@qq.com
  12. * @Date: 2021/7/31 22:39
  13. * @Version: 1.0
  14. * @Description:
  15. */
  16. public class MineTokenEnhancer implements TokenEnhancer {
  17. @Override
  18. public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
  19. Map<String,Object> map = new HashMap<>();
  20. map.put("enhancer","enhancer info");
  21. ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(map);
  22. return oAuth2AccessToken;
  23. }
  24. }

AuthorizationServer : 

  1. package application.config;
  2. import lombok.RequiredArgsConstructor;
  3. import org.springframework.beans.factory.annotation.Qualifier;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.security.authentication.AuthenticationManager;
  6. import org.springframework.security.crypto.password.PasswordEncoder;
  7. import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
  8. import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
  9. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
  10. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
  11. import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
  12. import org.springframework.security.oauth2.provider.token.TokenEnhancer;
  13. import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
  14. import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
  15. import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
  16. import javax.annotation.Resource;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19. /**
  20. * @author: wtl
  21. * @License: (C) Copyright 2021, wtl Corporation Limited.
  22. * @Contact: 1050100468@qq.com
  23. * @Date: 2021/7/31 14:05
  24. * @Version: 1.0
  25. * @Description:
  26. */
  27. @Configuration
  28. @EnableAuthorizationServer
  29. public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
  30. @Resource
  31. private PasswordEncoder passwordEncoder;
  32. @Resource
  33. private UserService userService;
  34. @Resource
  35. private AuthenticationManager authenticationManager;
  36. @Resource
  37. @Qualifier("jwtTokenStore")
  38. private JwtTokenStore jwtTokenStore;
  39. @Resource
  40. private JwtAccessTokenConverter jwtAccessTokenConverter;
  41. @Resource
  42. private TokenEnhancer tokenEnhancer;
  43. @Override
  44. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  45. TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
  46. //token 增强,在JWT token里加入自定义信息
  47. List<TokenEnhancer> tokenEnhancerList = new ArrayList<>();
  48. tokenEnhancerList.add(tokenEnhancer);
  49. tokenEnhancerList.add(jwtAccessTokenConverter);
  50. tokenEnhancerChain.setTokenEnhancers(tokenEnhancerList);
  51. endpoints
  52. .userDetailsService(userService)
  53. .authenticationManager(authenticationManager)
  54. .tokenStore(jwtTokenStore)
  55. .accessTokenConverter(jwtAccessTokenConverter)
  56. .tokenEnhancer(tokenEnhancerChain);
  57. }
  58. @Override
  59. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  60. clients.inMemory()
  61. //clientId
  62. .withClient("admin")
  63. //密码
  64. .secret(passwordEncoder.encode("112233"))
  65. //重定向地址,获取授权码
  66. .redirectUris("https://www.baidu.com")
  67. //授权范围
  68. .scopes("all")
  69. //授权类型
  70. .authorizedGrantTypes("authorization_code","password");
  71. }
  72. }

 UserController :

  1. package application.controller;
  2. import org.springframework.security.core.Authentication;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. import javax.servlet.http.HttpServletRequest;
  7. /**
  8. * @author: wtl
  9. * @License: (C) Copyright 2021, wtl Corporation Limited.
  10. * @Contact: 1050100468@qq.com
  11. * @Date: 2021/7/31 14:18
  12. * @Version: 1.0
  13. * @Description:
  14. */
  15. @RestController
  16. @RequestMapping("/user")
  17. public class UserController {
  18. @GetMapping("/getCurrentUser")
  19. public Object getCurrentUser(Authentication authentication, HttpServletRequest httpServletRequest){
  20. String authorization = httpServletRequest.getHeader("Authorization");
  21. String[] split = authorization.split(" ");
  22. System.out.println(split[0]);
  23. System.out.println(split[1]);
  24. return authentication;
  25. }
  26. }

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

闽ICP备14008679号