1.配置类
@Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication()//手动在内存中存入账号密码 .withUser("admin") .password(passwordEncoder().encode("123"))//密码必须为加密 .roles("ADMIN")//角色 .authorities("sys:query") //权限 .and() .withUser("tom") .password(passwordEncoder().encode("123")) .roles("MANAGE") .and() .withUser("jerry") .password(passwordEncoder().encode("123")) .roles("STUDENT"); } @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } }
2.获取当前灯枯用户的信息的对象:1)Principal principal必须在Controller中用。2)SecurityContext框架的上下文对象,类似ServletContext,=SecurityContextHolder.getContext()。
3.方法鉴权
@Override protected void configure(HttpSecurity http) throws Exception {//鉴权 http.formLogin();//不调用这个方法登录会失效 http.authorizeRequests() .antMatchers("/admin/query").hasAnyRole("ADMIN")//hasRole是指定某个角色,Any是其中一个 .antMatchers("/manage/save").hasAnyRole("MANAGE") .antMatchers("/student/remove").hasAnyRole("STUDENT") .antMatchers("/sys/query").hasAuthority("sys:query")//权限 .anyRequest().authenticated();//所有请求 }
4,注解式权限鉴定,在配置类上加注解@EnableGlobalMethodSecurity(prePostEnabled = true),在需要鉴权的方法上加注解@PreAuthorize("hasRole('ADMIN')")权限@PreAuthorize("hasAuthority('sys:query')")角色
5.鉴权失败Handler,实现AccessDeniedHandler,在配置类中注入,http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);//鉴权失败处理器
6.未身份认证处理器AuthenticationEntryPoint;配置类中注入http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
7.springboot提供一个UserDetail的实现类,从数据库查询数据
@Service public class UserDetailServiceImpl implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return User.withUsername(username) .password(new BCryptPasswordEncoder().encode("123")) .authorities("sys:query", "sys:save", "ROLE_ADMIN") .build(); } } @AutoWired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); }
8.JWT json web token应用于web服务器单点登录一种特殊格式的字符串,不依赖于session,客户端保存数据,服务端解析数据。JWT字符串分为头部负载签名,Header是一个json对象,描述JWT的元数据,{“alg”:"HS256",“type”:"jwt"}签名算法为hs256,token令牌类型为jwt,最后将json对象Base64URL算法转为字符串。Payload其实也是json对象,存放需要传递的数据。Signature对前两个部分签名部分防止数据篡改。