赞
踩
maven依赖:
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-dependencies</artifactId>
- <version>Hoxton.SR12</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
-
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- <!-- 从依赖信息里移除 Tomcat配置 -->
- <exclusions>
- <exclusion>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-tomcat</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-undertow</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-oauth2</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-security</artifactId>
- </dependency>
-
-
- <!--离线包-->
- <!-- <dependency>-->
- <!-- <groupId>test</groupId>-->
- <!-- <artifactId>testa</artifactId>-->
- <!-- <version>0.0.1</version>-->
- <!-- <scope>system</scope>-->
- <!-- <systemPath>${project.basedir}/src/main/resources/lib/test.jar</systemPath>-->
- <!-- </dependency>-->
- </dependencies>
-
实现UserDetailsService 接口:
- package application.config;
-
- import org.springframework.security.core.authority.AuthorityUtils;
- import org.springframework.security.core.userdetails.UserDetails;
- import org.springframework.security.core.userdetails.UserDetailsService;
- import org.springframework.security.core.userdetails.UsernameNotFoundException;
- import org.springframework.security.crypto.password.PasswordEncoder;
- import org.springframework.stereotype.Service;
-
- import javax.annotation.Resource;
-
- /**
- * @author: wtl
- * @License: (C) Copyright 2021, wtl Corporation Limited.
- * @Contact: 1050100468@qq.com
- * @Date: 2021/7/31 13:54
- * @Version: 1.0
- * @Description:
- */
- @Service
- public class UserService implements UserDetailsService {
-
- @Resource
- private PasswordEncoder passwordEncoder;
-
- @Override
- public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
- return new User(username,passwordEncoder.encode("123456"),
- AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
- }
- }
实现UserDetails 接口:
- package application.config;
-
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.userdetails.UserDetails;
-
- import java.util.Collection;
- import java.util.List;
-
- /**
- * @author: wtl
- * @License: (C) Copyright 2021, wtl Corporation Limited.
- * @Contact: 1050100468@qq.com
- * @Date: 2021/7/31 13:55
- * @Version: 1.0
- * @Description:
- */
- public class User implements UserDetails {
-
- private String username;
- private String password;
- private List<GrantedAuthority> authorities;
-
- public User() {
- }
-
- public User(String username, String password, List<GrantedAuthority> authorities) {
- this.username = username;
- this.password = password;
- this.authorities = authorities;
- }
-
- @Override
- public Collection<? extends GrantedAuthority> getAuthorities() {
- return authorities;
- }
-
- @Override
- public String getPassword() {
- return password;
- }
-
- @Override
- public String getUsername() {
- return username;
- }
-
- @Override
- public boolean isAccountNonExpired() {
- return true;
- }
-
- @Override
- public boolean isAccountNonLocked() {
- return true;
- }
-
- @Override
- public boolean isCredentialsNonExpired() {
- return true;
- }
-
- @Override
- public boolean isEnabled() {
- return true;
- }
- }
SpringSecurity的SecurityConfig类:
- package application.config;
-
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.security.authentication.AuthenticationManager;
- import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
- import org.springframework.security.config.annotation.web.builders.HttpSecurity;
- import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
- import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
- import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
- import org.springframework.security.crypto.password.PasswordEncoder;
-
- /**
- * @author: wtl
- * @License: (C) Copyright 2021, wtl Corporation Limited.
- * @Contact: 1050100468@qq.com
- * @Date: 2021/7/31 13:53
- * @Version: 1.0
- * @Description:
- */
- @Configuration
- @EnableWebSecurity
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
-
- @Bean
- public PasswordEncoder passwordEncoder(){
- return new BCryptPasswordEncoder();
- }
-
- @Bean
- @Override
- protected AuthenticationManager authenticationManager() throws Exception {
- return super.authenticationManager();
- }
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .csrf().disable()
- .authorizeRequests()
- .antMatchers("/oauth/**").permitAll()
- .antMatchers("/login/**").permitAll()
- .antMatchers("/logout/**").permitAll()
- .and()
- .formLogin().permitAll();
- }
- }
资源配置类ResourcesConfig :
- package application.config;
-
- import org.springframework.context.annotation.Configuration;
- import org.springframework.security.config.annotation.web.builders.HttpSecurity;
- import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
- import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
-
- /**
- * @author: wtl
- * @License: (C) Copyright 2021, wtl Corporation Limited.
- * @Contact: 1050100468@qq.com
- * @Date: 2021/7/31 14:20
- * @Version: 1.0
- * @Description:
- */
- @Configuration
- @EnableResourceServer
- public class ResourcesConfig extends ResourceServerConfigurerAdapter {
-
- @Override
- public void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().authenticated()
- .and()
- .requestMatchers().antMatchers("/user/**");
-
- }
- }
授权服务AuthorizationServer :
- package application.config;
-
- import lombok.RequiredArgsConstructor;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.security.authentication.AuthenticationManager;
- import org.springframework.security.crypto.password.PasswordEncoder;
- import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
- import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
- import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
- import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
- import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
-
- import javax.annotation.Resource;
-
- /**
- * @author: wtl
- * @License: (C) Copyright 2021, wtl Corporation Limited.
- * @Contact: 1050100468@qq.com
- * @Date: 2021/7/31 14:05
- * @Version: 1.0
- * @Description:
- */
- @Configuration
- @EnableAuthorizationServer
- public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
-
- @Resource
- private PasswordEncoder passwordEncoder;
-
- @Resource
- private UserService userService;
-
- @Resource
- private AuthenticationManager authenticationManager;
-
- @Override
- public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
- endpoints
- .userDetailsService(userService)
- .authenticationManager(authenticationManager);
- }
-
- @Override
- public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
- clients.inMemory()
- //clientId
- .withClient("admin")
- //密码
- .secret(passwordEncoder.encode("112233"))
- //重定向地址,获取授权码
- .redirectUris("https://www.baidu.com")
- //授权范围
- .scopes("all")
- //授权类型
- .authorizedGrantTypes("authorization_code","password");
- }
- }
授权模式为 authorization_code时:
请求获取授权码的url:
首先登录鉴权:
post请求:
localhost:8082/oauth/token
password模式:
localhost:8082/oauth/token
jwt官网:
JwtTokenConfig:
- package application.config;
-
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.security.oauth2.provider.token.TokenEnhancer;
- import org.springframework.security.oauth2.provider.token.TokenStore;
- import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
- import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
-
- /**
- * @author: wtl
- * @License: (C) Copyright 2021, wtl Corporation Limited.
- * @Contact: 1050100468@qq.com
- * @Date: 2021/7/31 21:45
- * @Version: 1.0
- * @Description:
- */
- @Configuration
- public class JwtTokenConfig {
-
- @Bean
- public TokenStore jwtTokenStore(){
- return new JwtTokenStore(jwtAccessTokenConverter());
- }
-
-
- @Bean
- public JwtAccessTokenConverter jwtAccessTokenConverter(){
- JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
- //jwt token里的盐
- jwtAccessTokenConverter.setSigningKey("wtl199201180271");
- return jwtAccessTokenConverter;
- }
-
- @Bean
- public TokenEnhancer tokenEnhancer(){
- return new MineTokenEnhancer();
- }
- }
自定义的TokenEnhancer-》MineTokenEnhancer :
- package application.config;
-
- import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
- import org.springframework.security.oauth2.common.OAuth2AccessToken;
- import org.springframework.security.oauth2.provider.OAuth2Authentication;
- import org.springframework.security.oauth2.provider.token.TokenEnhancer;
-
- import java.util.HashMap;
- import java.util.Map;
-
- /**
- * @author: wtl
- * @License: (C) Copyright 2021, wtl Corporation Limited.
- * @Contact: 1050100468@qq.com
- * @Date: 2021/7/31 22:39
- * @Version: 1.0
- * @Description:
- */
- public class MineTokenEnhancer implements TokenEnhancer {
- @Override
- public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
- Map<String,Object> map = new HashMap<>();
- map.put("enhancer","enhancer info");
- ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(map);
- return oAuth2AccessToken;
- }
- }
AuthorizationServer :
- package application.config;
-
- import lombok.RequiredArgsConstructor;
- import org.springframework.beans.factory.annotation.Qualifier;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.security.authentication.AuthenticationManager;
- import org.springframework.security.crypto.password.PasswordEncoder;
- import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
- import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
- import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
- import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
- import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
- import org.springframework.security.oauth2.provider.token.TokenEnhancer;
- import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
- import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
- import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
-
- import javax.annotation.Resource;
- import java.util.ArrayList;
- import java.util.List;
-
- /**
- * @author: wtl
- * @License: (C) Copyright 2021, wtl Corporation Limited.
- * @Contact: 1050100468@qq.com
- * @Date: 2021/7/31 14:05
- * @Version: 1.0
- * @Description:
- */
- @Configuration
- @EnableAuthorizationServer
- public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
-
- @Resource
- private PasswordEncoder passwordEncoder;
-
- @Resource
- private UserService userService;
-
- @Resource
- private AuthenticationManager authenticationManager;
-
- @Resource
- @Qualifier("jwtTokenStore")
- private JwtTokenStore jwtTokenStore;
-
- @Resource
- private JwtAccessTokenConverter jwtAccessTokenConverter;
-
- @Resource
- private TokenEnhancer tokenEnhancer;
-
- @Override
- public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
- TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
- //token 增强,在JWT token里加入自定义信息
- List<TokenEnhancer> tokenEnhancerList = new ArrayList<>();
- tokenEnhancerList.add(tokenEnhancer);
- tokenEnhancerList.add(jwtAccessTokenConverter);
- tokenEnhancerChain.setTokenEnhancers(tokenEnhancerList);
- endpoints
- .userDetailsService(userService)
- .authenticationManager(authenticationManager)
- .tokenStore(jwtTokenStore)
- .accessTokenConverter(jwtAccessTokenConverter)
- .tokenEnhancer(tokenEnhancerChain);
- }
-
- @Override
- public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
- clients.inMemory()
- //clientId
- .withClient("admin")
- //密码
- .secret(passwordEncoder.encode("112233"))
- //重定向地址,获取授权码
- .redirectUris("https://www.baidu.com")
- //授权范围
- .scopes("all")
- //授权类型
- .authorizedGrantTypes("authorization_code","password");
- }
- }
UserController :
- package application.controller;
-
- import org.springframework.security.core.Authentication;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- import javax.servlet.http.HttpServletRequest;
-
- /**
- * @author: wtl
- * @License: (C) Copyright 2021, wtl Corporation Limited.
- * @Contact: 1050100468@qq.com
- * @Date: 2021/7/31 14:18
- * @Version: 1.0
- * @Description:
- */
- @RestController
- @RequestMapping("/user")
- public class UserController {
-
- @GetMapping("/getCurrentUser")
- public Object getCurrentUser(Authentication authentication, HttpServletRequest httpServletRequest){
- String authorization = httpServletRequest.getHeader("Authorization");
-
- String[] split = authorization.split(" ");
-
- System.out.println(split[0]);
- System.out.println(split[1]);
- return authentication;
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。