基于spring-boot-2.0.0
1,在pom.xml中添加:
<!-- security -->
<!-- https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2 -->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2,ServerConfig
package com.italkbb.homesecurity.alertmessage.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.crypto.password.PasswordEncoder; 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.AuthorizationServerSecurityConfigurer; @Configuration @EnableAuthorizationServer //提供/oauth/authorize,/oauth/token,/oauth/check_token,/oauth/confirm_access,/oauth/error public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired PasswordEncoder bCryptPasswordEncoder;//定义在SecurityConfig 中@Bean public PasswordEncoder passwordEncoder() @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.tokenKeyAccess("permitAll()") .checkTokenAccess("isAuthenticated()") //allow check token .allowFormAuthenticationForClients(); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("app") .secret(bCryptPasswordEncoder.encode("app")) .authorizedGrantTypes("client_credentials", "password", "refresh_token") .scopes("all") .resourceIds("oauth2-resource") .and() .withClient("app1") .secret(bCryptPasswordEncoder.encode("app1")) .authorizedGrantTypes("client_credentials", "password", "refresh_token") .scopes("all") .resourceIds("oauth2-resource1") .accessTokenValiditySeconds(1200) .refreshTokenValiditySeconds(50000) ; } }