@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
// 指定密碼的加密方式
@SuppressWarnings ( "deprecation" )
@Bean
PasswordEncoder passwordEncoder(){
// 不對密碼進行加密
return NoOpPasswordEncoder.getInstance();
}
// 配置用戶及其對應的角色
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser( "root" ).password( "123" ).roles( "DBA" )
.and()
.withUser( "admin" ).password( "123" ).roles( "ADMIN" )
.and()
.withUser( "hangge" ).password( "123" ).roles( "USER" );
}
// 配置角色繼承關係
@Bean
RoleHierarchy roleHierarchy() {
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
String hierarchy = "ROLE_DBA > ROLE_ADMIN > ROLE_USER" ;
roleHierarchy.setHierarchy(hierarchy);
return roleHierarchy;
}
// 配置 URL 訪問權限
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() // 開啓 HttpSecurity 配置
.antMatchers( "/db/**" ).hasRole( "DBA" ) // db/** 模式URL需DBA角色
.antMatchers( "/admin/**" ).hasRole( "ADMIN" ) // admin/** 模式URL需ADMIN角色
.antMatchers( "/user/**" ).hasRole( "USER" ) // user/** 模式URL需USER角色
.anyRequest().authenticated() // 用戶訪問其它URL都必須認證後訪問(登錄後訪問)
.and().formLogin().loginProcessingUrl( "/login" ).permitAll() // 開啓表單登錄並配置登錄接口
.and().csrf().disable(); // 關閉csrf
}
}
|