spring secutity配置要点
WebSecurityConfig配置几大要素
UserDetailsService,密码编码器,安全拦截机制
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// super.configure(auth);
// }
/** * //定义用户信息服务
* @return
*/
@Bean
public UserDetailsService userDetailsService(){
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build());
manager.createUser(User.withUsername("lisi").password("456").authorities("p2").build());
return manager;
}
/**
* //密码编码器
* @return
*/
@Bean
public PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
//安全拦截机制(最重要)
@Override
protected void configure(HttpSecurity http) throws Exception {
//super.configure(http);
http.authorizeRequests()
.antMatchers("/r/r1").hasAuthority("p1")
.antMatchers("/r/r2").hasAuthority("p2")
.antMatchers("/r/**").authenticated()//所有/r/**的请求必须认证
.anyRequest().permitAll() //除了/r/** 其他请求都可以访问
.and()
.formLogin()//允许表单登录
.successForwardUrl("/login-success");//自定义登录成功路由
}
spring secutity认证授权的原理
经过一系列filter交给认证管理器(AuthenticationManager)和决策管理器 (AccessDecisionManager)
json对象里边的数组转为数组
@Controller与@RestController
@Controller与@RestController的区别
1 后者不能返回jsp页面, @RestController是@Controller和@ResponseBody的结合体,两个标注合并起来的作用。
2、如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
例如:本来应该到success.jsp页面的,则其显示success.
3、如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
4、如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。
校验顺序
网关先校验客户端的权限
微服务在校验访问资源的权限