spring security(一)
本文是個人向的
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/common/**").permitAll()
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest()
.authenticated()
.and()
.formLogin()
.and()
.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("{noop}123")
.roles("USER");
}
}
這是基本配置,建立了一個使用者名稱是user,密碼是123的使用者,{noop}表示不用加密,另外在這種配置裡面角色不需要加ROLE字首。
@RestController
@RequestMapping("user")
public class UserController {
@GetMapping
public String query(){
return "i am user";
}
}
@RestController
@RequestMapping("admin")
public class AdminController {
@GetMapping
public String query(){
return "i am admin";
}
}
@RestController
@RequestMapping("common")
public class CommonController {
@GetMapping
public String query(){
return "i am common";
}
}
這是三個訪問路徑,啟動之後可以發現common開頭的無需登入即可訪問,而使用者只有user這個許可權,只能訪問user開頭的。
下面簡化一下配置,使用許可權註解來使用。
@RestController
@RequestMapping("user")
public class UserController {
@GetMapping
@PreAuthorize("hasRole('USER')")
public String query(){
return "i am user";
}
}
@PreAuthorize 用於判斷使用者是否有指定許可權,沒有就不能訪問
同時配置類加上
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)註解,分別表示開啟 Security 服務、開啟全域性 Securtiy 註解,這樣操作之後效果同上。
相關文章
- Spring Security(一):整合JWTSpringJWT
- Spring Security(一)入門Spring
- Java安全框架(一)Spring SecurityJava框架Spring
- Spring SecuritySpring
- Spring Boot —— Spring SecuritySpring Boot
- Spring Security原始碼分析八:Spring Security 退出Spring原始碼
- Spring Security原始碼分析九:Spring Security Session管理Spring原始碼Session
- Spring Boot整合Spring SecuritySpring Boot
- Spring Security(8)Spring
- Spring Security(6)Spring
- Spring Security(7)Spring
- Spring Security + JWTSpringJWT
- 初探Spring SecuritySpring
- Spring Security 上Spring
- Spring Security(二)Spring
- Spring Boot SecuritySpring Boot
- 如何從Spring Security 5遷移到Spring Security 6/Spring Boot 3Spring Boot
- Spring security(四)-spring boot +spring security簡訊認證+redis整合Spring BootRedis
- SpringBoot整合Spring SecuritySpring Boot
- [譯]Spring Security ArchitectureSpring
- Spring Security進階Spring
- Spring Security OAuth 2.0SpringOAuth
- Spring Security詳解Spring
- Spring Security系列教程之一簡介Spring
- Spring Security原始碼分析十一:Spring Security OAuth2整合JWTSpring原始碼OAuthJWT
- spring-boot 整合 spring-securitySpringboot
- Spring security (一)架構框架-Component、Service、Filter分析Spring架構框架Filter
- Spring Security系列之體系結構概述(一)Spring
- Spring Security 6.3 新功能Spring
- Spring Security 中的 BCryptPasswordEncoderSpring
- Spring Security OAuth 筆記SpringOAuth筆記
- Spring Security 入門篇Spring
- Spring security config httpSecurity tipsSpringHTTP
- Spring Security Oauth2SpringOAuth
- Spring Boot Security配置教程Spring Boot
- Spring Boot Security 詳解Spring Boot
- Spring Security 快速瞭解Spring
- Spring Security 快速入門Spring