十年架构师分享:基于SpringSecurity实现的基本认证及OAuth2

实现安全机制

本节将介绍基于Spring Security实现的基本认证及OAuth2。

实现基本认证

如果Spring Security位于类路径上,则所有HTTP端点上默认使用基本认证,这样就能使Web应用程序得到一定的安全保障。最为快捷的方式是在依赖中添加Spring Boot Security Starter。

//依赖关系
dependencies {
//该依赖用于编译阶段
compile('org.springf ramework . boot : spring-boot-starter-security')

如果要向Web应用程序添加方法级别的安全保障,还可以在Spring Boot应用里面添加@
Ena-bleGlobalMethodSecurity注解来实现,如下面的例子所示。

@EnableGlobalMe thodsecurity
@SpringBootApplication
public class Application {
public static void main (String[] args) {
SpringApplication. run (Application.class, args) ;

需要注意的是,@
EnableGlobalMethodSecurity 可以配置多个参数:

prePostEnabled:决定Spring Security的前注解是否可用@PreAuthorize、@PostAuthorize 等;

secureEnabled:决定Spring Security的保障注解@Secured是否可用;

jsr250Enabled :决定JSR-250注解@RolesAllowed等是否可用。

配置方式分别如下。

@EnableGlobalMethodSecurity (securedEnabled = true)
public class MethodSecuri tyConfig {
// ...
@EnableGlobalMethodSecurity (jsr250Enabled = true)
public class MethodSecurityConfig {
//...
@EnableGlobalMe thodsecurity (prePostEnabled = true)
public class MethodSecurityConfig {
/...
}

在同一个应用程序中,可以启用多个类型的注解,但是对于行为类的接口或类只应该设置一个注解。如果将2个注解同时应用于某- -特定方法, 则只有其中-一个被应用。

1. @Secured

此注解是用来定义业务方法的安全配置属性的列表。您可以在需要安全角色1权限等的方法上指定@Secured,并且只有那些角色1权限的用户才可以调用该方法。如果有人不具备要求的角色1权限但试图调用此方法,将会抛出AccessDenied 异常。

@Secured源于Spring 之前的版本,它有一个局限就是不支持Spring EL表达式。可以看看下面的例子。

如果你想指定AND (和)这个条件,即deleteUser方法只能被同时拥有ADMIN & DBA,但是仅仅通过使用@Secured注解是无法实现的。

但是你可以使用Spring新的注解@PreAuthorize/@PostAuthorize (支持Spring EL),使实现上面的功能成为可能,而且无限制。

@PreAuthori ze/@PostAuthorize

Spring的@PreAuthorize/@PostAuthorize 注解更适合方法级的安全,也支持Spring EL表达式

语言,提供了基于表达式的访问控制。

●@PreAuthorize 注解:适合进入方法前的权限验证,@PreAuthorize 可以将登录用户的角色1权

限参数传到方法中。

●@PostAuthorize注解:使用并不多,在方法执行后再进行权限验证。

以下是-一个使用了@PreAuthorize 注解的例子。

@PreAuthorize ("hasAuthority('ROLE ADMIN')") // 指定角色权限才能操作方法
@GetMapping(value = "delete/ {id}")
public ModelAndView delete (@PathVariable ("id") Long i
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值