Spring Security5 学习4 - 授权

Spring Security5(4)授权

在 Spring Security 中,一般有两种授权方式,分别是

  • hasAuthoriry
  • hasRole

一个是指明URL需要特定的权限才能访问,一个是指明URL需要特定的用户才能访问。两者都可以用于权限的限定,区别是粒度的大小。

我们来看下面的例子。

首先,使用 idea 创建一个 spring boot 工程,勾选下列功能:

  • spring boot devtool
  • lombok
  • thymeleaf
  • spring security

创建 Controller

package com.example.spring.security5.demo;

import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@AllArgsConstructor
@RequestMapping("/employee")
public class EmployeeController {
   

    @GetMapping()
    public String findAll() {
   
        return "list";
    }

    @DeleteMapping("/{id}")
    public Long delete(@PathVariable Long id) {
   
        return id;
    }
}

然后创建一个配置文件,用来配置安全选项:

package com.example.spring.security5.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
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.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
   
    @Configuration
    public static class UserSecurityConfig extends WebSecurityConfigurerAdapter {
   
        @Override
        protected void configure(HttpSecurity http) throws<
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值