按示例创建Spring Resource Server
2023-01-23 本文已影响0人
寻找无名的特质
按照示例创建Message Resource:spring-authorization-server/samples/messages-resource at main · spring-projects/spring-authorization-server (github.com)
示例使用gradle创建,现在使用Maven创建。
增加下面的库:
image.png
创建config和web两个目录,在config中增加config
package cn.jiagoushi.mymessageresource.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@EnableWebSecurity
@Configuration(proxyBeanMethods = false)
public class ResourceServerConfig {
// @formatter:off
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors()
.and()
.securityMatcher("/messages/**")
.authorizeHttpRequests()
.requestMatchers("/messages/**").hasAuthority("SCOPE_message.read")
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
}
// @formatter:on
}
在web下创建rest controller:
package cn.jiagoushi.mymessageresource.web;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin
public class MessagesController {
@GetMapping("/messages")
//@CrossOrigin
public String[] getMessages() {
return new String[] {"Message 1", "Message 2", "Message 3"};
}
}
在resources中增加application.yml:
server:
port: 8090
logging:
level:
root: INFO
org.springframework.web: INFO
org.springframework.security: INFO
org.springframework.security.oauth2: INFO
# org.springframework.boot.autoconfigure: DEBUG
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:9000
这样就可以了