這篇文章給大家分享的是有關spring中如何給指定的用戶指定角色的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
一、如何給指定的用戶指定角色
(1)通過AuthenticationManagerBuilder的roles()方法,就可以指定角色。
// 通過AuthenticationManagerBuilder的roles()方法,就可以指定角色。
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("000000"))
.roles("admin");
auth.inMemoryAuthentication()
.withUser("user")
.password(passwordEncoder().encode("000000"))
.roles("normal");(2)如何開啟方法級別安全控制
在@Configuration注解的類上再添加@EnableGlobalMethodSecurity
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//會攔截注解了@PreAuthrize注解的配置
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {(3)如何配置方法級別的權限控制
使用注解@PreAuthorize("hasAnyAuthority('admin')")即可指定訪問級別的角色
@RestController
@RequestMapping("/hello")
public class HelloController {
@GetMapping
public String hello() {
return "hello, spring security! ";
}
@GetMapping("/helloAdmin")
@PreAuthorize("hasAnyRole('admin')")
public String helloAdmin() {
return "hello, admin! ";
}
@GetMapping("/helloUser")
@PreAuthorize("hasAnyRole('normal','admin')")
public String helloUser() {
return "hello, user! ";
}
}感謝各位的閱讀!關于“spring中如何給指定的用戶指定角色”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。