Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- http://localhost:8082/oauth/authorize
- http://localhost:8082/oauth/token
- ...
- http://localhost:8081/users (protected resource)
- HttpHeaders headers = new HttpHeaders()
- ResponseEntity<List<String>> response = restTemplate.exchange('http://localhost:8081/users', HttpMethod.GET, null, new ParameterizedTypeReference<List<String>>(){}, [])
- response.getBody()
- ImplicitResourceDetails resource = (ImplicitResourceDetails) details;
- try {
- ...
- @EnableAuthorizationServer
- @SpringBootApplication
- class Oauth2AuthorizationServerApplication {
- static void main(String[] args) {
- SpringApplication.run Oauth2AuthorizationServerApplication, args
- }
- }
- @Configuration
- class OAuth2Config extends AuthorizationServerConfigurerAdapter{
- @Autowired
- private AuthenticationManager authenticationManager
- @Bean
- public UserDetailsService userDetailsService() throws Exception {
- InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager([])
- manager.createUser(new User("jose","mypassword", [new SimpleGrantedAuthority("ROLE_USER")]))
- manager.createUser(new User("themostuntrustedclientid","themostuntrustedclientsecret", [new SimpleGrantedAuthority("ROLE_USER")]))
- return manager
- }
- @Bean
- public TokenStore tokenStore() {
- return new InMemoryTokenStore();
- }
- @Override
- public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
- clients.inMemory()
- //curl trustedclient:trustedclientsecret@localhost:8082/oauth/token -d grant_type=password -d username=user -d password=cec31d99-e5ee-4f1d-b9a3-8d16d0c6eeb5 -d scope=read
- .withClient("themostuntrustedclientid")
- .secret("themostuntrustedclientsecret")
- .authorizedGrantTypes("implicit")
- .authorities("ROLE_USER")
- .scopes("read", "write")
- .accessTokenValiditySeconds(60)
- }
- @Override
- public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
- endpoints.authenticationManager(this.authenticationManager);
- }
- @Override
- public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
- //security.checkTokenAccess('hasRole("ROLE_RESOURCE_PROVIDER")')
- security.checkTokenAccess('isAuthenticated()')
- }
- }
- @EnableResourceServer
- @SpringBootApplication
- class Oauth2ResourceServerApplication {
- static void main(String[] args) {
- SpringApplication.run Oauth2ResourceServerApplication, args
- }
- }
- @Configuration
- class OAuth2Config extends ResourceServerConfigurerAdapter{
- @Value('${security.oauth2.resource.token-info-uri}')
- private String checkTokenEndpointUrl
- @Override
- public void configure(HttpSecurity http) throws Exception {
- 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().antMatchers("/users/**")
- .and()
- .authorizeRequests()
- .antMatchers(HttpMethod.GET, "/users").access("#oauth2.hasScope('read')")
- .antMatchers(HttpMethod.PUT, "/users/**").access("#oauth2.hasScope('write')")
- }
- @Override
- public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
- RemoteTokenServices remoteTokenServices = new RemoteTokenServices()
- remoteTokenServices.setCheckTokenEndpointUrl(checkTokenEndpointUrl)
- remoteTokenServices.setClientId("usersResourceProvider")
- remoteTokenServices.setClientSecret("usersResourceProviderSecret")
- resources.tokenServices(remoteTokenServices)
- }
- }
- @RestController
- class UsersRestController {
- private Set<String> users = ["jose", "ana"]
- @GetMapping("/users")
- def getUser(){
- return users
- }
- @PutMapping("/users/{user}")
- void postUser(@PathVariable String user){
- users.add(user)
- }
- }
- @EnableOAuth2Client
- @SpringBootApplication
- class SpringBootOauth2ClientApplication {
- static void main(String[] args) {
- SpringApplication.run SpringBootOauth2ClientApplication, args
- }
- }
- @Configuration
- class SecurityConfig extends WebSecurityConfigurerAdapter{
- @Autowired
- public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
- auth.eraseCredentials(false)
- .inMemoryAuthentication().withUser("jose").password("mypassword").roles('USER')
- }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.csrf().disable()
- .authorizeRequests()
- .anyRequest().hasRole('USER')
- .and()
- .formLogin()
- }
- }
- @Configuration
- class OAuth2Config {
- @Value('${oauth.resource:http://localhost:8082}')
- private String baseUrl
- @Value('${oauth.authorize:http://localhost:8082/oauth/authorize}')
- private String authorizeUrl
- @Value('${oauth.token:http://localhost:8082/oauth/token}')
- private String tokenUrl
- @Autowired
- private OAuth2ClientContext oauth2Context
- @Bean
- OAuth2ProtectedResourceDetails resource() {
- ImplicitResourceDetails resource = new ImplicitResourceDetails()
- resource.setAuthenticationScheme(AuthenticationScheme.header)
- resource.setAccessTokenUri(authorizeUrl)
- resource.setUserAuthorizationUri(authorizeUrl);
- resource.setClientId("themostuntrustedclientid")
- resource.setClientSecret("themostuntrustedclientsecret")
- resource.setScope(['read', 'write'])
- resource
- }
- @Bean
- OAuth2RestTemplate restTemplate() {
- OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource(), oauth2Context)
- //restTemplate.setAuthenticator(new ApiConnectOAuth2RequestAuthenticator())
- restTemplate
- }
- }
- @RestController
- class ClientRestController {
- @Autowired
- private OAuth2RestTemplate restTemplate
- def exceptionHandler(InsufficientScopeException ex){
- ex
- }
- @GetMapping("/home")
- def getHome(HttpSession session){
- session.getId()
- }
- @GetMapping("/users")
- def getUsers(HttpSession session){
- println 'Session id: '+ session.getId()
- //TODO Move to after authentication
- Authentication auth = SecurityContextHolder.getContext().getAuthentication()
- restTemplate.getOAuth2ClientContext().getAccessTokenRequest().setAll(['client_id': 'themostuntrustedclientid', 'response_type': 'token', 'redirect_uri': 'http://localhost:8080/api/users'])
- HttpHeaders headers = new HttpHeaders()
- ResponseEntity<List<String>> response = restTemplate.exchange('http://localhost:8081/users', HttpMethod.GET, null, new ParameterizedTypeReference<List<String>>(){}, [])
- response.getBody()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement