Security之注解篇

1、功能实现

1.开启基于方法的安全认证机制
2.自定义实现细粒度的权限控制

2、security03 子工程

学习本篇前最好对 入门篇 有所了解
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.yzm</groupId>
        <artifactId>security</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath> <!-- lookup parent from repository -->
    </parent>

    <artifactId>security03</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>security03</name>
    <description>Demo project for Spring Boot</description>

    <dependencies>
        <dependency>
            <groupId>com.yzm</groupId>
            <artifactId>common</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.192.128:3306/testdb?useUnicode=true&characterEncoding=utf8&useSSL=false&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
    username: root
    password: 1234
  # 启动时提示需要这个,加上就好了
  main:
    allow-bean-definition-overriding: true

mybatis-plus:
  mapper-locations: classpath:/mapper/*Mapper.xml
  type-aliases-package: com.yzm.security03.entity
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3、自定义UserDetailsService 实现类

package com.yzm.security03.config;

import com.yzm.security03.entity.Role;
import com.yzm.security03.entity.User;
import com.yzm.security03.service.RoleService;
import com.yzm.security03.service.UserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义UserDetailsService,重写loadUserByUsername方法,查询数据库获取用户信息和权限信息
 * Spring Security进行用户认证时,需要根据用户的账号、密码、权限等信息进行认证,
 * 因此,需要根据查询到的用户信息封装成一个认证用户对象并交给Spring Security进行认证。
 * 查询用户信息并封装成认证用户对象的过程是在UserDetailsService接口的实现类(需要用户自己实现)中完成的
 */
@Service
public class SecUserDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;
    private final RoleService roleService;

    public SecUserDetailsServiceImpl(UserService userService, RoleService roleService) {
        this.userService = userService;
        this.roleService = roleService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.lambdaQuery().eq(User::getUsername, username).one();
        if (user == null) {
            throw new UsernameNotFoundException(String.format("用户'%s'不存在", username));
        }

        List<Integer> roleIds = Arrays.stream(user.getRIds().split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        List<Role> roleList = roleService.listByIds(roleIds);
        List<SimpleGrantedAuthority> authorities = roleList.stream()
                .map(Role::getRName)
                .distinct()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return new SecUserDetails(username, user.getPassword(), authorities, roleIds);
    }
}

由于我需要一些自定义的属性信息,默认org.springframework.security.core.userdetails.User满足不了需求,所以自定义了SecUserDetails 继承User,为后面使用细粒度权限作准备

package com.yzm.security03.config;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;

import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 自定义 安全用户模型
 * loadUserByUsername 的返回值是UserDetails,这是一个接口,
 * 可以使用它的子类org.springframework.security.core.userdetails.User
 * 也可以自定义一个,新增一些自定义的东西
 */
public class SecUserDetails extends User {

    private static final long serialVersionUID = 3033317408164827323L;

    // 自定义属性
    private List<Integer> roleIds;
    private Set<String> permissions;

    public SecUserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        this(username, password, true, true, true, true, authorities);
    }

    public SecUserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities, List<Integer> roleIds) {
        this(username, password, true, true, true, true, authorities);
        this.roleIds = roleIds;
    }

    public SecUserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities, Set<String> permissions) {
        this(username, password, true, true, true, true, authorities);
        this.permissions = permissions;
    }

    public SecUserDetails(
            String username,
            String password,
            boolean enabled,
            boolean accountNonExpired,
            boolean credentialsNonExpired,
            boolean accountNonLocked,
            Collection<? extends GrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    }

    public List<Integer> getRoleIds() {
        return roleIds;
    }

    public void setRoleIds(List<Integer> roleIds) {
        this.roleIds = roleIds;
    }

    public Set<String> getPermissions() {
        return permissions;
    }

    public void setPermissions(Set<String> permissions) {
        this.permissions = permissions;
    }
}

4、SecurityConfig 配置类

开启注解 @EnableGlobalMethodSecurity(prePostEnabled = true)

package com.yzm.security03.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;

@Slf4j
@Configuration
@EnableWebSecurity // 开启Security服务
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启全局注解
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserDetailsService userDetailsService;
    private final SecPermissionEvaluator permissionEvaluator;

    public SecurityConfig(@Qualifier("secUserDetailsServiceImpl") UserDetailsService userDetailsService, SecPermissionEvaluator permissionEvaluator) {
        this.userDetailsService = userDetailsService;
        this.permissionEvaluator = permissionEvaluator;
    }

    /**
     * 密码编码器
     * passwordEncoder.encode是用来加密的,passwordEncoder.matches是用来解密的
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置用户
     * 指定默认从哪里获取认证用户的信息,即指定一个UserDetailsService接口的实现类
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 从数据库读取用户、并使用密码编码器解密
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    //配置资源权限规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 关闭CSRF跨域
                .csrf().disable()

                // 登录
                .formLogin()
                .loginPage("/auth/login") //指定登录页的路径,默认/login
                .loginProcessingUrl("/login") //指定自定义form表单请求的路径(必须跟login.html中的form action=“url”一致)
                .defaultSuccessUrl("/home", true) // 登录成功后的跳转url地址
                .failureUrl("/auth/login?error") // 登录失败后的跳转url地址
                .permitAll()
                .and()

                .exceptionHandling()
                .accessDeniedPage("/401") // 拒接访问跳转页面
                .and()

                // 退出登录
                .logout().permitAll()
                .and()

                // 访问路径URL的授权策略,如注册、登录免登录认证等
                .authorizeRequests()
                .antMatchers("/", "/home", "/register", "/auth/login").permitAll() //指定url放行
                .anyRequest().authenticated() //其他任何请求都需要身份认证
                .and()
        ;
    }
}

5、注解使用

@PreAuthorize(“hasAuthority(‘ROLE_ADMIN’)”)
@PreAuthorize(“hasAnyRole(‘ADMIN’,‘USER’)”)

package com.yzm.security03.controller;


import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/admin")
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public class AdminController {

	@GetMapping
    public Object admin(@AuthenticationPrincipal UserDetails userDetails) {
        return userDetails;
    }

    @GetMapping("/select")
    public Object select() {
        return "Select";
    }

    @GetMapping("/create")
    public Object create() {
        return "Create";
    }

    @GetMapping("/update")
    public Object update() {
        return "Update";
    }

    @GetMapping("/delete")
    public Object delete() {
        return "Delete";
    }
}
package com.yzm.security03.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
@PreAuthorize("hasAnyRole('ADMIN','USER')")
public class UserController {

	@GetMapping
    public Object user(@AuthenticationPrincipal UserDetails userDetails) {
        return userDetails;
    }

   ...

    @GetMapping("/delete")
    public Object delete() {
        return "Delete";
    }
}

6、html 页面

参考上一篇 入门篇

7、测试注解

启动项目,登录yzm,访问 /user/** 接口
在这里插入图片描述
admin可以访问所有接口

8、细粒度权限控制@PreAuthorize(“hasPermission()”)

目前演示都是基于角色进行授权的,如果要角色role跟权限permission一起使用,就需要我们自定义了
SecPermissionEvaluator 实现 PermissionEvaluator 重写 hasPermission()

package com.yzm.security03.config;

import com.yzm.security03.entity.Permissions;
import com.yzm.security03.entity.Role;
import com.yzm.security03.service.PermissionsService;
import com.yzm.security03.service.RoleService;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 细粒度的权限控制
 */
@Slf4j
@Component
public class SecPermissionEvaluator implements PermissionEvaluator {

    private final RoleService roleService;
    private final PermissionsService permissionsService;

    public SecPermissionEvaluator(RoleService roleService, PermissionsService permissionsService) {
        this.roleService = roleService;
        this.permissionsService = permissionsService;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Object targetUrl, Object targetPermission) {
    	log.info("hasPermission 方法执行");
        // 获得loadUserByUsername()方法的结果
        SecUserDetails userDetails = (SecUserDetails) authentication.getPrincipal();
        // 获得loadUserByUsername()中注入的角色
        //Collection<GrantedAuthority> authorities = userDetails.getAuthorities();
        // 拿到SecUserDetails 自定义的roleIds值
        List<Integer> roleIds = userDetails.getRoleIds();

        // 查询角色对应的权限id信息
        List<Role> roles = roleService.listByIds(roleIds);
        Set<Integer> permIds = new HashSet<>();
        roles.forEach(role -> {
            Set<Integer> collect = Arrays.stream(role.getPIds().split(","))
                    .map(Integer::parseInt).collect(Collectors.toSet());
            permIds.addAll(collect);
        });

        List<Permissions> perms = permissionsService.listByIds(permIds);
        String permission = (String) targetUrl + ":" + (String) targetPermission;
        for (Permissions perm : perms) {
            // 如果访问的Url和权限用户符合的话,返回true
            if (permission.equals(perm.getPName())) {
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }

}

SecurityConfig中把自定义SecPermissionEvaluator交给Security管理

    /**
     * 注入自定义PermissionEvaluator
     */
    @Bean
    public DefaultWebSecurityExpressionHandler webSecurityExpressionHandler() {
        DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
        handler.setPermissionEvaluator(permissionEvaluator);
        return handler;
    }

使用@PreAuthorize(“hasPermission(’’,’’)”)

package com.yzm.security03.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/admin")
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public class AdminController {

    @GetMapping("/select")
    @PreAuthorize("hasPermission('admin','select')")
    public Object select() {
        return "Select";
    }

    @GetMapping("/create")
    public Object create() {
        return "Create";
    }

    @GetMapping("/update")
    public Object update() {
        return "Update";
    }

    @GetMapping("/delete")
    @PreAuthorize("hasPermission('admin','delete')")
    public Object delete() {
        return "Delete";
    }
}

package com.yzm.security03.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
@PreAuthorize("hasAnyRole('ADMIN','USER')")
public class UserController {

    @GetMapping("/select")
    @PreAuthorize("hasPermission('user','select')")
    public Object select() {
        return "Select";
    }

    @GetMapping("/create")
    public Object create() {
        return "Create";
    }

    @GetMapping("/update")
    public Object update() {
        return "Update";
    }

    @GetMapping("/delete")
    @PreAuthorize("hasPermission('user','delete')")
    public Object delete() {
        return "Delete";
    }
}

9、测试细粒度权限

登录yzm,/user/select、/user/delete时会打印日志,并且由于/user/delete没有权限,拒绝访问
在这里插入图片描述
在这里插入图片描述

相关链接

首页
上一篇:入门篇
下一篇:记住我篇

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
常用的security注解包括: 1. @Secured: 用于在方法上指定访问权限的注解。需要在启动类上使用@EnableGlobalMethodSecurity(securedEnabled = true)开启支持。 2. @PreAuthorize: 用于在方法执行前进行权限验证的注解。可以在注解中指定访问权限表达式,只有满足表达式条件的用户才能执行方法。需要在启动类上使用@EnableGlobalMethodSecurity(prePostEnabled = true)开启支持。 3. @PostAuthorize: 用于在方法执行后进行权限验证的注解。可以在注解中指定访问权限表达式,只有满足表达式条件的用户才能获取方法返回结果。需要在启动类上使用@EnableGlobalMethodSecurity(prePostEnabled = true)开启支持。 4. @RolesAllowed: 用于在方法上指定允许访问的角色的注解。需要在启动类上使用@EnableGlobalMethodSecurity(jsr250Enabled = true)开启支持。 5. @PostFilter: 用于在方法执行后对返回结果进行过滤的注解。可以在注解中指定过滤条件,只有满足条件的数据才会被返回。需要在启动类上使用@EnableGlobalMethodSecurity(prePostEnabled = true)开启支持。 总结:常用的security注解包括@Secured、@PreAuthorize、@PostAuthorize、@RolesAllowed和@PostFilter。在使用注解之前,需要在启动类上开启相应的注解支持。123 #### 引用[.reference_title] - *1* *2* *3* [Spring——Security安全框架之注解使用](https://blog.csdn.net/qq_38322527/article/details/123085675)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值