话不多说
导包
<!-- spring security 包含下面两个注释掉的包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.security</groupId>-->
<!-- <artifactId>spring-security-web</artifactId>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.security</groupId>-->
<!-- <artifactId>spring-security-config</artifactId>-->
<!-- </dependency>-->
- WebSecurityConfigurerAdapter:自定义 Security 策略
- AuthenticationManagerBuilder:自定义认证策略
- @EnableWebSecurity:开启WebSecuryti模式
Authentication - 认证
Authorization - 授权
本质上主要是使用了AOP 和 拦截器!
package com.people.management.config;
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.crypto.bcrypt.BCryptPasswordEncoder;
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
// 授权
@Override
protected void configure(HttpSecurity http) throws Exception {
// 请求授权的规则 目前是根据权限认证
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/company").hasRole("user")
.antMatchers("/resource").hasRole("admin");
// 没有权限默认事件 - 比如登录界面
/*
loginPage - 定制登录界面
loginProcessingUrl - 实际上点击登录后访问的路径
usernameParameter passwordParameter - - 设置表单传参的属性
*/
http.formLogin().loginPage("/toLogin")
.usernameParameter("user")
.passwordParameter("pwd")
.loginProcessingUrl("/login");
// 放跨站攻击 关闭csrf功能
http.csrf().disable();
// 开启注销功能 - 删除cookie、之类的... 一般跳到首页或者登录界面
// logoutSuccessUrl - 注销成功跳转url
http.logout().logoutSuccessUrl("/login");
// 开启记住我功能,cookie 存活时间 2周。 自定义接收参数
http.rememberMe().rememberMeParameter("remenber");
}
// 认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 这些用户数据应该从数据库中获取
/*
password 这部分,必须要进行一些加密方式。 passwordEncoder(new BCryptPasswordEncoder())
否则后台报错 There is no PasswordEncoder mapped for the id "null"
*/
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("admin", "user")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("admin");
}
}