SpringCloud-Secruity入门开发(授权的两种方式)

本篇主要简单介绍一下secruity的两种授权方式:

一种是基于url的授权,也称web授权。

另一种是基于方法的授权。

web授权(根据url进行授权)

在Secruity的配置文件中有如下的代码 

package com.nlx.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class MyWebSecruityConfig extends WebSecurityConfigurerAdapter{

	@Override
	protected void configure(HttpSecurity http) throws Exception {
			http
				// 关闭csrf
				.csrf().disable()
				.authorizeRequests()
				// 添加权限
				.antMatchers("/insert").hasAuthority("p1")
				.antMatchers("/delete").hasAuthority("p2")
				// 其他不匹配上面的验证规则的请求都需要被验证
				.anyRequest().authenticated()
				// permitAll()无条件允许访问
				// 开启session管理
				// .and().sessionManagement()
				.and().logout()
				// 基本认证
				// .and().httpBasic();
				// 表单认证
				.and().formLogin();
	}
	 
	@Bean
	PasswordEncoder passwordEncoder() {
		//secriuty默认对密码进行了BCrypt加密
		return new BCryptPasswordEncoder();
	}
}

在configure(HttpSecurity http)方法里面.antMatchers("/insert").hasAuthority("p1")即是授权。授权条件越是具体的要放在越上面。对不同的url可以进行不同的授权。但是一般情况下我们都不使用这种方式进行授权。项目越大,url越多,这种授权越难以管理。

 

基于方法的授权(prePostEnabled)

基于方法的授权在实际开发中使用比较广泛
具体实现如下:
1.在secruity的配置类上加上注解@EnableGlobalMethodSecurity(prePostEnabled = true)这里的注解括号里面的额内容表示启用springsecruity前/后注解

 2.在需要权限的方法或者类上添加权限注解@PreAuthorize("hasAuthority('p1')")

package com.nlx.controller;

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

@RestController
@PreAuthorize("hasAuthority('p1')")
public class TestController {

	@RequestMapping("/insert")
	public String testInsert() {
		return "Insert Success";
	}
	
	@RequestMapping("/delete")
	public String testDelete() {
		return "Delete Success";
	}
	
	@RequestMapping("/query")
	public String testQuery() {
		return "Query Success";
	}
	
	@RequestMapping("/update")
	public String testUpdate() {
		return "Update Success";
	}
}

将@PreAuthorize("hasAuthority('p1')")加在类上相当于给这个类的所有方法都加了这个注解,只有拥有p1权限才能执行该类下的方法。
如果将注解加在方法上则只对该方法有效。

 

关于授权注解:

@PreAuthorize("hasAuthority('p1')")
表示具备某种权限才能进入
@PreAuthorize("hasRole('ROLE_insert')")
表示属于某种角色才能进入
@PostAuthorize 该注解使用不多,在方法执行后再进行权限验证。 适合验证带有返回值的权限。

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值