1. 程式人生 > >spring oauth2.0授權伺服器配置

spring oauth2.0授權伺服器配置

1.首先spring security基本配置

  1. public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

  2. ......

  3. @Override

  4. public void onStartup(ServletContext servletContext) throws ServletException {

  5. super.onStartup(servletContext);

  6. /** UrlRewriteFilter **/

  7. /*

  8. * servletContext.addFilter("UrlRewriteFilter",

  9. * UrlRewriteFilter.class).addMappingForUrlPatterns(null, false, "/*");

  10. */

  11. DelegatingFilterProxy filter = new DelegatingFilterProxy("springSecurityFilterChain");

  12. filter.setContextAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");

  13. servletContext.addFilter("springSecurityFilterChain", filter).addMappingForUrlPatterns(null, false, "/*");

  14. }

  15. }

  1. @Configuration

  2. @EnableWebSecurity

  3. @Order(2)

  4. public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

  5. @Autowired

  6. private UserDetailsService myUserDetailsService;

  7. @Override

  8. protected void configure(AuthenticationManagerBuilder auth) throws Exception {

  9. // auth.inMemoryAuthentication().withUser("marissa").password("koala").roles("USER").and().withUser("paul")

  10. // .password("emu").roles("USER");

  11. auth.userDetailsService(myUserDetailsService);

  12. }

  13. @Override

  14. public void configure(WebSecurity web) throws Exception {

  15. web.ignoring().antMatchers("/webjars/**", "/images/**", "/oauth/uncache_approvals", "/oauth/cache_approvals");

  16. }

  17. @Override

  18. protected UserDetailsService userDetailsService() {

  19. return myUserDetailsService;

  20. }

  21. @Override

  22. @Bean

  23. public AuthenticationManager authenticationManagerBean() throws Exception {

  24. return super.authenticationManagerBean();

  25. }

  26. @Override

  27. protected void configure(HttpSecurity http) throws Exception {

  28. System.out.println("==============SecurityConfiguration.configure(HttpSecurity http)");

  29. // @formatter:off

  30. http

  31. .authorizeRequests()

  32. .antMatchers("/login.jsp").permitAll()

  33. .anyRequest().hasRole("USER")

  34. .and()

  35. .exceptionHandling()

  36. .accessDeniedPage("/login.jsp?authorization_error=true")

  37. .and()

  38. // TODO: put CSRF protection back into this endpoint

  39. .csrf()

  40. .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))

  41. .disable()

  42. .logout()

  43. .logoutUrl("/logout")

  44. .logoutSuccessUrl("/login.jsp")

  45. .and()

  46. .formLogin()

  47. .loginProcessingUrl("/login")

  48. .failureUrl("/login.jsp?authentication_error=true")

  49. .loginPage("/login.jsp");

  50. // @formatter:on

  51. }

  52. }


2.配置oauth

  1. @Configuration

  2. public class OAuth2ServerConfig {

  3. @Configuration

  4. @EnableResourceServer

  5. @Order(6)

  6. protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

  7. @Override

  8. public void configure(ResourceServerSecurityConfigurer resources) {

  9. resources.resourceId(ResourcesIDs.USER_RESOURCE_ID).stateless(false);

  10. }

  11. @Override

  12. public void configure(HttpSecurity http) throws Exception {

  13. System.out.println("====================ResourceServerConfiguration.configure(HttpSecurity http)");

  14. // @formatter:off

  15. http

  16. // Since we want the protected resources to be accessible in the UI as well we need

  17. // session creation to be allowed (it's disabled by default in 2.0.6)

  18. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)

  19. .and()

  20. .requestMatchers()

  21. .antMatchers("/user/**")

  22. .and()

  23. .authorizeRequests()

  24. .antMatchers("/user/profile").access("#oauth2.hasScope('read') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))");

  25. // @formatter:on

  26. }

  27. }

  28. @Configuration

  29. @EnableAuthorizationServer

  30. protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

  31. @Autowired

  32. @Qualifier("myClientDetailsService")

  33. private ClientDetailsService clientDetailsService;

  34. @Autowired

  35. private TokenStore tokenStore;

  36. @Autowired

  37. private UserApprovalHandler userApprovalHandler;

  38. @Autowired

  39. @Qualifier("authenticationManagerBean")

  40. private AuthenticationManager authenticationManager;

  41. @Override

  42. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

  43. clients.withClientDetails(clientDetailsService);

  44. }

  45. @Override

  46. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

  47. endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)

  48. .authenticationManager(authenticationManager);

  49. /*

  50. * .pathMapping("/oauth/authorize", "/oauth2/authorize")

  51. * .pathMapping("/oauth/token", "/oauth2/token");

  52. */

  53. // 以上的註釋掉的是用來改變配置的

  54. }

  55. @Override

  56. public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {

  57. // oauthServer.realm("sparklr2/client");

  58. oauthServer.allowFormAuthenticationForClients();

  59. }

  60. @Bean

  61. public TokenStore tokenStore() {

  62. return new InMemoryTokenStore();

  63. }

  64. }

  65. /**

  66. * @author admin

  67. *

  68. * some bean denfinition

  69. *

  70. */

  71. @Configuration

  72. protected static class Stuff {

  73. @Autowired

  74. @Qualifier("myClientDetailsService")

  75. private ClientDetailsService clientDetailsService;

  76. @Autowired

  77. private TokenStore tokenStore;

  78. @Bean

  79. public ApprovalStore approvalStore() throws Exception {

  80. TokenApprovalStore store = new TokenApprovalStore();

  81. store.setTokenStore(tokenStore);

  82. return store;

  83. }

  84. @Bean

  85. @Lazy

  86. @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)

  87. public MyUserApprovalHandler userApprovalHandler() throws Exception {

  88. MyUserApprovalHandler handler = new MyUserApprovalHandler();

  89. handler.setApprovalStore(approvalStore());

  90. handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));

  91. handler.setClientDetailsService(clientDetailsService);

  92. handler.setUseApprovalStore(true);

  93. return handler;

  94. }

  95. }


以上是基於註解配置的

一定注意: ResourceServerConfiguration 和 SecurityConfiguration上配置的順序,  SecurityConfiguration一定要在ResourceServerConfiguration 之前,因為spring實現安全是通過新增過濾器(Filter)來實現的,基本的安全過濾應該在oauth過濾之前, 所以在SecurityConfiguration設定@Order(2), 在ResourceServerConfiguration上設定@Order(6)

其它類:

MyUserApprovalHandler.java

  1. public class MyUserApprovalHandler extends ApprovalStoreUserApprovalHandler {

  2. private boolean useApprovalStore = true;

  3. private ClientDetailsService clientDetailsService;

  4. /**

  5. * Service to load client details (optional) for auto approval checks.

  6. *

  7. * @param clientDetailsService

  8. * a client details service

  9. */

  10. public void setClientDetailsService(ClientDetailsService clientDetailsService) {

  11. this.clientDetailsService = clientDetailsService;

  12. super.setClientDetailsService(clientDetailsService);

  13. }

  14. /**

  15. * @param useApprovalStore

  16. * the useTokenServices to set

  17. */

  18. public void setUseApprovalStore(boolean useApprovalStore) {

  19. this.useApprovalStore = useApprovalStore;

  20. }

  21. /**

  22. * Allows automatic approval for a white list of clients in the implicit

  23. * grant case.

  24. *

  25. * @param authorizationRequest

  26. * The authorization request.

  27. * @param userAuthentication

  28. * the current user authentication

  29. *

  30. * @return An updated request if it has already been approved by the current

  31. * user.

  32. */

  33. @Override

  34. public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest,

  35. Authentication userAuthentication) {

  36. boolean approved = false;

  37. // If we are allowed to check existing approvals this will short circuit

  38. // the decision

  39. if (useApprovalStore) {

  40. authorizationRequest = super.checkForPreApproval(authorizationRequest, userAuthentication);

  41. approved = authorizationRequest.isApproved();

  42. } else {

  43. if (clientDetailsService != null) {

  44. Collection<String> requestedScopes = authorizationRequest.getScope();

  45. try {

  46. ClientDetails client = clientDetailsService

  47. .loadClientByClientId(authorizationRequest.getClientId());

  48. for (String scope : requestedScopes) {

  49. if (client.isAutoApprove(scope)) {

  50. approved = true;

  51. break;

  52. }

  53. }

  54. } catch (ClientRegistrationException e) {

  55. }

  56. }

  57. }

  58. authorizationRequest.setApproved(approved);

  59. return authorizationRequest;

  60. }

  61. }


MyClientDetailsService.java

  1. @Service

  2. public class MyClientDetailsService implements ClientDetailsService {

  3. private ClientDetailsService clientDetailsService;

  4. @PostConstruct

  5. public void init() {

  6. InMemoryClientDetailsServiceBuilder inMemoryClientDetailsServiceBuilder = new InMemoryClientDetailsServiceBuilder();

  7. // @formatter:off

  8. inMemoryClientDetailsServiceBuilder.

  9. withClient("tonr")

  10. .resourceIds(ResourcesIDs.USER_RESOURCE_ID)

  11. .authorizedGrantTypes("authorization_code", "implicit")

  12. .authorities("ROLE_CLIENT")

  13. .scopes("read", "write")

  14. .secret("secret")

  15. .and()

  16. .withClient("tonr-with-redirect")

  17. .resourceIds(ResourcesIDs.USER_RESOURCE_ID)

  18. .authorizedGrantTypes("authorization_code", "implicit")

  19. .authorities("ROLE_CLIENT")

  20. .scopes("read", "write")

  21. .secret("secret")

  22. // .redirectUris(tonrRedirectUri)

  23. .and()

  24. .withClient("my-client-with-registered-redirect")

  25. .resourceIds(ResourcesIDs.USER_RESOURCE_ID)

  26. .authorizedGrantTypes("authorization_code", "client_credentials")

  27. .authorities("ROLE_CLIENT")

  28. .scopes("read", "trust")

  29. .redirectUris("http://anywhere?key=value")

  30. .and()

  31. .withClient("my-trusted-client")

  32. .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")

  33. .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")

  34. .scopes("read", "write", "trust")

  35. .accessTokenValiditySeconds(60)

  36. .and()

  37. .withClient("my-trusted-client-with-secret")

  38. .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")

  39. .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")

  40. .scopes("read", "write", "trust")

  41. .secret("somesecret")

  42. .and()

  43. .withClient("my-less-trusted-client")

  44. .authorizedGrantTypes("authorization_code", "implicit")

  45. .authorities("ROLE_CLIENT")

  46. .scopes("read", "write", "trust")

  47. .and()

  48. .withClient("my-less-trusted-autoapprove-client")

  49. .authorizedGrantTypes("implicit")

  50. .authorities("ROLE_CLIENT")

  51. .scopes("read", "write", "trust")

  52. .autoApprove(true);

  53. // @formatter:on

  54. try {

  55. clientDetailsService = inMemoryClientDetailsServiceBuilder.build();

  56. } catch (Exception e) {

  57. // TODO Auto-generated catch block

  58. e.printStackTrace();

  59. }

  60. }

  61. @Override

  62. public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {

  63. System.out.println("loadClientByClientId:" + clientId + " ----------------------");

  64. return clientDetailsService.loadClientByClientId(clientId);

  65. }

  66. }