第一步:添加Security的依赖:
|
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> |
第二步:配置Security信息
找到@Configuration注解的配置类,在其基础上添加@EnableWebSecurity注解,由于该注解要求被注解的类实现WebSecurityConfigurer接口,或者继承WebSecurityConfigurerAdapter类,这里选择继承WebSecurityConfigurerAdapter;
重写WebSecurityConfigurerAdapter的2个方法,把@Override去掉,把protected修改为public,这2个方法是:
configure(AuthenticationManagerBuilder)
configure(HttpSecurity)
下面贴出部分代码:
|
// @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { //认证用户的来源:内存、数据库等 // 这里是基于内存的,到了项目中还是基于数据库的 auth.inMemoryAuthentication() .withUser("zonghang").password("(noop)111111").roles("ADMIN"); // super.configure(auth); } // @Override public void configure(HttpSecurity http) throws Exception { //配置SpringSecurity信息:释放静态资源、指定拦截规则、指定自定义认证页面、指定认证配置、csrf配置 // super.configure(http); http.authorizeRequests() //禁止拦截的URL路径 .antMatchers("/login","/loginfailer","/css/**","/image/**").permitAll() //以下路径需要拦截 .antMatchers("/**").hasAnyRole("ADMIN","USER").anyRequest().authenticated() //另外的配置 .and() //指定自定义登录页面、登录页面提交的action、登录成功后跳转的页面、登录失败后跳转的页面 .formLogin().loginPage("/login.html").loginProcessingUrl("/login").successForwardUrl("index.html").failureForwardUrl("/loginfailer.html") .and() //退出提交的action、退出成功后跳转的页面 .logout().logoutUrl("/logout").logoutSuccessUrl("/login.html") //校验session .invalidateHttpSession(true) //提交配置 .permitAll() .and() //禁止csrf .csrf().disable(); } |
第三步:配置视图解析器
第四步:配置action权限
找到@Configuration注解的配置类,在其基础上添加@EnableGlobalMethodSecurity注解,确定使用哪个框架的注解来配置权限;
在具体的action方法上,通过@Secured注解来指定角色名称;
第五步:处理权限异常
@ControllerAdvice注解类
@ExcetionHandler注解方法;
总结
除了添加starter启动器之后,其他过程与Security开发过程相同;
1325

被折叠的 条评论
为什么被折叠?



