中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

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

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

springsecurity輕松實現角色權限的示例代碼

發布時間:2020-09-03 02:51:57 來源:腳本之家 閱讀:214 作者:怡蘅 欄目:編程語言

問題:

如何在springboot項目中使用springsecurity去實現角色權限管理呢?本文將盡可能簡單的一步步實現對接口的角色權限管理。

項目框架:

springsecurity輕松實現角色權限的示例代碼

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:

實體類User要實現springsecurity的基本接口UserDetails,UserDetails里繼承了Serializable,不用擔心序列化

@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; 
 } 
} 

實體類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:

首先實現UserDetailsService類。自定義獲取用戶信息和角色信息。

@Component 
public class CustomUserDetailsService implements UserDetailsService { 
 @Autowired 
 private UserService userService; 
​ 
 @Autowired 
 private HttpServletRequest request; 
​ 
 @Override 
 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 
 // 通過用戶名從數據庫獲取用戶信息 
 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_`開頭,數據庫中沒有,則在這里加 
 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':'沒有訪問權限'}"); 
 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("用戶擁有規定角色才允許訪問的路徑,如:'/user/delte'").hasRole("admin") 
 .antMatchers("規定ip才允許訪問的路徑,如:'/*'").hasIpAddress("192.168.1.1/24"); 
 .anyRequest().authenticated() // 所有請求都需要驗證 
 .and() 
 // 跳轉自定義成功頁 
 .formLogin().defaultSuccessUrl("/html/index.html") 
 .and() 
 .exceptionHandling() 
 //用戶無權限訪問鏈接,給出友好提示 
 .accessDeniedHandler(accessDeniedHandler) 
 .and() 
 .csrf().disable();// post請求要關閉csrf驗證,不然訪問報錯;實際開發中要開啟。 
 } 
}

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

 @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("刪除失敗"); 
 }

到此這篇關于springsecurity輕松實現角色權限的示例代碼的文章就介紹到這了,更多相關springsecurity 角色權限內容請搜索億速云以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持億速云!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

京山县| 同心县| 合川市| 洞口县| 博白县| 钟祥市| 左云县| 新绛县| 安康市| 思茅市| 贵溪市| 乡宁县| 吉首市| 巴彦县| 浠水县| 西乌珠穆沁旗| 岳普湖县| 惠来县| 精河县| 仙居县| 新乡县| 梁山县| 清远市| 酉阳| 临漳县| 东丰县| 阳高县| 陵川县| 教育| 巩留县| 桐柏县| 杭州市| 阿拉尔市| 牟定县| 上犹县| 香河县| 易门县| 颍上县| 汽车| 夏邑县| 宕昌县|