授权的方式包括web授权(通过对url进行拦截)和方法授权(通过对方法进行拦截)
上一篇文章就是web授权的方式,下面我们来实现通过方法进行授权
我们通过上面一篇文章的程序进行改造
config
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
//因为使用了方法授权,所以就不需要在通过web的方式进行授权了
// .antMatchers("/r/r1").hasAnyAuthority("p1")
// .antMatchers("/r/r2").hasAnyAuthority("p2")
.antMatchers("/r/**","/login-success").authenticated() //需要认证才能访问
.anyRequest().permitAll()//其它请求都允许 注意位置(放在最前面所有请求都会被放行)
.and()
.formLogin() //允许基于Form表单登录验证
.loginPage("/login-page")//自定义登录界面
.loginProcessingUrl("/login")//对应表单提交时的action="login"
.successForwardUrl("/login-success")//自定义登录成功的页面地址(可以不写)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login-page?logout");
}
}
controller
@RequestMapping(value = "/r/r1" , produces = {"text/plain; charset=UTF-8"})
@PreAuthorize("hasAuthority(‘p1‘)")//拥有p1权限
//@PreAuthorize("hasAnyAuthority(‘p1‘,‘p2‘)")//拥有p1,p2权限可以访问
public String r1(){
return getUsername()+"访问资源r1";
}
@RequestMapping(value = "/r/r2" , produces = {"text/plain; charset=UTF-8"})
@PreAuthorize("hasAuthority(‘p3‘)")
public String r2(){
return getUsername()+"访问资源r2";
}
登录成功后可以访问r1方法,不能访问r2方法,因为用户没有p3权限。
原文:https://www.cnblogs.com/lanxinren/p/14743821.html