2019-06-12

Spring boot with web security

正确开启Web Security的方法:





定义WEB用户数据表Entity结构类(Model),





定义对应的JPA接口JPARepository,





定义对应的实现了UserDetailsService的用户详情类





@EnableWebSecurity写在Application类前面





定义一个带@Configuration,且基于WebSecurityConfigurerAdapter的配置类,重写两个configure方法,分别定义authentication(认证)和authorization(授权)行为





authentication设置





http.authorizeRequests()





.antMatchers("/error","/favicon.ico",
"/data/**", "/js/**", "/dist/**",
"/vendor/**").permitAll()





.anyRequest().authenticated()





.and().formLogin().loginPage("/login")





.failureUrl("/login?error").defaultSuccessUrl("/home").permitAll().and().logout().permitAll();





authorization设置





auth.userDetailsService(customUserService()).passwordEncoder(NoOpPasswordEncoder.getInstance());





注意点:





/error 需加入至permitAll中,否则错误页面会302





由于spring
security默认开启csrf,需在表单中加入以下csrf字段:





<input
type="hidden" th:name="$_csrf.parameterName"
th:value="$_csrf.token">





Spring security默认的权限查询SQL,用户及权限表字段设计需有下面的必需字段:





DEF_AUTHORITIES_BY_USERNAME_QUERY        "select
username,authority from authorities where username = ?"





DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY        "select
g.id, g.group_name, ga.authority from groups g, group_members gm,
group_authorities ga where gm.username = ? and g.id = ga.group_id and g.id =
gm.group_id"





DEF_USERS_BY_USERNAME_QUERY        "select
username,password,enabled from users where username = ?"





登陆表单,用户名:username,密码:password





AuthenticationManagerBuilder密码编码配置:





推荐的BCrypt算法:





auth.userDetailsService(customUserService()).passwordEncoder(new BCryptPasswordEncoder());





PLAINTEXT,明文,不推荐:





auth.userDetailsService(customUserService()).passwordEncoder(NoOpPasswordEncoder.getInstance());

没有评论:

发表评论