您好,登錄后才能下訂單哦!
這篇文章主要介紹如何解決Spring Security的權(quán)限配置不生效問題,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
在集成Spring Security做接口權(quán)限配置時(shí),在給用戶配置的權(quán)限后,還是一直顯示“無權(quán)限”或者"權(quán)限不足"。
接口
@RequestMapping("/admin") @ResponseBody @PreAuthorize("hasRole('ADMIN')") public String printAdmin() { return "如果你看見這句話,說明你有ROLE_ADMIN角色"; } @RequestMapping("/user") @ResponseBody @PreAuthorize("hasRole('USER')") public String printUser() { return "如果你看見這句話,說明你有ROLE_USER角色"; }
SecurityConfig
.and() .authorizeRequests() .antMatchers("/user").hasAnyRole("USER") .antMatchers("/admin").hasAnyRole("ADMIN") .anyRequest().authenticated() //必須授權(quán)才能范圍
用戶攜帶權(quán)限
經(jīng)測試,只有用戶攜帶權(quán)限的字段為 “ROLE_” + 接口/配置 中的權(quán)限字段,才能控制生效,舉例:
將上面的用戶攜帶權(quán)限改為
<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
實(shí)體類User,Role,Menu
這里要實(shí)現(xiàn)UserDetails接口,這個(gè)接口好比一個(gè)規(guī)范。防止開發(fā)者定義的密碼變量名各不相同,從而導(dǎo)致springSecurity不知道哪個(gè)方法是你的密碼
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; ... }
和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>
創(chuàng)建UserService實(shí)現(xiàn)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; } }
創(chuàng)建MenuService
@Service public class MenuService { @Autowired private MenuMapper menuMapper; public List<Menu> getMenus() {return menuMapper.getMenus();} }
實(shí)現(xiàn)接口FilterInvocationSecurityMetadataSource
注:加@comppent注解,把自定義類注冊成spring組件
supports返回值設(shè)成true表示支持
重寫getAttributes()方法
invacation
調(diào)用 ,求助
metadata
元數(shù)據(jù)
@Component public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource { //ant風(fēng)格的路徑匹配器 AntPathMatcher pathMatcher = new AntPathMatcher(); @Autowired private MenuService menuService; //supports返回值設(shè)成true表示支持 @Override public boolean supports(Class<?> aClass) { return true; } @Override public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { //獲取當(dāng)前用戶請(qǐng)求的url String requestUrl=((FilterInvocation) object).getRequestUrl(); //數(shù)據(jù)庫中查詢出所有的路徑 List<Menu> menus =menuService.getMenus(); for (Menu menu : menus) { //判斷用戶請(qǐng)求的url和數(shù)據(jù)庫的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); } } //如果沒有匹配上就返回一個(gè)默認(rèn)的角色,作用好比作一個(gè)標(biāo)記 return SecurityConfig.createList("ROLE_def"); } @Override public Collection<ConfigAttribute> getAllConfigAttributes() { return null; } }
實(shí)現(xiàn)AccessDecisionManager接口 access 通道
注:加@comppent注解,把自定義類注冊成spring組件
將兩個(gè)supports()都設(shè)置成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) { //如果你請(qǐng)求的url在數(shù)據(jù)庫中不具備角色 if ("ROLE_def".equals(configAttribute.getAttribute())) { //在判斷是不是匿名用戶(也就是未登錄) if (authentication instanceof AnonymousAuthenticationToken) { System.out.println(">>>>>>>>>>>>>>>>匿名用戶>>>>>>>>>>>>>>"); throw new AccessDeniedException("權(quán)限不足,無法訪問"); }else{ //這里面就是已經(jīng)登錄的其他類型用戶,直接放行 System.out.println(">>>>>>>>>>>其他類型用戶>>>>>>>>>>>"); return; } } //如果你訪問的路徑在數(shù)據(jù)庫中具有角色就會(huì)來到這里 //Autherntication這里面存放著登錄后的用戶所有信息 Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); for (GrantedAuthority authority : authorities) { System.out.println(">>>>>>>authority(賬戶所擁有的權(quán)限):"+authority.getAuthority()); System.out.println(">>>>>>>configAttribute(路徑需要的角色):"+configAttribute.getAttribute()); //路徑需要的角色和賬戶所擁有的角色作比較 if (authority.getAuthority().equals(configAttribute.getAttribute())) { System.out.println(">>>>>>>>>>>>>>>>>>進(jìn)來>>>>>>>>>>>>>>>>>"); return; } } } } @Override public boolean supports(ConfigAttribute configAttribute) { return true; } @Override public boolean supports(Class<?> aClass) { return true; } }
WebSecurityConfig實(shí)現(xiàn)WebSecurityConfigurerAdapter
注入一會(huì)所需要的類
SpringSecurity5.0之后必須密碼加密
將數(shù)據(jù)庫查出的賬戶密碼交給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(); } //將數(shù)據(jù)庫查出的賬戶密碼交給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"; } }
以上是“如何解決Spring Security的權(quán)限配置不生效問題”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。