spring oauth2.0授权服务器配置

1.首先spring security基本配置

 

 
  1. public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

  2.  
  3. ......

  4.  
  5. @Override

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

  7. super.onStartup(servletContext);

  8. /** UrlRewriteFilter **/

  9. /*

  10. * servletContext.addFilter("UrlRewriteFilter",

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

  12. */

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

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

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

  16.  
  17. }

  18. }

 

 

 

 
  1. @Configuration

  2. @EnableWebSecurity

  3. @Order(2)

  4. public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

  5. @Autowired

  6. private UserDetailsService myUserDetailsService;

  7.  
  8. @Override

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

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

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

  12. auth.userDetailsService(myUserDetailsService);

  13. }

  14.  
  15. @Override

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

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

  18. }

  19.  
  20. @Override

  21. protected UserDetailsService userDetailsService() {

  22. return myUserDetailsService;

  23. }

  24.  
  25. @Override

  26. @Bean

  27. public AuthenticationManager authenticationManagerBean() throws Exception {

  28. return super.authenticationManagerBean();

  29. }

  30.  
  31. @Override

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

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

  34.  
  35. // @formatter:off

  36. http

  37. .authorizeRequests()

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

  39. .anyRequest().hasRole("USER")

  40. .and()

  41. .exceptionHandling()

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

  43. .and()

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

  45. .csrf()

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

  47. .disable()

  48. .logout()

  49. .logoutUrl("/logout")

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

  51. .and()

  52. .formLogin()

  53. .loginProcessingUrl("/login")

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

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

  56. // @formatter:on

  57.  
  58. }

  59. }


2.配置oauth

 

 

 
  1. @Configuration

  2. public class OAuth2ServerConfig {

  3.  
  4. @Configuration

  5. @EnableResourceServer

  6. @Order(6)

  7. protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

  8.  
  9. @Override

  10. public void configure(ResourceServerSecurityConfigurer resources) {

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

  12. }

  13.  
  14. @Override

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

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

  17. // @formatter:off

  18. http

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

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

  21. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)

  22. .and()

  23. .requestMatchers()

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

  25. .and()

  26. .authorizeRequests()

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

  28. // @formatter:on

  29. }

  30.  
  31. }

  32.  
  33. @Configuration

  34. @EnableAuthorizationServer

  35. protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

  36. @Autowired

  37. @Qualifier("myClientDetailsService")

  38. private ClientDetailsService clientDetailsService;

  39.  
  40. @Autowired

  41. private TokenStore tokenStore;

  42.  
  43. @Autowired

  44. private UserApprovalHandler userApprovalHandler;

  45.  
  46. @Autowired

  47. @Qualifier("authenticationManagerBean")

  48. private AuthenticationManager authenticationManager;

  49.  
  50. @Override

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

  52. clients.withClientDetails(clientDetailsService);

  53. }

  54.  
  55. @Override

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

  57. endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)

  58. .authenticationManager(authenticationManager);

  59. /*

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

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

  62. */

  63. // 以上的注释掉的是用来改变配置的

  64. }

  65.  
  66. @Override

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

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

  69. oauthServer.allowFormAuthenticationForClients();

  70. }

  71.  
  72. @Bean

  73. public TokenStore tokenStore() {

  74. return new InMemoryTokenStore();

  75. }

  76. }

  77.  
  78. /**

  79. * @author admin

  80. *

  81. * some bean denfinition

  82. *

  83. */

  84. @Configuration

  85. protected static class Stuff {

  86.  
  87. @Autowired

  88. @Qualifier("myClientDetailsService")

  89. private ClientDetailsService clientDetailsService;

  90.  
  91. @Autowired

  92. private TokenStore tokenStore;

  93.  
  94. @Bean

  95. public ApprovalStore approvalStore() throws Exception {

  96. TokenApprovalStore store = new TokenApprovalStore();

  97. store.setTokenStore(tokenStore);

  98. return store;

  99. }

  100.  
  101. @Bean

  102. @Lazy

  103. @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)

  104. public MyUserApprovalHandler userApprovalHandler() throws Exception {

  105. MyUserApprovalHandler handler = new MyUserApprovalHandler();

  106. handler.setApprovalStore(approvalStore());

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

  108. handler.setClientDetailsService(clientDetailsService);

  109. handler.setUseApprovalStore(true);

  110. return handler;

  111. }

  112. }


以上是基于注解配置的

 

一定注意: ResourceServerConfiguration 和 SecurityConfiguration上配置的顺序,  SecurityConfiguration一定要在ResourceServerConfiguration 之前,因为spring实现安全是通过添加过滤器(Filter)来实现的,基本的安全过滤应该在oauth过滤之前, 所以在SecurityConfiguration设置@Order(2), 在ResourceServerConfiguration上设置@Order(6)

 

其它类:

MyUserApprovalHandler.java

 

 
  1. public class MyUserApprovalHandler extends ApprovalStoreUserApprovalHandler {

  2.  
  3. private boolean useApprovalStore = true;

  4.  
  5. private ClientDetailsService clientDetailsService;

  6.  
  7. /**

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

  9. *

  10. * @param clientDetailsService

  11. * a client details service

  12. */

  13. public void setClientDetailsService(ClientDetailsService clientDetailsService) {

  14. this.clientDetailsService = clientDetailsService;

  15. super.setClientDetailsService(clientDetailsService);

  16. }

  17.  
  18. /**

  19. * @param useApprovalStore

  20. * the useTokenServices to set

  21. */

  22. public void setUseApprovalStore(boolean useApprovalStore) {

  23. this.useApprovalStore = useApprovalStore;

  24. }

  25.  
  26. /**

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

  28. * grant case.

  29. *

  30. * @param authorizationRequest

  31. * The authorization request.

  32. * @param userAuthentication

  33. * the current user authentication

  34. *

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

  36. * user.

  37. */

  38. @Override

  39. public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest,

  40. Authentication userAuthentication) {

  41.  
  42. boolean approved = false;

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

  44. // the decision

  45. if (useApprovalStore) {

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

  47. approved = authorizationRequest.isApproved();

  48. } else {

  49. if (clientDetailsService != null) {

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

  51. try {

  52. ClientDetails client = clientDetailsService

  53. .loadClientByClientId(authorizationRequest.getClientId());

  54. for (String scope : requestedScopes) {

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

  56. approved = true;

  57. break;

  58. }

  59. }

  60. } catch (ClientRegistrationException e) {

  61. }

  62. }

  63. }

  64. authorizationRequest.setApproved(approved);

  65.  
  66. return authorizationRequest;

  67.  
  68. }

  69.  
  70. }


MyClientDetailsService.java

 

 

 
  1. @Service

  2. public class MyClientDetailsService implements ClientDetailsService {

  3.  
  4. private ClientDetailsService clientDetailsService;

  5.  
  6. @PostConstruct

  7. public void init() {

  8. InMemoryClientDetailsServiceBuilder inMemoryClientDetailsServiceBuilder = new InMemoryClientDetailsServiceBuilder();

  9. // @formatter:off

  10. inMemoryClientDetailsServiceBuilder.

  11. withClient("tonr")

  12. .resourceIds(ResourcesIDs.USER_RESOURCE_ID)

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

  14. .authorities("ROLE_CLIENT")

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

  16. .secret("secret")

  17. .and()

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

  19. .resourceIds(ResourcesIDs.USER_RESOURCE_ID)

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

  21. .authorities("ROLE_CLIENT")

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

  23. .secret("secret")

  24. // .redirectUris(tonrRedirectUri)

  25. .and()

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

  27. .resourceIds(ResourcesIDs.USER_RESOURCE_ID)

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

  29. .authorities("ROLE_CLIENT")

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

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

  32. .and()

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

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

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

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

  37. .accessTokenValiditySeconds(60)

  38. .and()

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

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

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

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

  43. .secret("somesecret")

  44. .and()

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

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

  47. .authorities("ROLE_CLIENT")

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

  49. .and()

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

  51. .authorizedGrantTypes("implicit")

  52. .authorities("ROLE_CLIENT")

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

  54. .autoApprove(true);

  55. // @formatter:on

  56. try {

  57. clientDetailsService = inMemoryClientDetailsServiceBuilder.build();

  58. } catch (Exception e) {

  59. // TODO Auto-generated catch block

  60. e.printStackTrace();

  61. }

  62. }

  63.  
  64. @Override

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

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

  67. return clientDetailsService.loadClientByClientId(clientId);

  68. }

  69.  
  70. }

 

 

 

 

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/buyaore_wo/article/details/48680981

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值