配置资源授权,默认是不需要授权。现在访问/say
是要有权限aa的
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/login/page")
.loginProcessingUrl("/login")
.and()
.authorizeRequests()
.antMatchers("/login/page").permitAll()
.anyRequest().authenticated()
//以上是认证的配置,以下是授权的配置
//拥有 aa 权限的用户,可以访问任意请求方式的 /say
.antMatchers("/say").hasAuthority("aa")
;
http.csrf().disable();
}
}
给devin用户的权限是ADMIN,并么有aa权限,因此/say
是没有权限访问的。
@Slf4j
@Component
public class CustomUserDetailService implements UserDetailsService {
@Autowired
public PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//模拟用户可以在数据库查询到
if ("devin".equals(username)) {
return new User("devin", passwordEncoder.encode("1234"),
//这个给的权限标识符为 ADMIN
AuthorityUtils.commaSeparatedStringToAuthorityList("ADMIN"));
}
throw new UsernameNotFoundException("用户名输入错误");
}
}
添加/say
@RestController
public class HelloController {
@RequestMapping("hello")
public String hell() {
return "Hello World";
}
@RequestMapping("say")
public String say() {
return "say";
}
}
登录访问:http://localhost:8080/hello
访问:http://localhost:8080/say 没有权限
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/login/page")
.loginProcessingUrl("/login")
.and()
.authorizeRequests()
.antMatchers("/login/page").permitAll()
//拥有 aa 权限的用户,可以访问任意请求方式的 /say
.antMatchers("/say").hasAuthority("aa") //配置权限
.antMatchers("/run").hasRole("ADMIN") //配置角色
.anyRequest().authenticated()
;
http.csrf().disable();
}
}
@Slf4j
@Component
public class CustomUserDetailService implements UserDetailsService {
@Autowired
public PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//模拟用户可以在数据库查询到
if ("devin".equals(username)) {
return new User("devin", passwordEncoder.encode("1234"),
//这个给的权限标识符为 aa, 角色为ROLE_ADMIN(这里要注意加上前缀ROLE_标识是角色)
AuthorityUtils.commaSeparatedStringToAuthorityList("aa, ROLE_ADMIN"));
}
throw new UsernameNotFoundException("用户名输入错误");
}
}
登录访问:http://localhost:8080/hello
登录访问:http://localhost:8080/say
登录访问:http://localhost:8080/run
可参考的权限表达式