0
点赞
收藏
分享

微信扫一扫

springSecurity基于注解的访问控制

彪悍的鼹鼠 2022-01-08 阅读 47

在 Spring Security 中提供了一些访问控制的注解。这些注解都是
默认是都不可用的,需要通过@EnableGlobalMethodSecurity 进行开启
后使用。
如果设置的条件允许,程序正常执行。如果不允许会报 500

这些注解可以写到 Service 接口或方法上上也可以写到 Controller
或 Controller 的方法上。通常情况下都是写在控制器方法上的,控制
接口 URL 是否允许被访问。

@Secured
@Secured 是专门用于判断是否具有角色的。能写在方法或类上。
参数要以 ROLE_开头。在这里插入代码片

@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true)
public class MyApp {
public static void main(String [] args){
SpringApplication.run(MyApp.class,args);
}
}
@Secured("abc")
@RequestMapping("/toMain")
public String toMain(){
return
```‘

```java
protected void configure(HttpSecurity http) throws Exception {
// 表单认证
http.formLogin()
.loginProcessingUrl("/login") //当发现/login 时认为是登录,需要执UserDetailsServiceImpl
.successForwardUrl("/toMain") //此处是 post 请求
.loginPage("/login.html");
// url 拦截
http.authorizeRequests()
.antMatchers("/login.html").permitAll() //login.html 不需要被认证
.anyRequest().authenticated();//所有的请求都必须被认证。必须登录后才
能访问。
//关闭 csrf 防护
http.csrf().disable();
}
举报

相关推荐

0 条评论