Polish OAuth SSO

This commit is contained in:
Phillip Webb
2015-06-03 18:46:12 -07:00
parent 31d6a0f17a
commit 09a29a7207
33 changed files with 605 additions and 568 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,13 +13,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample;
package sample.secure.oauth2;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@@ -33,18 +35,24 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Flight {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String origin;
private String destination;
private String airline;
private String flightNumber;
private Date date;
private String traveler;
public Long getId() {
return id;
return this.id;
}
public void setId(Long id) {
@@ -52,7 +60,7 @@ public class Flight {
}
public String getOrigin() {
return origin;
return this.origin;
}
public void setOrigin(String origin) {
@@ -60,7 +68,7 @@ public class Flight {
}
public String getDestination() {
return destination;
return this.destination;
}
public void setDestination(String destination) {
@@ -68,7 +76,7 @@ public class Flight {
}
public String getAirline() {
return airline;
return this.airline;
}
public void setAirline(String airline) {
@@ -76,7 +84,7 @@ public class Flight {
}
public String getFlightNumber() {
return flightNumber;
return this.flightNumber;
}
public void setFlightNumber(String flightNumber) {
@@ -84,7 +92,7 @@ public class Flight {
}
public Date getDate() {
return date;
return this.date;
}
public void setDate(Date date) {
@@ -92,10 +100,11 @@ public class Flight {
}
public String getTraveler() {
return traveler;
return this.traveler;
}
public void setTraveler(String traveler) {
this.traveler = traveler;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample;
package sample.secure.oauth2;
import org.springframework.data.repository.CrudRepository;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -26,15 +27,16 @@ import org.springframework.security.access.prepost.PreAuthorize;
*/
public interface FlightRepository extends CrudRepository<Flight, Long> {
@PreAuthorize("#oauth2.hasScope('read')")
@Override
@PreAuthorize("#oauth2.hasScope('read')")
Iterable<Flight> findAll();
@PreAuthorize("#oauth2.hasScope('read')")
@Override
@PreAuthorize("#oauth2.hasScope('read')")
Flight findOne(Long aLong);
@PreAuthorize("#oauth2.hasScope('write')")
@Override
@PreAuthorize("#oauth2.hasScope('write')")
<S extends Flight> S save(S entity);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample;
package sample.secure.oauth2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -21,14 +21,11 @@ import org.springframework.security.config.annotation.method.configuration.Enabl
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
// @formatter:off
/**
* After you launch the app, you can seek a bearer token like this:
*
* <pre>
*
* curl localhost:8080/oauth/token -d "grant_type=password&scope=read&username=greg&password=turnquist" -u foo:bar
*
* </pre>
*
* <ul>
@@ -91,16 +88,14 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.E
* @author Craig Walls
* @author Greg Turnquist
*/
// @formatter:on
@SpringBootApplication
@EnableAuthorizationServer
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class Application {
public class SampleSecureOAuth2Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
SpringApplication.run(SampleSecureOAuth2Application.class, args);
}
}

View File

@@ -1,13 +1,4 @@
package sample;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
package sample.secure.oauth2;
import java.util.Map;
@@ -28,8 +19,20 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.web.context.WebApplicationContext;
import sample.secure.oauth2.SampleSecureOAuth2Application;
import sample.secure.oauth2.Flight;
import com.fasterxml.jackson.databind.ObjectMapper;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
/**
* Series of automated integration tests to verify proper behavior of auto-configured,
* OAuth2-secured system
@@ -38,12 +41,13 @@ import com.fasterxml.jackson.databind.ObjectMapper;
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringApplicationConfiguration(classes = Application.class)
@SpringApplicationConfiguration(classes = SampleSecureOAuth2Application.class)
@IntegrationTest("server.port:0")
public class ApplicationTests {
public class SampleSecureOAuth2ApplicationTests {
@Autowired
WebApplicationContext context;
@Autowired
FilterChainProxy filterChain;
@@ -53,85 +57,51 @@ public class ApplicationTests {
@Before
public void setUp() {
this.mvc = webAppContextSetup(this.context).addFilters(this.filterChain).build();
SecurityContextHolder.clearContext();
}
@Test
public void everythingIsSecuredByDefault() throws Exception {
this.mvc.perform(get("/").//
accept(MediaTypes.HAL_JSON)).// /
andExpect(status().isUnauthorized()).//
andDo(print());
this.mvc.perform(get("/flights").//
accept(MediaTypes.HAL_JSON)).// /
andExpect(status().isUnauthorized()).//
andDo(print());
this.mvc.perform(get("/flights/1").//
accept(MediaTypes.HAL_JSON)).// /
andExpect(status().isUnauthorized()).//
andDo(print());
this.mvc.perform(get("/alps").//
accept(MediaTypes.HAL_JSON)).// /
andExpect(status().isUnauthorized()).//
andDo(print());
this.mvc.perform(get("/").accept(MediaTypes.HAL_JSON))
.andExpect(status().isUnauthorized()).andDo(print());
this.mvc.perform(get("/flights").accept(MediaTypes.HAL_JSON))
.andExpect(status().isUnauthorized()).andDo(print());
this.mvc.perform(get("/flights/1").accept(MediaTypes.HAL_JSON))
.andExpect(status().isUnauthorized()).andDo(print());
this.mvc.perform(get("/alps").accept(MediaTypes.HAL_JSON))
.andExpect(status().isUnauthorized()).andDo(print());
}
@Test
@Ignore
// TODO: maybe show mixed basic + token auth on different resources?
public void accessingRootUriPossibleWithUserAccount() throws Exception {
String header = "Basic " + new String(Base64.encode("greg:turnquist".getBytes()));
this.mvc.perform(
get("/").//
accept(MediaTypes.HAL_JSON).//
header("Authorization",
"Basic "
+ new String(Base64.encode("greg:turnquist"
.getBytes()))))
.//
andExpect(header().string("Content-Type", MediaTypes.HAL_JSON.toString()))
.//
andExpect(status().isOk()).//
andDo(print());
get("/").accept(MediaTypes.HAL_JSON).header("Authorization", header))
.andExpect(
header().string("Content-Type", MediaTypes.HAL_JSON.toString()))
.andExpect(status().isOk()).andDo(print());
}
@Test
public void useAppSecretsPlusUserAccountToGetBearerToken() throws Exception {
// @formatter:off
String header = "Basic " + new String(Base64.encode("foo:bar".getBytes()));
MvcResult result = this.mvc
.perform(
post("/oauth/token").
header("Authorization",
"Basic " + new String(Base64.encode("foo:bar".getBytes()))).
param("grant_type", "password").
param("scope", "read").
param("username", "greg").
param("password", "turnquist")).
andExpect(status().isOk()).
andDo(print()).
andReturn();
// @formatter:on
post("/oauth/token").header("Authorization", header)
.param("grant_type", "password").param("scope", "read")
.param("username", "greg").param("password", "turnquist"))
.andExpect(status().isOk()).andDo(print()).andReturn();
Object accessToken = this.objectMapper.readValue(
result.getResponse().getContentAsString(), Map.class).get("access_token");
MvcResult flightsAction = this.mvc
.perform(get("/flights/1").//
accept(MediaTypes.HAL_JSON).//
header("Authorization", "Bearer " + accessToken))
.//
andExpect(header().string("Content-Type", MediaTypes.HAL_JSON.toString()))
.//
andExpect(status().isOk()).//
andDo(print()).//
andReturn();
.perform(
get("/flights/1").accept(MediaTypes.HAL_JSON).header(
"Authorization", "Bearer " + accessToken))
.andExpect(
header().string("Content-Type", MediaTypes.HAL_JSON.toString()))
.andExpect(status().isOk()).andDo(print()).andReturn();
Flight flight = this.objectMapper.readValue(flightsAction.getResponse()
.getContentAsString(), Flight.class);