A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 甘为伊一 初级黑马   /  2019-6-12 16:03  /  807 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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");
    }

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马