(三十四)java版spring cloud微服务架构b2b2c电子商务平台-Security安全认证模块

安全认证类一定要设置在程序启动类的子包下面

springCloud的Security认证组件有两种添加方式。一种是通过编写公共的安全认证组件进行添加,另外一种是通过application.yml配置文件添加配置。
第一种、创建安全认证组件模块
步骤1:修改安全认证模块pom文件,

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

步骤2:创建安全认证类,创建安全认证类时请注意:类要放在所有后台服务启动类所在包的子包下

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
public void configGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("java").password("hello")
.roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// 表示所有的访问都必须进行认证处理后才可以正常进行
http.httpBasic().and().authorizeRequests().anyRequest()
.fullyAuthenticated();
// 所有的Rest服务一定要设置为无状态,以提升操作性能
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}

步骤3:在父pom中添加该组件的引用,

<dependency>
<groupId>com.ultrapower</groupId>
<artifactId>springCloud-security</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>

步骤4:在各服务端的pom文件中添加对此组件的引用:

<dependency>
<groupId>com.ultrapower</groupId>
<artifactId>springCloud-security</artifactId>
</dependency>

步骤5:如果后台服务端的启动类不在刚刚所建的安全配置类的父包或是同级路径下,需要修改服务的启动类路径。
步骤6:启动验证。可通过在路径上添加上用户密码在浏览器上访问,但是在程序中不可以如此操作。程序中的调用,见Ribbon实现或者Feign组件实现文章中。

第二种、通过配置文件添加安全认证。
上面写的是为所有的微服务添加安全认证。此处为Eureka注册中心通过配置文件添加安全认证。
步骤1:修改Eureka注册中心的pom文件。添加对Security安全认证模块的引用

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>

步骤2:修改Eureka注册中心的application.yml配置文件,添加对安全认证功能的开启

security:
basic:
enabled: true #开启安全认证服务
user: #添加认证账户及密码
name: ejava
password: ehello

步骤3:启动Eureka注册中心,按照之前的访问地址访问,看是否出现提示输入账号密码的界面,输入账号密码后,是否可以正常登录。
步骤4:修改服务端注册地址为

eureka:
client:
serviceUrl:
defaultZone: http://ejava:[email protected]:8000/eureka/

defaultZone: ejava:[email protected]:8000/eureka/,在原地址中添加了“ejava:ehello@”这部分内容。是进行安全人中的校验,此时服务端可以进行Eureka的注册认证。

猜你喜欢

转载自blog.csdn.net/vvx0206/article/details/93845955