1、创建config包,后在下面添加3个配置类
(1)
(2)
2、AuthorizationServerConfig的内容
ppackage com.xachen.oauth2jwtcenter.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Arrays;
/**
* @author anxi
* @version 2020/9/20 19:11
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
public PasswordEncoder passwordEncoder;
// @Autowired
// public UserDetailsService userDetailsService;
@Autowired
public UserServiceImpl userDetailsService;
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
//TODO token持久化
//配置授权服务处理策略
endpoints.authenticationManager(authenticationManager).userDetailsService(userDetailsService);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//TODO 客户端持久化
//配置网关服务的用户名密码,仅网关服务可作为客户端可访问oauth服务
clients.inMemory()
.withClient("gateway-client").secret(passwordEncoder.encode("123456"))
.authorizedGrantTypes("refresh_token", "authorization_code", "password")
.accessTokenValiditySeconds(24 * 3600)
.scopes("all");
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
//允许客户端发送表单来进行权限认证来获取令牌
security.allowFormAuthenticationForClients()
//只允许认证的客户端,比如网关服务才可以获取和校验token
.checkTokenAccess("isAuthenticated()")
.tokenKeyAccess("isAuthenticated()");
security.addTokenEndpointAuthenticationFilter(new CorsFilter(corsConfigurationSource()));
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "HEAD", "DELETE", "OPTION"));
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.addExposedHeader("Authorization");
configuration.addExposedHeader("Content-disposition");//文件下载消息头
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
(2)UserServiceImpl的内容
package com.xachen.oauth2jwtcenter.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
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 java.util.ArrayList;
import java.util.List;
/**
* @author anxi
* @version 2020/9/20 13:21
*/
@Service
public class UserServiceImpl implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//TODO 用户持久化
if ("admin".equals(username)) {
String role = "ROLE_ADMIN";
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(role));
String password = passwordEncoder.encode("123456");
return new User(username, password, authorities);
}
throw new UsernameNotFoundException("no user");
}
}
(3)WebSecurityConfig的内容
package com.xachen.oauth2jwtcenter.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.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 anxi
* @version 2020/9/20 19:26
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
//默认的认证操作
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
//加密器
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//允许匿名访问所有接口 主要是 oauth 接口
http.authorizeRequests().antMatchers("/**").permitAll()
//以下陈添加 20210309
.anyRequest().authenticated()
.and()
.cors()
.and()
.csrf().disable();
}
}
3、测试方法
(1)base64的在线转换地址如下
(2)postman测试如下:
http://localhost:9000/oauth/token?grant_type=password&username=admin&password=123456&scope=all
头中
Authorization
Basic Z2F0ZXdheS1jbGllbnQ6MTIzNDU2
测试结果如下