1. 程式人生 > >spring security oauth2 jwt 認證和資源分離的配置文件(java類配置版)

spring security oauth2 jwt 認證和資源分離的配置文件(java類配置版)

boot cond lan 資源分離 測試 sql adapter 依賴 註入

最近再學習spring security oauth2。下載了官方的例子sparklr2和tonr2進行學習。但是例子裏包含的東西太多,不知道最簡單最主要的配置有哪些。所以決定自己嘗試搭建簡單版本的例子。學習的過程中搭建了認證和資源在一個工程的例子,將token存儲在數據庫的例子等等 。最後做了這個認證和資源分離的jwt tokens版本。網上找了一些可用的代碼然後做了一個整理, 同時測試了哪些代碼是必須的。可能仍有一些不必要的代碼在,歡迎大家賜教。

一.創建三個spring boot 工程,分別添加必要的依賴。認證和資源的工程需要添加依賴 <dependency>

<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.0.7.RELEASE</version>
</dependency>

二資源端工程的資源配置文件:

@Configuration
@EnableResourceServer
public class OAuth2ResourceService extends ResourceServerConfigurerAdapter {

private static final String SPARKLR_RESOURCE_ID = "apple";

@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.tokenServices(tokenServices()).resourceId(SPARKLR_RESOURCE_ID);
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
return converter;
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
return defaultTokenServices;
}

@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/hello").access("#oauth2.hasScope(‘read‘) or (!#oauth2.isOAuth() and hasRole(‘ROLE_USER‘))");
// @formatter:on
}
}

安全配置文件:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/hello").hasRole("USER")
.and().csrf().disable()
.formLogin().loginPage("/login").failureUrl("/login-error");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("hello").password("123").roles("USER");
}
}

三 認證端工程的認證配置文件:

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {
private static final String SPARKLR_RESOURCE_ID = "apple";

int accessTokenValiditySeconds = 3600;

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

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
return converter;
}

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

// @formatter:off
clients.inMemory().withClient("tonr")
.resourceIds(SPARKLR_RESOURCE_ID)
.authorizedGrantTypes("authorization_code", "implicit")
.authorities("ROLE_CLIENT")
.scopes("read", "write")
.secret("secret")
.accessTokenValiditySeconds(accessTokenValiditySeconds);
// @formatter:on
}
//jdbc
// @Bean
// public DataSource jdbcTokenDataSource(){
// DriverManagerDataSource dataSource = new DriverManagerDataSource();
// dataSource.setDriverClassName("com.MySQL.jdbc.Driver");
// dataSource.setUrl("jdbc:mysql://localhost/test");
// dataSource.setUsername("root");
// dataSource.setPassword("root");
// return dataSource;
// }

@Bean
public TokenStore tokenStore() {
// return new InMemoryTokenStore();
// return new JdbcTokenStore(jdbcTokenDataSource());
return new JwtTokenStore(accessTokenConverter());
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore())
.authenticationManager(this.authenticationManager)
.accessTokenConverter(accessTokenConverter());
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
defaultTokenServices.setSupportRefreshToken(true);
return defaultTokenServices;
}
}\

spring security安全配置文件:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**", "/index").permitAll()
.and()
.csrf()
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
.disable()
.formLogin().loginPage("/login").failureUrl("/login-error");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("hello").password("123").roles("USER");
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}

四 客戶端工程的配置文件:

@Configuration
@EnableOAuth2Client
public class ResourceConfiguration {

@Bean
public OAuth2ProtectedResourceDetails hello() {
AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
details.setId("hello");
details.setClientId("tonr");
details.setClientSecret("secret");
details.setAccessTokenUri("http://localhost:8083/auth/oauth/token");//認證服務器地址+/oauth/token
details.setUserAuthorizationUri("http://localhost:8083/auth/oauth/authorize");//認證服務器地址+/oauth/authorize
details.setScope(Arrays.asList("read", "write"));
return details;
}

@Bean
public OAuth2RestTemplate helloRestTemplate(OAuth2ClientContext oauth2Context) {//客戶端的信息被封裝到OAuth2RestTemplate用於請求資源
return new OAuth2RestTemplate(hello(), oauth2Context);
}
}

在業務邏輯的serviceImp類中 註入helloRestTemplate 然後:

@Autowired
private RestOperations helloRestTemplate

public String getDataFromResoureServer() {;

String data= helloRestTemplate.getForObject(URI.create("http://localhost:8080/resource/hello"), String.class);//請求資源服務器資源的路徑

return data;

}

spring security安全配置文件:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**", "/index").permitAll()
.and()
.formLogin()
.loginPage("/login").failureUrl("/login-error");
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("insecure").password("123").roles("USER");
}
}

http://blog.csdn.net/u010139801/article/details/68484090

spring security oauth2 jwt 認證和資源分離的配置文件(java類配置版)