이 문서 자료 : GitHub의이 · 여기를 클릭 || GitEE · 여기를 클릭하십시오
A, 보안 소개
1, 기본 개념
봄 보안은 엔터프라이즈 애플리케이션에 대한 보안 액세스 제어 선언적 보안 프레임 워크 Spring 기반의 솔루션을 제공 할 수 있습니다. 그것은 봄의 IOC, DI, AOP (Aspect 지향적 인 프로그래밍) 기능을 최대한 활용하여 보안 제어를위한 준비 감소, 보안 액세스 제어 선언적 응용 시스템을 제공하는 콩의 세트가 Spring 애플리케이션 컨텍스트에서 구성 할 수 있습니다 제공 작업 코드의 중복을 많이.
2, 핵심 API 읽기
1)에 SecurityContextHolder
현재 세션의 사용자 인증, 권한, 인증 및 기타 핵심 데이터를 보유 가장 기본적인 목적. SecurityContextHolder에 기본 ThreadLocal를 저장하는 인증 정보 정책, 전략에 쓰레드 범위. 사용자가 종료하면 자동으로 현재 스레드에 대한 인증 정보를 삭제합니다.
초기화 출처 : ThreadLocal를 스레드의 저명한 사용.
private static void initialize() {
if (!StringUtils.hasText(strategyName)) {
strategyName = "MODE_THREADLOCAL";
}
if (strategyName.equals("MODE_THREADLOCAL")) {
strategy = new ThreadLocalSecurityContextHolderStrategy();
} else if (strategyName.equals("MODE_INHERITABLETHREADLOCAL")) {
strategy = new InheritableThreadLocalSecurityContextHolderStrategy();
} else if (strategyName.equals("MODE_GLOBAL")) {
strategy = new GlobalSecurityContextHolderStrategy();
} else {
try {
Class<?> clazz = Class.forName(strategyName);
Constructor<?> customStrategy = clazz.getConstructor();
strategy = (SecurityContextHolderStrategy)customStrategy.newInstance();
} catch (Exception var2) {
ReflectionUtils.handleReflectionException(var2);
}
}
++initializeCount;
}
2) 인증
근원
public interface Authentication extends Principal, Serializable {
Collection<? extends GrantedAuthority> getAuthorities();
Object getCredentials();
Object getDetails();
Object getPrincipal();
boolean isAuthenticated();
void setAuthenticated(boolean var1) throws IllegalArgumentException;
}
소스 코드 분석
1)、getAuthorities,权限列表,通常是代表权限的字符串集合;
2)、getCredentials,密码,认证之后会移出,来保证安全性;
3)、getDetails,请求的细节参数;
4)、getPrincipal, 核心身份信息,一般返回UserDetails的实现类。
3)의 UserDetails
사용자 정보의 세부 사항을 캡슐화합니다.
public interface UserDetails extends Serializable {
Collection<? extends GrantedAuthority> getAuthorities();
String getPassword();
String getUsername();
boolean isAccountNonExpired();
boolean isAccountNonLocked();
boolean isCredentialsNonExpired();
boolean isEnabled();
}
4)의 UserDetailsService
일반적으로 인증을위한 사용자의 로그인 정보, 권한 부여에 비해 데이터베이스를 읽고, 인터페이스, 사용자 정의 사용자 인증 프로세스를 구현합니다.
public interface UserDetailsService {
UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException;
}
5)의 AuthenticationManager
인증 과정 최상위 인터페이스. 자신의 AuthenticationManager 인증을 사용자 정의 할 수있는 인터페이스를 구현할 수 있으며, 봄에는 기본 구현의 ProviderManager를 제공합니다.
public interface AuthenticationManager {
Authentication authenticate(Authentication var1) throws AuthenticationException;
}
SpringBoot2와 둘째, 통합
1, 프로세스 정보
1)、三个页面分类,page1、page2、page3
2)、未登录授权都不可以访问
3)、登录后根据用户权限,访问指定页面
4)、对于未授权页面,访问返回403:资源不可用
2, 핵심에 의존
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3 코어 구성
/**
* EnableWebSecurity注解使得SpringMVC集成了Spring Security的web安全支持
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 权限配置
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// 配置拦截规则
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/page1/**").hasRole("LEVEL1")
.antMatchers("/page2/**").hasRole("LEVEL2")
.antMatchers("/page3/**").hasRole("LEVEL3");
// 配置登录功能
http.formLogin().usernameParameter("user")
.passwordParameter("pwd")
.loginPage("/userLogin");
// 注销成功跳转首页
http.logout().logoutSuccessUrl("/");
//开启记住我功能
http.rememberMe().rememberMeParameter("remeber");
}
/**
* 自定义认证数据源
*/
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception{
builder.userDetailsService(userDetailService())
.passwordEncoder(passwordEncoder());
}
@Bean
public UserDetailServiceImpl userDetailService (){
return new UserDetailServiceImpl () ;
}
/**
* 密码加密
*/
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
/*
* 硬编码几个用户
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("spring").password("123456").roles("LEVEL1","LEVEL2")
.and()
.withUser("summer").password("123456").roles("LEVEL2","LEVEL3")
.and()
.withUser("autumn").password("123456").roles("LEVEL1","LEVEL3");
}
*/
}
4. 인증 과정
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Resource
private UserRoleMapper userRoleMapper ;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 这里可以捕获异常,使用异常映射,抛出指定的提示信息
// 用户校验的操作
// 假设密码是数据库查询的 123
String password = "$2a$10$XcigeMfToGQ2bqRToFtUi.sG1V.HhrJV6RBjji1yncXReSNNIPl1K";
// 假设角色是数据库查询的
List<String> roleList = userRoleMapper.selectByUserName(username) ;
List<GrantedAuthority> grantedAuthorityList = new ArrayList<>() ;
/*
* Spring Boot 2.0 版本踩坑
* 必须要 ROLE_ 前缀, 因为 hasRole("LEVEL1")判断时会自动加上ROLE_前缀变成 ROLE_LEVEL1 ,
* 如果不加前缀一般就会出现403错误
* 在给用户赋权限时,数据库存储必须是完整的权限标识ROLE_LEVEL1
*/
if (roleList != null && roleList.size()>0){
for (String role : roleList){
grantedAuthorityList.add(new SimpleGrantedAuthority(role)) ;
}
}
return new User(username,password,grantedAuthorityList);
}
}
5 테스트 인터페이스
@Controller
public class PageController {
/**
* 首页
*/
@RequestMapping("/")
public String index (){
return "home" ;
}
/**
* 登录页
*/
@RequestMapping("/userLogin")
public String loginPage (){
return "pages/login" ;
}
/**
* page1 下页面
*/
@PreAuthorize("hasAuthority('LEVEL1')")
@RequestMapping("/page1/{pageName}")
public String onePage (@PathVariable("pageName") String pageName){
return "pages/page1/"+pageName ;
}
/**
* page2 下页面
*/
@PreAuthorize("hasAuthority('LEVEL2')")
@RequestMapping("/page2/{pageName}")
public String twoPage (@PathVariable("pageName") String pageName){
return "pages/page2/"+pageName ;
}
/**
* page3 下页面
*/
@PreAuthorize("hasAuthority('LEVEL3')")
@RequestMapping("/page3/{pageName}")
public String threePage (@PathVariable("pageName") String pageName){
return "pages/page3/"+pageName ;
}
}
6, 로그인 화면
여기에 각각 보안 및 구성 파일에.
<div align="center">
<form th:action="@{/userLogin}" method="post">
用户名:<input name="user"/><br>
密 码:<input name="pwd"><br/>
<input type="checkbox" name="remeber"> 记住我<br/>
<input type="submit" value="Login">
</form>
</div>
셋째, 소스 주소
GitHub·地址
https://github.com/cicadasmile/middle-ware-parent
GitEE·地址
https://gitee.com/cicadasmile/middle-ware-parent