溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

springsecurity輕松實(shí)現(xiàn)角色權(quán)限的示例代碼

發(fā)布時(shí)間:2020-09-03 02:51:57 來源:腳本之家 閱讀:205 作者:怡蘅 欄目:編程語言

問題:

如何在springboot項(xiàng)目中使用springsecurity去實(shí)現(xiàn)角色權(quán)限管理呢?本文將盡可能簡單的一步步實(shí)現(xiàn)對接口的角色權(quán)限管理。

項(xiàng)目框架:

springsecurity輕松實(shí)現(xiàn)角色權(quán)限的示例代碼

sql:

user表:

CREATE TABLE `user` (
 `Id` int NOT NULL AUTO_INCREMENT,
 `UserName` varchar(255) NOT NULL,
 `CreatedDT` datetime DEFAULT NULL,
 `Age` int DEFAULT NULL,
 `Gender` int DEFAULT NULL,
 `Password` varchar(255) NOT NULL,
 PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

role表:

CREATE TABLE `role` (
 `Id` int NOT NULL AUTO_INCREMENT,
 `UserId` int DEFAULT NULL,
 `Role` varchar(255) DEFAULT NULL,
 `CreatedDT` datetime DEFAULT NULL,
 PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

maven:

在pom.xml中加入

   <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <!--SpringSecurity依賴配置-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <!--Hutool Java工具包-->
    <dependency>
      <groupId>cn.hutool</groupId>
      <artifactId>hutool-all</artifactId>
      <version>4.5.7</version>
    </dependency>

model:

實(shí)體類User要實(shí)現(xiàn)springsecurity的基本接口UserDetails,UserDetails里繼承了Serializable,不用擔(dān)心序列化

@Data 
public class User implements UserDetails { 
​ 
 public User() { 
 } 
​ 
 private static final long serialVersionUID = 1L; 
  
 private Integer id; 
​ 
 private String userName; 
​ 
 private Date createdDT; 
​ 
 private Integer age; 
​ 
 private Integer gender; 
​ 
 private String passWord; 
​ 
 private String role; 
​ 
 private List<GrantedAuthority> authorities; 
​ 
 public User(String userName, String passWord, List<GrantedAuthority> authorities) { 
 this.userName = userName; 
 this.passWord = passWord; 
 this.authorities = authorities; 
 } 
​ 
 @Override 
 public Collection<? extends GrantedAuthority> getAuthorities() { 
 return authorities; 
 } 
​ 
 @Override 
 public String getPassword() { 
 return this.passWord; 
 } 
​ 
 @Override 
 public String getUsername() { 
 return this.userName; 
 } 
​ 
 @Override 
 public boolean isAccountNonExpired() { 
 return true; 
 } 
​ 
 @Override 
 public boolean isAccountNonLocked() { 
 return true; 
 } 
​ 
 @Override 
 public boolean isCredentialsNonExpired() { 
 return true; 
 } 
​ 
 @Override 
 public boolean isEnabled() { 
 return true; 
 } 
} 

實(shí)體類role:

@Data 
public class Role implements Serializable { 
 private Integer id; 
​ 
 private String role; 
​ 
 private Date createdDT; 
​ 
 private Integer userId; 
} 

mapper:

@Mapper 
public interface UserMapper{ 
 User selectOneByName(User user); 
}

service:

public interface UserService{ 
 User selectOneByName(User user) throws ServiceException; 
}

serviceImpl:

@Service 
public class UserServiceImpl implements UserService { 
 @Autowired 
 private UserMapper mapper; 
​ 
 @Override 
 public User selectOneByName(User user) throws ServiceException { 
 return mapper.selectOneByName(user); 
 } 
}

mapper.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.pzh.hyh.demo.mapper.UserMapper"><!--  mapper相對路徑--> 
 <resultMap id="BaseResultMap" type="com.pzh.hyh.demo.model.User"><!--  model相對路徑--> 
 <result column="Id" jdbcType="INTEGER" property="id"/> 
 <result column="UserName" jdbcType="VARCHAR" property="userName"/> 
 <result column="CreatedDT" jdbcType="TIMESTAMP" propert="createdDT"/> 
 <result column="Age" jdbcType="INTEGER" property="age"/> 
 <result column="Gender" jdbcType="INTEGER" property="gender"/> 
 <result column="Password" jdbcType="VARCHAR" property="passWord"/> 
 </resultMap> 
​ 
 <sql id="Base_Column_List"> 
 Id, UserName, CreatedDT, Age, Gender,Password 
 </sql> 
  
 <select id="selectOneByName" parameterType="com.pzh.hyh.demo.model.User" resultMap="BaseResultMap"><!--  model相對路徑--> 
 SELECT u.*,r.role FROM `user` u LEFT JOIN role r on u.Id = r.UserId 
 where u.UserName = #{userName,jdbcType=VARCHAR} 
 </select> 
​ 
</mapper> 

config:

首先實(shí)現(xiàn)UserDetailsService類。自定義獲取用戶信息和角色信息。

@Component 
public class CustomUserDetailsService implements UserDetailsService { 
 @Autowired 
 private UserService userService; 
​ 
 @Autowired 
 private HttpServletRequest request; 
​ 
 @Override 
 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 
 // 通過用戶名從數(shù)據(jù)庫獲取用戶信息 
 User user = userService.selectOneByName(new User(){ 
 { 
 setUserName(username); 
 } 
 }); 
 if (user == null) { 
 throw new UsernameNotFoundException("用戶不存在"); 
 } 
​ 
 HttpSession session = request.getSession(); 
 session.setAttribute(session.getId(),user); 
​ 
 // 得到用戶角色 
 String role = user.getRole(); 
​ 
 // 角色集合 
 List<GrantedAuthority> authorities = new ArrayList<>(); 
 // 角色必須以`ROLE_`開頭,數(shù)據(jù)庫中沒有,則在這里加 
 authorities.add(new SimpleGrantedAuthority("ROLE_" + role)); 
​ 
 return new User( 
 user.getUsername(), 
 user.getPassword(), 
 authorities 
 ); 
 } 
}

自定義錯誤提示

@Component 
public class MyAccessDeniedHandler implements AccessDeniedHandler { 
 @Override 
 public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { 
 response.setCharacterEncoding("UTF-8"); 
 response.setContentType("application/json"); 
 response.getWriter().println("{'code':'403','message':'沒有訪問權(quán)限'}"); 
 response.getWriter().flush(); 
 } 
}

終于來到security的配置了

@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled = true) 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 
 @Autowired 
 private CustomUserDetailsService userDatailService; 
​ 
 @Autowired 
 private MyAccessDeniedHandler accessDeniedHandler; 
​ 
 @Bean 
 public PasswordEncoder passwordEncoder(){ 
 return new BCryptPasswordEncoder(); 
 } 
​ 
 @Override 
 protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
 auth 
 .userDetailsService(userDatailService) 
 .passwordEncoder(passwordEncoder()); 
 } 
​ 
​ 
 @Override 
 protected void configure(HttpSecurity http) throws Exception { 
 http 
 .headers().frameOptions().disable() 
 .and() 
 .authorizeRequests() 
 .antMatchers("不限制訪問的路徑,如:'/user/*'").permitAll() 
 .antMatchers("用戶擁有規(guī)定角色才允許訪問的路徑,如:'/user/delte'").hasRole("admin") 
 .antMatchers("規(guī)定ip才允許訪問的路徑,如:'/*'").hasIpAddress("192.168.1.1/24"); 
 .anyRequest().authenticated() // 所有請求都需要驗(yàn)證 
 .and() 
 // 跳轉(zhuǎn)自定義成功頁 
 .formLogin().defaultSuccessUrl("/html/index.html") 
 .and() 
 .exceptionHandling() 
 //用戶無權(quán)限訪問鏈接,給出友好提示 
 .accessDeniedHandler(accessDeniedHandler) 
 .and() 
 .csrf().disable();// post請求要關(guān)閉csrf驗(yàn)證,不然訪問報(bào)錯;實(shí)際開發(fā)中要開啟。 
 } 
}

至此,springsecurity的角色權(quán)限管理就完成了,如果想要實(shí)現(xiàn)方法級的角色權(quán)限限制,可以在方法前加入 @PreAuthorize("hasRole('角色')")注解,多個(gè)角色可以使用hasAnyRole(),就可以限制擁有規(guī)定角色權(quán)限的用戶才能訪問了。

 @PreAuthorize("hasRole('admin')") 
 @RequestMapping(value = "/delete") 
 public CommonResult delete(@RequestBody int id) { 
   int i = userService.delete(new User() { 
   { 
    setId(id); 
   } 
   }); 
   return i > 0 ? processSuccess("刪除成功") : processFailure("刪除失敗"); 
 }

到此這篇關(guān)于springsecurity輕松實(shí)現(xiàn)角色權(quán)限的示例代碼的文章就介紹到這了,更多相關(guān)springsecurity 角色權(quán)限內(nèi)容請搜索億速云以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持億速云!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI