Spring?Security權(quán)限注解啟動及邏輯處理使用示例
啟用注解
@EnableGlobalMethodSecurity(prePostEnabled = true)
正常啟用開啟那個(gè)注解就行,下面放下我的配置
package com.fedtech.sys.provider.config.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import javax.annotation.Resource;
/**
* 資源配置
*
* @author <a href = "mailto:njpkhuan@gmail.com" > huan </a >
* @date 2021/1/13
* @since 1.0.0
*/
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Resource
RedisConnectionFactory redisConnectionFactory;
@Resource
private TokenStore tokenStore;
@Bean
public TokenStore redisTokenStore() {
return new RedisTokenStore(redisConnectionFactory);
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.tokenStore(tokenStore);
}
}角色
/**
* 查詢單個(gè)用戶
*
* @param query {@link UserQuery}
*
* @return com.fedtech.common.util.result.R<com.fedtech.sys.provider.view.UserView>
*
* @author <a href = "mailto:njpkhuan@gmail.com" > huan </a >
* @date 2021/2/20
* @since 1.0.0
*/
@GetMapping("select")
@PreAuthorize("hasAuthority('admin')")
public R<UserView> selectUser(UserQuery query) {
UserDto dto = userService.selectUser(query);
return R.successWithData(userMapper.dto2View(dto));
}權(quán)限
默認(rèn)的是DenyAllPermissionEvaluator,所有權(quán)限都拒絕,所以要自定義
自定義處理邏輯
我是把權(quán)限放到了自定義的userDetails里面
package com.fedtech.common.model;
import cn.hutool.core.collection.CollUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;
/**
* 該類返回的是安全的,能夠提供給用戶看到的信息,即脫敏后的信息
*
* @author <a href = "mailto:njpkhuan@gmail.com" > huan </a >
* @date 2021/1/9
* @since 1.0.0
*/
@Data
@Slf4j
public class SecurityUser implements UserDetails {
private static final long serialVersionUID = 8689435103879098852L;
/**
* 鹽
*/
private String salt;
/**
* 用戶token
*/
private String token;
/**
* 用戶狀態(tài)
*/
private String status;
/**
* 用戶密碼
*/
private String password;
/**
* 用戶登錄賬號
*/
private String loginName;
private Long userId;
/**
* 用戶角色
*
* @date 2021/1/10
* @since 1.0.0
*/
private List<UserRole> roleList;
/**
* 權(quán)限列表
*
* @date 2021/1/11
* @since 1.0.0
*/
private List<UserPermission> permissionList;
/**
* 客戶端用戶
*
* @param client 客戶端
*
* @author <a href = "mailto:njpkhuan@gmail.com" > huan </a >
* @date 2021/1/13
* @since 1.0.0
*/
public SecurityUser(OauthClientDetails client) {
if (client != null) {
password = client.getClientSecret();
loginName = client.getClientId();
String authorities = client.getAuthorities();
StringTokenizer stringTokenizer = new StringTokenizer(authorities, ", ");
roleList = new ArrayList<>();
if (stringTokenizer.hasMoreTokens()) {
UserRole userRole = new UserRole();
userRole.setCode(stringTokenizer.nextToken());
roleList.add(userRole);
}
}
}
/**
* 普通用戶
*
* @param user 用戶
* @param roleList 角色
* @param permissionList 權(quán)限
*
* @author <a href = "mailto:njpkhuan@gmail.com" > huan </a >
* @date 2021/1/13
* @since 1.0.0
*/
public SecurityUser(User user, List<UserRole> roleList, List<UserPermission> permissionList) {
if (user != null) {
salt = user.getSalt();
token = user.getToken();
status = user.getStatus();
password = user.getPassword();
loginName = user.getLoginName();
userId = user.getId();
this.roleList = roleList;
this.permissionList = permissionList;
}
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
if (!CollUtil.isEmpty(roleList)) {
for (UserRole role : roleList) {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getCode());
authorities.add(authority);
}
}
log.debug("獲取到的用戶權(quán)限:{}", authorities);
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return loginName;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}package com.fedtech.common.config;
import cn.hutool.core.collection.CollUtil;
import com.fedtech.common.model.SecurityUser;
import com.fedtech.common.model.UserPermission;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import java.io.Serializable;
import java.util.List;
/**
* 自定義權(quán)限處理
*
* @author <a href="mailto:njpkhuan@gmail.com" rel="external nofollow" >huan</a>
* @version 1.0.0
* @date 2021/2/26
*/
@Slf4j
@Configuration
public class MyPermissionEvaluator implements PermissionEvaluator {
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
SecurityUser principal = (SecurityUser) authentication.getPrincipal();
List<UserPermission> permissionList = principal.getPermissionList();
if (CollUtil.isNotEmpty(permissionList)) {
return permissionList.stream().anyMatch(x -> StringUtils.equals(x.getUrl(), (CharSequence) targetDomainObject) &&
StringUtils.equals(x.getCode(), (CharSequence) permission));
}
return false;
}
@Override
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
return false;
}
}使用
/**
* 查詢單個(gè)用戶
*
* @param query {@link UserQuery}
*
* @return com.fedtech.common.util.result.R<com.fedtech.sys.provider.view.UserView>
*
* @author <a href = "mailto:njpkhuan@gmail.com" > huan </a >
* @date 2021/2/20
* @since 1.0.0
*/
@GetMapping("select")
@PreAuthorize("hasPermission('/sys/user/insert','userInsert')")
public R<UserView> selectUser(UserQuery query) {
UserDto dto = userService.selectUser(query);
return R.successWithData(userMapper.dto2View(dto));
}以上就是Spring Security權(quán)限注解啟動及邏輯處理使用示例的詳細(xì)內(nèi)容,更多關(guān)于Spring Security權(quán)限注解的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
spring mvc中的@PathVariable動態(tài)參數(shù)詳解
這篇文章主要介紹了spring mvc中的@PathVariable動態(tài)參數(shù)詳解,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
Java優(yōu)先隊(duì)列?priority?queue
本文主要介紹了Java優(yōu)先隊(duì)列?priority?queue,優(yōu)先隊(duì)列是一種特殊的數(shù)據(jù)結(jié)構(gòu)隊(duì)列中每一個(gè)元素都被分配到一個(gè)優(yōu)先權(quán)值,出隊(duì)順序按照優(yōu)先權(quán)值來劃分。一般有兩種出隊(duì)順序高優(yōu)先權(quán)出隊(duì)或低優(yōu)先權(quán)出隊(duì),想了解具體內(nèi)容的小伙伴可以參考下文內(nèi)容,希望對你有所幫助2021-12-12
詳解如何在項(xiàng)目中應(yīng)用SpringSecurity權(quán)限控制
本文主要介紹了如何在項(xiàng)目中應(yīng)用SpringSecurity權(quán)限控制,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
Java String類簡單用法實(shí)戰(zhàn)示例【字符串輸出、比較】
這篇文章主要介紹了Java String類簡單用法,結(jié)合具體實(shí)例形式分析了Java使用String類實(shí)現(xiàn)字符串的輸出和比較功能相關(guān)操作技巧,需要的朋友可以參考下2019-07-07
java實(shí)現(xiàn)稀疏矩陣的壓縮與解壓的方法
這篇文章主要介紹了java實(shí)現(xiàn)稀疏矩陣的壓縮與解壓 ,把該稀疏矩陣壓縮以三元組形式表示并以文件形式保存,再寫另一個(gè)程序讀取文件中的信息把壓縮后的三元組還原成原來的稀疏矩陣,需要的朋友可以參考下2022-03-03
Jackson處理Optional時(shí)遇到問題的解決與分析
Optional是Java實(shí)現(xiàn)函數(shù)式編程的強(qiáng)勁一步,并且?guī)椭诜妒街袑?shí)現(xiàn),但是Optional的意義顯然不止于此,下面這篇文章主要給大家介紹了關(guān)于Jackson處理Optional時(shí)遇到問題的解決與分析的相關(guān)資料,需要的朋友可以參考下2022-02-02
java實(shí)現(xiàn)頁面多查詢條件必選的統(tǒng)一處理思路
這篇文章主要為大家介紹了java實(shí)現(xiàn)頁面多查詢條件必選的統(tǒng)一處理思路詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
FeignClient設(shè)置動態(tài)url方式
文章介紹了如何在Spring Cloud環(huán)境下使用FeignClient實(shí)現(xiàn)負(fù)載均衡,通過配置Nacos和FeignClient屬性,可以實(shí)現(xiàn)服務(wù)間的負(fù)載均衡調(diào)用2024-11-11

