OAuth2ResourceServerSecurityConfiguration.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright 2002-2019 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package sample;
  17. import java.security.KeyFactory;
  18. import java.security.interfaces.RSAPublicKey;
  19. import java.security.spec.X509EncodedKeySpec;
  20. import java.util.Base64;
  21. import org.springframework.context.annotation.Bean;
  22. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  23. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  24. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  25. import org.springframework.security.oauth2.jwt.JwtDecoder;
  26. import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
  27. /**
  28. * @author Josh Cummings
  29. */
  30. @EnableWebSecurity
  31. public class OAuth2ResourceServerSecurityConfiguration extends WebSecurityConfigurerAdapter {
  32. @Override
  33. protected void configure(HttpSecurity http) throws Exception {
  34. // @formatter:off
  35. http
  36. .authorizeRequests()
  37. .antMatchers("/message/**").hasAuthority("SCOPE_message:read")
  38. .anyRequest().authenticated()
  39. .and()
  40. .oauth2ResourceServer()
  41. .jwt()
  42. .decoder(jwtDecoder());
  43. // @formatter:on
  44. }
  45. @Bean
  46. JwtDecoder jwtDecoder() throws Exception {
  47. return NimbusJwtDecoder.withPublicKey(key()).build();
  48. }
  49. private RSAPublicKey key() throws Exception {
  50. String encoded = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDdlatRjRjogo3WojgGHFHYLugd" +
  51. "UWAY9iR3fy4arWNA1KoS8kVw33cJibXr8bvwUAUparCwlvdbH6dvEOfou0/gCFQs" +
  52. "HUfQrSDv+MuSUMAe8jzKE4qW+jK+xQU9a03GUnKHkkle+Q0pX/g6jXZ7r1/xAK5D" +
  53. "o2kQ+X5xK9cipRgEKwIDAQAB";
  54. byte[] bytes = Base64.getDecoder().decode(encoded.getBytes());
  55. return (RSAPublicKey) KeyFactory.getInstance("RSA")
  56. .generatePublic(new X509EncodedKeySpec(bytes));
  57. }
  58. }