SpringSecurity是用来保护网页或者接口不被所有用户随意访问,因此它包含两个功能,认证和授权,认证就是登录,授权就是根据登录的用户的角色而给与不同的系统权限,比如你们的校园网,一般氛围管理员、教师和学生,你登录和老师登录系统后,得到的权限是不一样的,这就是权限管理。
在不用SpringSecurity等权限管理框架的情况下,我们设计的登录系统的基本逻辑就是:
前端表单输入用户名和密码——>通过用户名在数据库中查找该用户(queryByUsername)——>通过对比表单接收的密码和数据库查到的密码——>相同就登录成功,不相同就登录失败
而SpringSecurity的基本原理也相似,只不过其中有一些方式已经帮我们实现了,所以我们不需要自己去写。
SpringSecurity的内部运行逻辑所调用的顺序是怎么样的呢?
首先是登录验证阶段:
执行的入口是 配置类,如WebSecurityConfig这个类,这个类的标志就是它是用了以下两个注解:
@Configuration @EnableWebSecurity
package com.oycbest.config;
import com.oycbest.domain.User;
import com.oycbest.service.PasswordEncoder;
import com.oycbest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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.web.util.matcher.AntPathRequestMatcher;
import javax.annotation.Resource;
/**
* @Author: oyc
* @Date: 2019/1/29 13:45
* @Description:
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
private UserService<User> userService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("configureGlobal最先执行,运行系统后则自动执行");
auth.userDetailsService(userService).passwordEncoder(new PasswordEncoder());
System.out.println("configureGlobal最先执行,运行系统后则自动执行");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//允许基于HttpServletRequest使用限制访问
http.authorizeRequests()
//不需要身份认证
.antMatchers("/", "/home","/toLogin","/**/customer/**").permitAll()
.antMatchers("/js/**", "/css/**", "/images/**", "/fronts/**", "/doc/**", "/toLogin").permitAll()
.antMatchers("/user/**").hasAnyRole("USER")
//.hasIpAddress()//读取配置权限配置
.antMatchers("/**").access("hasRole('ADMIN')")
.anyRequest().authenticated()
//自定义登录界面
.and().formLogin().loginPage("/toLogin").loginProcessingUrl("/login").failureUrl("/toLogin?error").permitAll()
.and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.and().exceptionHandling().accessDeniedPage("/toLogin?deny")
.and().httpBasic()
.and().sessionManagement().invalidSessionUrl("/toLogin")
.and().csrf().disable();
}
}