| 
 
| SpringSecurity入门 
 导入相关依赖
 
 thymeleaf
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-security</artifactId>
 </dependency>
 springsecurity
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>
 在默认配置的情况下启动项目
 
 创建IndexController
 
 package com.auth.springsecurity.controller;
 
 
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.GetMapping;
 
 @Controller
 public class IndexController {
 
 @GetMapping("/index")
 public String index(){
 return "index";
 }
 
 @GetMapping("/log")
 public String login(){
 return "login";
 }
 
 @GetMapping("/error")
 public String errorPage(){
 return "error";
 }
 }
 在浏览器中输入请求/index,会被拦截并重定向到默认的请求/login转到一个默认登陆界面。 SpringSecurity默认登陆界面 在默认配置的情况下用户名为:"user",默认密码会在项目启动时打印在控制台信息中。 SpringSecurity默认登陆密码 登陆之后自动跳转 登录成功后跳转
 
 自定义配置
 
 创建MySecurityConfig继承自WebSecurityConfigurerAdapter,并添加注解@EnableWebSecurity
 
 @EnableWebSecurity
 public class MySecurityConfig extends WebSecurityConfigurerAdapter {
 
 }
 重写config()方法 如图我们可以看到在WebSecurityConfigurerAdapter类中公有3个config()方法 WebSecurityConfigurerAdapter中的方法
 
 参数为HttpSecurity的config()方法
 
 formLogin().loginPage("/login") 拦截请求后转到登陆页面对应的请求。
 loginProcessingUrl("login")登陆表单提交对应的请求
 permitAll()当前页面不拦截
 authorizeRequests() 匹配请求认证
 antMatchers("/error").permitAll() 选择对应请求/error设置权限为不拦截
 .anyRequest().authenticated()选择任意请求设置权限为需要登陆
 logout().permitAll() 启动注销请求(/logout)且权限为不拦截 在这个方法中主要是对于资源访问权限的设定
 @Override
 protected void configure(HttpSecurity http) throws Exception {
 http
 .formLogin().loginPage("/login")
 .loginProcessingUrl("/login")
 .successForwardUrl("/index")
 .failureUrl("/error")
 .permitAll()
 .and()
 .authorizeRequests()
 .antMatchers("/error").permitAll()
 .anyRequest().authenticated()
 .and()
 .logout().permitAll()
 .and()
 .csrf().disable();
 }
 参数为AuthenticationManagerBuilder的方法
 
 inMemoryAuthentication()内存中验证
 .withUser("user").password("{noop}123456).roles("USER"); 添加用户
 注:在SpringSecurity5中密码的存储格式有变若采用明文存储需加前缀{noop}即"no opration",更多信息
 @Override
 protected void configure(AuthenticationManagerBuilder auth) throws Exception {
 auth.inMemoryAuthentication()
 .withUser("user")
 .password("{noop}123456")
 .roles("USER");
 }
 | 
 |