Advertisement
Guest User

Untitled

a guest
Dec 28th, 2016
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.86 KB | None | 0 0
  1. http://localhost:8082/oauth/authorize
  2. http://localhost:8082/oauth/token
  3. ...
  4.  
  5. http://localhost:8081/users (protected resource)
  6.  
  7. HttpHeaders headers = new HttpHeaders()
  8. ResponseEntity<List<String>> response = restTemplate.exchange('http://localhost:8081/users', HttpMethod.GET, null, new ParameterizedTypeReference<List<String>>(){}, [])
  9. response.getBody()
  10.  
  11. ImplicitResourceDetails resource = (ImplicitResourceDetails) details;
  12. try {
  13. ...
  14.  
  15. @EnableAuthorizationServer
  16. @SpringBootApplication
  17. class Oauth2AuthorizationServerApplication {
  18.  
  19. static void main(String[] args) {
  20. SpringApplication.run Oauth2AuthorizationServerApplication, args
  21. }
  22. }
  23.  
  24. @Configuration
  25. class OAuth2Config extends AuthorizationServerConfigurerAdapter{
  26.  
  27. @Autowired
  28. private AuthenticationManager authenticationManager
  29.  
  30. @Bean
  31. public UserDetailsService userDetailsService() throws Exception {
  32. InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager([])
  33. manager.createUser(new User("jose","mypassword", [new SimpleGrantedAuthority("ROLE_USER")]))
  34. manager.createUser(new User("themostuntrustedclientid","themostuntrustedclientsecret", [new SimpleGrantedAuthority("ROLE_USER")]))
  35. return manager
  36. }
  37.  
  38. @Bean
  39. public TokenStore tokenStore() {
  40. return new InMemoryTokenStore();
  41. }
  42.  
  43. @Override
  44. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  45. clients.inMemory()
  46.  
  47. //curl trustedclient:trustedclientsecret@localhost:8082/oauth/token -d grant_type=password -d username=user -d password=cec31d99-e5ee-4f1d-b9a3-8d16d0c6eeb5 -d scope=read
  48. .withClient("themostuntrustedclientid")
  49. .secret("themostuntrustedclientsecret")
  50. .authorizedGrantTypes("implicit")
  51. .authorities("ROLE_USER")
  52. .scopes("read", "write")
  53. .accessTokenValiditySeconds(60)
  54.  
  55. }
  56.  
  57. @Override
  58. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  59. endpoints.authenticationManager(this.authenticationManager);
  60. }
  61.  
  62. @Override
  63. public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
  64. //security.checkTokenAccess('hasRole("ROLE_RESOURCE_PROVIDER")')
  65. security.checkTokenAccess('isAuthenticated()')
  66. }
  67. }
  68.  
  69. @EnableResourceServer
  70. @SpringBootApplication
  71. class Oauth2ResourceServerApplication {
  72.  
  73. static void main(String[] args) {
  74. SpringApplication.run Oauth2ResourceServerApplication, args
  75. }
  76. }
  77.  
  78. @Configuration
  79. class OAuth2Config extends ResourceServerConfigurerAdapter{
  80.  
  81. @Value('${security.oauth2.resource.token-info-uri}')
  82. private String checkTokenEndpointUrl
  83.  
  84. @Override
  85. public void configure(HttpSecurity http) throws Exception {
  86. http
  87. // Since we want the protected resources to be accessible in the UI as well we need
  88. // session creation to be allowed (it's disabled by default in 2.0.6)
  89. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
  90. .and()
  91. .requestMatchers().antMatchers("/users/**")
  92. .and()
  93. .authorizeRequests()
  94. .antMatchers(HttpMethod.GET, "/users").access("#oauth2.hasScope('read')")
  95. .antMatchers(HttpMethod.PUT, "/users/**").access("#oauth2.hasScope('write')")
  96. }
  97.  
  98. @Override
  99. public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
  100. RemoteTokenServices remoteTokenServices = new RemoteTokenServices()
  101. remoteTokenServices.setCheckTokenEndpointUrl(checkTokenEndpointUrl)
  102. remoteTokenServices.setClientId("usersResourceProvider")
  103. remoteTokenServices.setClientSecret("usersResourceProviderSecret")
  104. resources.tokenServices(remoteTokenServices)
  105. }
  106. }
  107.  
  108. @RestController
  109. class UsersRestController {
  110.  
  111. private Set<String> users = ["jose", "ana"]
  112.  
  113. @GetMapping("/users")
  114. def getUser(){
  115. return users
  116. }
  117.  
  118. @PutMapping("/users/{user}")
  119. void postUser(@PathVariable String user){
  120. users.add(user)
  121. }
  122.  
  123. }
  124.  
  125. @EnableOAuth2Client
  126. @SpringBootApplication
  127. class SpringBootOauth2ClientApplication {
  128.  
  129. static void main(String[] args) {
  130. SpringApplication.run SpringBootOauth2ClientApplication, args
  131. }
  132. }
  133.  
  134. @Configuration
  135. class SecurityConfig extends WebSecurityConfigurerAdapter{
  136.  
  137. @Autowired
  138. public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
  139. auth.eraseCredentials(false)
  140. .inMemoryAuthentication().withUser("jose").password("mypassword").roles('USER')
  141. }
  142.  
  143. @Override
  144. protected void configure(HttpSecurity http) throws Exception {
  145. http.csrf().disable()
  146. .authorizeRequests()
  147. .anyRequest().hasRole('USER')
  148. .and()
  149. .formLogin()
  150. }
  151.  
  152. }
  153.  
  154. @Configuration
  155. class OAuth2Config {
  156.  
  157. @Value('${oauth.resource:http://localhost:8082}')
  158. private String baseUrl
  159.  
  160. @Value('${oauth.authorize:http://localhost:8082/oauth/authorize}')
  161. private String authorizeUrl
  162.  
  163. @Value('${oauth.token:http://localhost:8082/oauth/token}')
  164. private String tokenUrl
  165.  
  166. @Autowired
  167. private OAuth2ClientContext oauth2Context
  168.  
  169. @Bean
  170. OAuth2ProtectedResourceDetails resource() {
  171. ImplicitResourceDetails resource = new ImplicitResourceDetails()
  172. resource.setAuthenticationScheme(AuthenticationScheme.header)
  173. resource.setAccessTokenUri(authorizeUrl)
  174. resource.setUserAuthorizationUri(authorizeUrl);
  175. resource.setClientId("themostuntrustedclientid")
  176. resource.setClientSecret("themostuntrustedclientsecret")
  177. resource.setScope(['read', 'write'])
  178. resource
  179. }
  180.  
  181. @Bean
  182. OAuth2RestTemplate restTemplate() {
  183. OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource(), oauth2Context)
  184. //restTemplate.setAuthenticator(new ApiConnectOAuth2RequestAuthenticator())
  185. restTemplate
  186. }
  187. }
  188.  
  189. @RestController
  190. class ClientRestController {
  191.  
  192. @Autowired
  193. private OAuth2RestTemplate restTemplate
  194.  
  195. def exceptionHandler(InsufficientScopeException ex){
  196. ex
  197. }
  198.  
  199. @GetMapping("/home")
  200. def getHome(HttpSession session){
  201. session.getId()
  202. }
  203.  
  204. @GetMapping("/users")
  205. def getUsers(HttpSession session){
  206. println 'Session id: '+ session.getId()
  207.  
  208. //TODO Move to after authentication
  209. Authentication auth = SecurityContextHolder.getContext().getAuthentication()
  210. restTemplate.getOAuth2ClientContext().getAccessTokenRequest().setAll(['client_id': 'themostuntrustedclientid', 'response_type': 'token', 'redirect_uri': 'http://localhost:8080/api/users'])
  211.  
  212. HttpHeaders headers = new HttpHeaders()
  213. ResponseEntity<List<String>> response = restTemplate.exchange('http://localhost:8081/users', HttpMethod.GET, null, new ParameterizedTypeReference<List<String>>(){}, [])
  214.  
  215.  
  216. response.getBody()
  217. }
  218. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement