Spring Security 4とoauth 2統合注記+xml混合使用(基礎運転編)


Spring Security 4とoauth 2の統合
最近プロジェクトの中でoauth 2を使う必要があって、ネット上で多くの資料を探して、すべてめちゃくちゃで、東は寄せ集めて、ついに1版を走り出して、xmlの方式はあまりにも乱れて、走ることができなくて、やはり注釈の方式を使って、そしていくつかの肝心な配置をxmlの中に言及します.
gitアドレス:https://gitee.com/ffch/OauthUmp
Spring Security 4とoauth 2統合注記+xml混合使用(ベース運転編)spring Security 4とoauth 2統合注記+xml混合使用(ステップ編)spring Security 4とoauth 2統合注記+xml混合使用(ライセンスコード編)spring Security 4とoauth 2統合注記+xml混合使用(注意事項編)Spring Security 4とoauth 2統合注記+xml混合使用(6ビットの認証コードを置換)spring Security 4とoauth 2統合注記+xml混合使用(ユーザ名パスワード認証を置換)spring Security 4とoauth 2統合注記+xml混合使用(認証コードなどの追加データ検証)
ネット上に既存の注釈版案(実行に問題があり、後で修正)
リンク:http://www.yiibai.com/spring-security/secure-spring-rest-api-using-oauth2.html このリンクはspringmvcかspringbootで使うとは言っていませんが、どうせ私はspringmvcで使っていますから、使ってもいいです.私はここに引っ越して、同時に自分のコードを書きます.後で修正します.
pom.xml

		4.0.5.RELEASE
		2.4
		4.0.1.RELEASE
	

	
		
			junit
			junit
			4.10
			test
		
		
			org.springframework
			spring-core
			${spring.version}
		
		
			org.springframework
			spring-aop
			${spring.version}
		

		
			org.springframework
			spring-aspects
			${spring.version}
		
		
			org.springframework
			spring-context
			${spring.version}
		
		
			org.springframework
			spring-beans
			${spring.version}
		
		
			org.springframework
			spring-context-support
			${spring.version}
		
		
			org.springframework
			spring-expression
			${spring.version}
		
		
			org.springframework
			spring-web
			${spring.version}
		
		
			org.springframework
			spring-webmvc
			${spring.version}
		
		
			org.springframework
			spring-context-support
			${spring.version}
		
		
			org.springframework
			spring-orm
			${spring.version}
		
		
			org.springframework
			spring-tx
			${spring.version}
		
		
			org.springframework
			spring-test
			${spring.version}
			test
			
				
					commons-logging
					commons-logging
				
			
		

		
		
			org.springframework.security
			spring-security-core
			${spring.security.version}
		
		
			org.springframework.security
			spring-security-web
			${spring.security.version}
		
		
			org.springframework.security
			spring-security-config
			${spring.security.version}
		
		
			org.springframework.security.oauth
			spring-security-oauth2
			2.1.0.RELEASE
		

		
		
			org.slf4j
			slf4j-log4j12
			1.7.5
		
		
			log4j
			log4j
			1.2.17
		
		

		
		
			javax.servlet
			jstl
			1.2
		

		
			commons-httpclient
			commons-httpclient
			3.1
		

		
		
			org.codehaus.jackson
			jackson-core-lgpl
			1.8.1
		
		
			org.codehaus.jackson
			jackson-mapper-lgpl
			1.8.1
		
		
			net.sf.json-lib
			json-lib
			${jsonlib.version}
			jdk15
		
		
			com.fasterxml.jackson.core
			jackson-annotations
			2.3.0
		
		
			com.fasterxml.jackson.core
			jackson-core
			2.3.1
		
		
			com.fasterxml.jackson.core
			jackson-databind
			2.3.3
		
		

		
		
			com.thoughtworks.xstream
			xstream
			1.4.10
		

		
		
			org.mybatis
			mybatis
			3.2.5
		
		
			org.mybatis
			mybatis-spring
			1.3.0
		
		
		
			com.alibaba
			druid
			1.0.20
		
		
			com.oracle
			ojdbc6
			11.2.2
		
		
		
			net.sf.ehcache
			ehcache
			2.10.2
		
	

ResourceServer
package com.yiibai.springmvc.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

	private static final String RESOURCE_ID = "my_rest_api";
	
	@Override
	public void configure(ResourceServerSecurityConfigurer resources) {
		resources.resourceId(RESOURCE_ID).stateless(false);
	}

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.
		anonymous().disable()
		.requestMatchers().antMatchers("/user/**")
		.and().authorizeRequests()
		.antMatchers("/user/**").access("hasRole('ADMIN')")
		.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
	}

}

AuthorizationServer
package com.yiibai.springmvc.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
import org.springframework.security.oauth2.provider.token.TokenStore;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

	private static String REALM="MY_OAUTH_REALM";
	
	@Autowired
	private TokenStore tokenStore;

	@Autowired
	private UserApprovalHandler userApprovalHandler;

	@Autowired
	@Qualifier("authenticationManagerBean")
	private AuthenticationManager authenticationManager;

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

		clients.inMemory()
	        .withClient("my-trusted-client")
            .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
            .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
            .scopes("read", "write", "trust")
            .secret("secret")
            .accessTokenValiditySeconds(120).//Access token is only valid for 2 minutes.
            refreshTokenValiditySeconds(600);//Refresh token is only valid for 10 minutes.
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)
				.authenticationManager(authenticationManager);
	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
		oauthServer.realm(REALM+"/client");
	}

}

OAuth2SecurityConfiguration
package com.yiibai.springmvc.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {

	@Autowired
	private ClientDetailsService clientDetailsService;
	
	@Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
        .withUser("bill").password("abc123").roles("ADMIN").and()
        .withUser("bob").password("abc123").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
		http
		.csrf().disable()
		.anonymous().disable()
	  	.authorizeRequests()
	  	.antMatchers("/oauth/token").permitAll();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


	@Bean
	public TokenStore tokenStore() {
		return new InMemoryTokenStore();
	}

	@Bean
	@Autowired
	public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
		TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
		handler.setTokenStore(tokenStore);
		handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
		handler.setClientDetailsService(clientDetailsService);
		return handler;
	}
	
	@Bean
	@Autowired
	public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
		TokenApprovalStore store = new TokenApprovalStore();
		store.setTokenStore(tokenStore);
		return store;
	}
	
}

MethodSecurityConfig
package com.yiibai.springmvc.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
	@Autowired
	private OAuth2SecurityConfiguration securityConfig;

	@Override
	protected MethodSecurityExpressionHandler createExpressionHandler() {
		return new OAuth2MethodSecurityExpressionHandler();
	}
}

最後に
これでcopyは終わりますがspringmvcは使えません.web.xmlにfilterを付ける必要があります.
  
    springSecurityFilterChain
    org.springframework.web.filter.DelegatingFilterProxy
  
  
    springSecurityFilterChain
    /*
  

これで走れるようになり、http://www.yiibai.com/spring-security/secure-spring-rest-api-using-oauth2.html提供された方法は走りますが、いつもtokenエラーを提示していることに気づきます.なぜならtokenstoreが一致しないからです.これで@Bean注釈を使わずにxmlに書いて@AutoWiredでいいです.
xml構成tokenstore
	
	

構成が完了すると、OAuth 2 SecurityConfigurationファイルのtokenstoreをドロップできます.
//
//	@Bean
//	public TokenStore tokenStore() {
//		return new InMemoryTokenStore();
//	}

次に、ファイルAuthorizationServerConfigurationとResourceServerConfigurationのTokenStore@Autowiredをクリックします.
@Autowired
	private TokenStore tokenStore;

クライアントdetailsをxmlに言及する
Clientdetailsはコードに書かれていて、置き換えが不便で、プロファイルに書くことができます.

		
			
				
				
			
		

	

	
		
		
		
		
		
			
				read
				write
				trust
			
		
		
			
				password
				authorization_code
				refresh_token
				implicit
			
		
		
			
				
					
				
				
					
				
			
		
	
	
		
		
		
		
		
			
				read
				write
				trust
			
		
		
			
				password
				authorization_code
				refresh_token
				implicit
			
		
		
			
				
					
				
				
					
				
			
		
	

次のページでは、他のものとページを置き換える方法について説明します.