您好,登錄后才能下訂單哦!
要在Spring Security中配置基于角色的訪問(wèn)控制,您可以使用antMatchers()
方法和hasRole()
方法來(lái)定義URL模式和角色的對(duì)應(yīng)關(guān)系。
以下是一個(gè)簡(jiǎn)單的示例配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling()
.accessDeniedPage("/403");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("{noop}admin").roles("ADMIN")
.and()
.withUser("user").password("{noop}user").roles("USER");
}
}
在這個(gè)配置中,我們定義了兩個(gè)角色:“ADMIN”和“USER”,并為它們分別指定了訪問(wèn)的URL模式。管理員可以訪問(wèn)/admin/**
路徑,而普通用戶可以訪問(wèn)/user/**
路徑。任何其他URL都需要進(jìn)行身份驗(yàn)證。
請(qǐng)注意,在configure(AuthenticationManagerBuilder auth)
方法中,我們使用了inMemoryAuthentication()
方法來(lái)定義了兩個(gè)用戶,分別屬于兩種不同的角色。
這只是一個(gè)簡(jiǎn)單的示例配置,您可以根據(jù)自己的需求來(lái)定義更多的角色和對(duì)應(yīng)的訪問(wèn)控制規(guī)則。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。