Pour:
AuthorizationServerConfig: Configuration du serveur d'autorisation
ResourceServerConfig: Configuration
du serveur de ressources SecurityConfiguration: Configuration de la règle de sécurité Spring Security
<!--oauth2-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security.oauth.boot/spring-security-oauth2-autoconfigure -->
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
server:
port: 999
spring:
profiels:
active: minimal
#注册OAuth客户端
security:
oauth2:
client:
client-id: client
client-secret: client
package com.zcw.demospringsecurity.demo18;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Profile;
/**
* @ClassName : AuthorizationserverApplicationSimple
* @Description : 自定义配置的授权服务器
* @Author : Zhaocunwei
* @Date: 2020-04-13 20:04
*/
@Profile("simple")
@SpringBootApplication
public class AuthorizationserverApplicationSimple {
public static void main(String[] args){
SpringApplication.run(AuthorizationserverApplicationSimple.class,args);
}
}
package com.zcw.demospringsecurity.demo18;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
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.AuthorizationServerSecurityConfiguration;
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;
/**
* @ClassName : AuthorizationServerConfig
* @Description : 新建授权服务器配置类 --该demo来自《SpringSecurity实战(陈木鑫)》
* @Author : Zhaocunwei
* @Date: 2020-04-13 20:07
*/
@Profile("simple")
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
/**
* 配置授权服务器的安全,意味着/oauth/token端点和/oauth/authorize端点都应该是安全的
* 默认的设置覆盖了绝大数需求,所以一般情况下不需要做任何事情
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer security)throws Exception{
super.configure(security);
}
/**
* 该处通过配置,ClientDetailsService来配置注册到该授权服务器的客户端,clients信息
* 注意,除非在下面的configure(AuthorizationServerEndpointsConfigurer)中指定了一个
* AuthenticationManager,否则密码授权模式不可用,至少要配置一个client,否则无法启动服务器
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception{
clients.inMemory()
//client_id
.withClient("client-for-server")
//client_secret
.secret(passwordEncoder.encode("client-for-server"))
//该client 支持的授权模式,OAuth的client在请求code时,
//只有传递授权模式参数,该处包含的授权模式才可以访问
.authorizedGrantTypes("authorization_code","implicit")
//该client分配的access_token的有效时间要少于刷新时间,
.accessTokenValiditySeconds(7200)
//该client分配的access_token的可刷新时间要多于有效时间
//超过有效时间,单可以刷新时间范围的access_token也可以刷新
.refreshTokenValiditySeconds(72000)
//重定向
.redirectUris("http://localhost:8080/login/oauth2/code/authorizationserver")
.additionalInformation()
//该client 可以访问的资源服务器ID,每个资源服务器都有一个ID
.resourceIds(ResourceServerConfig.RESOURCE_ID)
//该client拥有的权限,资源服务器可以依据该处定义的权限,对client进行鉴权
.authorities("ROLE_CLIENT")
//该client可以访问的资源范围,资源服务器可以依据该处定义的范围对client进行鉴权
.scopes("profile","email","phone","aaa")
//自动批准的范围(scope)自动批准的scope在批准也不需要显示
//即不需要用户确认批准,如果所有scope 都自动批准,则不显示批准页
.autoApprove("profile");
}
/**
* 该方法是用来配置授权服务器特性的(Authorization Server endpoints)主要是一些
* 非安全的特性,比如token存储,token自定义,授权模式等
* 默认不需要任何配置,如果需要密码授权,则需要提供一个AuthenticationManager
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpointsConfigurer)throws Exception{
super.configure(endpointsConfigurer);
}
}
package com.zcw.demospringsecurity.demo18;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Profile;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
/**
* @ClassName : AuthServerApplicationMinimal
* @Description :开启授权服务器功能
* @Author : Zhaocunwei
* @Date: 2020-04-13 19:59
*/
@Profile("minimal")
@SpringBootApplication
@EnableAuthorizationServer
public class AuthServerApplicationMinimal {
public static void main(String[] args){
SpringApplication.run(AuthServerApplicationMinimal.class,args);
}
}
package com.zcw.demospringsecurity.demo18;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
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;
/**
* @ClassName : ResourceServerConfig
* @Description : 资源服务器配置---SpringSecurity实战(陈木鑫)
* @Author : Zhaocunwei
* @Date: 2020-04-14 09:56
*/
@Profile("simple")
@Configuration
@EnableResourceServer
@Slf4j
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
/**
* 摘抄来自书中内容一段话:---《SpringSecurity实战(陈木鑫)》
* 资源服务器的职责是对来自OAuth客户端的access_token进行鉴权,一个资源服务器包含多个端点(接口)
* 一部分端点作为资源服务器的资源提供给OAuth的client访问,
* 另外一个端点不由资源服务器管理。有资源服务器管理的端点安全性配置再此类中,其余端点的安全性配置在
* SecurityCongfiguration类中,当请求中包含OAuth2 access_token时,SpringSecurity会
* 根据资源服务器配置进行过滤,EnableResourceServer会创建一个
* webSecurityConfigurerAdapter,执行顺序(Order)是3
* 在SecurityConfiguration类之前运行,优先级更高
*/
public static final String RESOURCE_ID="authorizationserver";
@Override
public void configure(ResourceServerSecurityConfigurer resources)throws Exception{
super.configure(resources);
resources.resourceId(RESOURCE_ID);
}
@Override
public void configure(HttpSecurity httpSecurity)throws Exception{
log.info("ResourceServerConfig 中配置HttpSecurity对象执行");
//只有/me端点作为资源服务器的资源
httpSecurity.requestMatchers().antMatchers("/me")
.and()
.authorizeRequests()
.anyRequest()
.authenticated();
}
}
package com.zcw.demospringsecurity.demo18;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.validation.constraints.Size;
/**
* @ClassName : SecurityConfiguration
* @Description :
* @Author : Zhaocunwei
* @Date: 2020-04-14 10:16
*/
@Profile("simple")
@Configuration
@EnableWebSecurity(debug = true)
@Slf4j
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception{
authenticationManagerBuilder.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("user")).roles("USER")
.and()
.withUser("admin")
.password(passwordEncoder().encode("admin"))
.roles("ADMIN");
}
@Override
protected void configure(HttpSecurity httpSecurity)throws Exception{
log.info("SecurityConfiguration 中配置HttpSecurity对象执行");
httpSecurity.authorizeRequests()
.antMatchers("/")
.permitAll()
.anyRequest()
.hasAnyRole("USER","ADMIN")
.and()
.formLogin();
}
@Override
public void configure(WebSecurity webSecurity)throws Exception{
super.configure(webSecurity);
webSecurity.ignoring().antMatchers("/favicon.ico");
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}