pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
Controller为 Resource
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello() {
return "Hello Spring OAuth2";
}
}
启动入口 HelloOAuthApplication.java
@SpringBootApplication
public class HelloOAuth2Application {
public static void main(String[] args) {
SpringApplication.run(HelloOAuth2Application.class, args);
}
}
SecurityConfiguration:
@Configuration
@EnableGlobalAuthentication
public class SecurityConfiguration extends GlobalAuthenticationConfigurerAdapter {
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("123").authorities("ADMIN");
}
}
OAuth2 Configutation:
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
super.configure(security);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret("secret")
.authorizedGrantTypes("password", "authorization_code")
.scopes("myscope");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
}
@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/oauth/*").permitAll()
.antMatchers("/hello").authenticated();
}
}
启动,
C:\Users\ahan>curl -i -u client:secret http://localhost:8080/oauth/token -d "grant_type=password&scope=myscope&username=admin&password=123"
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 28 Aug 2017 08:00:43 GMT
{"access_token":"e9d51cd6-ed63-40e6-b3b8-7b5c09f5b451","token_type":"bearer","expires_in":42711,"scope":"myscope"}
根据上面得到的token,访问Resource
C:\Users\ahan>curl -i -H "Authorization: bearer e9d51cd6-ed63-40e6-b3b8-7b5c09f5b451" localhost:8080/hello
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: text/plain;charset=UTF-8
Content-Length: 19
Date: Mon, 28 Aug 2017 08:02:30 GMT
Hello Spring OAuth2