導入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.22</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
相關配置
application.properties
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/javaboy?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
實體類User,Role,Menu
這里要實現UserDetails接口,這個接口好比一個規范。防止開發者定義的密碼變量名各不相同,從而導致springSecurity不知道哪個方法是你的密碼
public class User implements UserDetails {
private Integer id;
private String username;
private String password;
private Boolean enabled;
private Boolean locked;
private List<Role> roleList;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
for (Role role : roleList) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return !locked;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return enabled;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Boolean getLocked() {
return locked;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
public List<Role> getRoleList() {
return roleList;
}
public void setRoleList(List<Role> roleList) {
this.roleList = roleList;
}
}
public class Role {
private Integer id;
private String name;
private String nameZh;
...
}
public class Menu {
private Integer id;
private String pattern;
private List<Role> roles;
...
}
創建UserMapper類&&UserMapper.xml和MenuMapper類&&MenuMapperxml
UserMapper
@Mapper
public interface UserMapper {
User getUserByName(String name);
List<Role> getRoleById(Integer id);
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qwl.mysecuritydy.mapper.UserMapper">
<select id="getUserByName" resultType="com.qwl.mysecuritydy.bean.User">
select * from user where username= #{name}
</select>
<select id="getRoleById" resultType="com.qwl.mysecuritydy.bean.Role">
select * from role where id in (select rid from user_role where uid = #{uid})
</select>
</mapper>
MenuMapper
@Mapper
public interface MenuMapper {
List<Menu> getMenus();
}
MemuMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qwl.mysecuritydy.mapper.MenuMapper">
<resultMap id="menus_map" type="com.qwl.mysecuritydy.bean.Menu">
<id property="id" column="id"/>
<result property="pattern" column="pattern"/>
<collection property="roles" ofType="com.qwl.mysecuritydy.bean.Role">
<id property="id" column="rid"/>
<result property="name" column="rname"/>
<result property="nameZh" column="rnameZh"/>
</collection>
</resultMap>
<select id="getMenus" resultMap="menus_map">
select m.*,r.id as rid,r.name as rname,r.nameZh as rnameZh from menu_role mr left join
menu m on mr.mid = m.id left join role r on mr.rid = r.id
</select>
</mapper>
創建UserService MenuService
創建UserService實現UserServiceDetails接口
@Service
public class UserService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.getUserByName(username);
if(user ==null){
throw new UsernameNotFoundException("用戶名不存在");
}
user.setRoleList(userMapper.getRoleById(user.getId()));
return user;
}
}
創建MenuService
@Service
public class MenuService {
@Autowired
private MenuMapper menuMapper;
public List<Menu> getMenus() {return menuMapper.getMenus();}
}
創建CustomFilterInvocationSecurityMetadataSource
實現接口FilterInvocationSecurityMetadataSource
注:加@comppent注解,把自定義類注冊成spring組件
supports返回值設成true表示支持
重寫getAttributes()方法
invacation 調用 ,求助
metadata 元數據
@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
//ant風格的路徑匹配器
AntPathMatcher pathMatcher = new AntPathMatcher();
@Autowired
private MenuService menuService;
//supports返回值設成true表示支持
@Override
public boolean supports(Class<?> aClass) {
return true;
}
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
//獲取當前用戶請求的url
String requestUrl=((FilterInvocation) object).getRequestUrl();
//數據庫中查詢出所有的路徑
List<Menu> menus =menuService.getMenus();
for (Menu menu : menus) {
//判斷用戶請求的url和數據庫的url是否能匹配的上
if (pathMatcher.match(menu.getPattern(), requestUrl)) {
List<Role> roles =menu.getRoles();
String[] roleStr = new String[roles.size()];
for (int i = 0; i < roles.size(); i++) {
roleStr[i]=roles.get(i).getName();
}
//將篩選的url路徑所具備的角色返回回去
return SecurityConfig.createList(roleStr);
}
}
//如果沒有匹配上就返回一個默認的角色,作用好比作一個標記
return SecurityConfig.createList("ROLE_def");
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
}
創建CustomAccessDecisionManager
實現AccessDecisionManager接口 access 通道
注:加@comppent注解,把自定義類注冊成spring組件
將兩個supports()都設置成true
重寫decide()方法
@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
//configattributes里存放着CustomFilterInvocationSecurityMetadataSource過濾出來的角色
for (ConfigAttribute configAttribute : collection) {
//如果你請求的url在數據庫中不具備角色
if ("ROLE_def".equals(configAttribute.getAttribute())) {
//在判斷是不是匿名用戶(也就是未登錄)
if (authentication instanceof AnonymousAuthenticationToken) {
System.out.println(">>>>>>>>>>>>>>>>匿名用戶>>>>>>>>>>>>>>");
throw new AccessDeniedException("權限不足,無法訪問");
}else{
//這里面就是已經登錄的其他類型用戶,直接放行
System.out.println(">>>>>>>>>>>其他類型用戶>>>>>>>>>>>");
return;
}
}
//如果你訪問的路徑在數據庫中具有角色就會來到這里
//Autherntication這里面存放着登錄后的用戶所有信息
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority authority : authorities) {
System.out.println(">>>>>>>authority(賬戶所擁有的權限):"+authority.getAuthority());
System.out.println(">>>>>>>configAttribute(路徑需要的角色):"+configAttribute.getAttribute());
//路徑需要的角色和賬戶所擁有的角色作比較
if (authority.getAuthority().equals(configAttribute.getAttribute())) {
System.out.println(">>>>>>>>>>>>>>>>>>進來>>>>>>>>>>>>>>>>>");
return;
}
}
}
}
@Override
public boolean supports(ConfigAttribute configAttribute) {
return true;
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
創建WebSecurityConfig配置類
WebSecurityConfig實現WebSecurityConfigurerAdapter
注入一會所需要的類
SpringSecurity5.0之后必須密碼加密
將數據庫查出的賬戶密碼交給SpringSecurity去判斷
配置HttpSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Autowired
private CustomFilterInvocationSecurityMetadataSource customFilterInvocationSecurityMetadataSource;
@Autowired
private CustomAccessDecisionManager customAccessDecisionManager;
//springSecutity5.0之后必密碼加密
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
//將數據庫查出的賬戶密碼交給springsecurity去判斷
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
//配置HttpSecurity
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O object){
object.setSecurityMetadataSource(customFilterInvocationSecurityMetadataSource);
object.setAccessDecisionManager(customAccessDecisionManager);
return object;
}
})
.and()
.formLogin()
.permitAll()
.and()
.csrf().disable();
}
}
Controller
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "hello";
}
@GetMapping("/dba/hello")
public String dba(){
return "hello dba";
}
@GetMapping("/admin/hello")
public String admin(){
return "hello admin";
}
@GetMapping("/user/hello")
public String user(){
return "hello user";
}
}