package com.example.oauth.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
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.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
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.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
@Configuration
public class OAuth2ServerConfig {
private static final String DEMO_RESOURCE_ID = "order";
// 资源服务器配置
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(DEMO_RESOURCE_ID).stateless(true);
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers()
.anyRequest()
.and()
.anonymous()
.and()
.authorizeRequests()
// .antMatchers("/product
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
@Override
protected UserDetailsService userDetailsService() {
// 内存 , 实现了登录的接口
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withUsername("zhangsan")
.password(this.passwordEncoder().encode("123"))
.authorities("client")
.build());
manager.createUser(User.withUsername("user_2")
.password(this.passwordEncoder().encode("123"))
.authorities("USER")
.build());
return manager;
}
// http 请求的权限配置 , 和 路径, 和 处理器
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatchers()
.anyRequest()
.and()
.authorizeRequests()
.antMatchers("/oauth
@RestController
public class TestController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@GetMapping("/public/{id}")
public String getProduct(@PathVariable String id) {
logger.info("当前用户认证信息:{}", SecurityContextHolder.getContext().getAuthentication());
return "public id: " + id;
}
@GetMapping("/private/{id}")
public String getOrder(@PathVariable String id) {
logger.info("当前用户认证信息:{}", SecurityContextHolder.getContext().getAuthentication());
return "private id: " + id;
}
}
@EnableResourceServer
@SpringBootApplication
public class OauthApplication {
public static void main(String[] args) {
SpringApplication.run(OauthApplication.class, args);
}
}
spring.redis.host=localhost
spring.redis.database=0
spring.redis.port=6379
spring.redis.password=123456
#filter ����˳��,�������,���ز���
security.oauth2.resource.filter-order=3
logging.level.org.springframework.security: DEBUG
server.port=8083
readme
1.测试需要启动redis
2.直接get访问
localhost:8080/public/1 这个路径能通过
localhost:8080/private/1 这个路径不放行,需要认证
3.使用http工具post访问password模式
http://localhost:8080/oauth/token?username=zhangsan&password=123&grant_type=password&scope=select&client_id=client_2&client_secret=123456
使用http工具post访问client模式
http://localhost:8080/oauth/token?grant_type=client_credentials&scope=select&client_id=client_1&client_secret=123456
4.再次带上获取的tokenget访问 , get 请求
http://localhost:8080/private/1?access_token=bd77315b-5f83-433f-a4aa-b9f20b89ff34
或者
http://localhost:8080/private/1?access_token=d6912dd2-347d-4e64-98a3-922380dab7a0
这里的token 是上面任意种方式获取的 token