SpringSecurity(1)

SpringSecurity

HttpBasic模式

Basic认证是一种较为简单的HTTP认证方式,客户端通过明文(Base64编码格式)传输用户名和密码到服务端进行认证,通常需要配合HTTPS来保证信息传输的安全。

  • 项目的搭建
    1.新建maven项目
    2.pom文件
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
    </parent>
    <dependencies>
        <!--  springboot 整合web组件-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>

3.访问路径

@RestController
public class MemberService {
    @RequestMapping("/addMember")
    public String addMember() {
        return "addMember";
    }
    @RequestMapping("/delMember")
    public String delMember() {
        return "delMember";
    }
    @RequestMapping("/updateMember")
    public String updateMember(){
        return "updateMember";
    }
    @RequestMapping("/showMember")
    public String showMember(){
        return "showMember";
    }
}

4.config配置类

@Component//需要将配置类注入到ioc容器中
@EnableScheduling//开启校验
//继承WebSecurityConfigurerAdapter
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     *需要重写两个方法,1.对Security账户授权。2.对请求进行拦截的规则
     */
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 需要通过mubai账号来进行授权
         */
        auth.inMemoryAuthentication().withUser("mubai").password("123456").authorities("/");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //配置认证方式 token,设置httpBasic模式
        //拦截全部请求进入httpBasic模式
        http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();
    }
    /**
     * There is no PasswordEncoder mapped for the id "null"
     * 原因:升级为Security5.0以上密码支持多中加密方式,恢复以前模式
     * @return
     */
    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }
}

formLogin模式

1.修改拦截请求的规则

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //配置认证方式 token,设置httpBasic模式
        //拦截全部请求进入httpBasic模式
//        http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();
        // /adddMember:拦截的规则 addMember:拦截的名称
        http.authorizeRequests().antMatchers("/addMember").hasAnyAuthority("addMember")
                .antMatchers("/delMember").hasAnyAuthority("delMember")
                .antMatchers("/updateMember").hasAnyAuthority("updateMember")
                .antMatchers("/showMember").hasAnyAuthority("showMember")

                .antMatchers("/**").fullyAuthenticated().and().formLogin();
    }

2.对账号进行授权

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 需要通过mubai账号来进行授权
         */
//        auth.inMemoryAuthentication().withUser("mubai").password("123456").authorities("/"); //此处的意思是 mubai这个账号可以访问所有的接口
        auth.inMemoryAuthentication().withUser("mubai_admin").password("123456").authorities("/");
        auth.inMemoryAuthentication().withUser("mubai_crud").password("123456").authorities("addMember","updateMember","delMember");
        auth.inMemoryAuthentication().withUser("mubai_show").password("123456").authorities("showMember");
    }

定义springboot错误页面

1.config配置

/**
 * 自定义SpringBoot 错误异常
 */
@Configuration
public class WebServerAutoConfiguration {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400");
        ErrorPage errorPage401 = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401");
        ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, "/error/403");
        ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
        ErrorPage errorPage415 = new ErrorPage(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "/error/415");
        ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
        factory.addErrorPages(errorPage400, errorPage401, errorPage403, errorPage404, errorPage415, errorPage500);
        return factory;
    }
}

2.定义错误页面

/**
 * 统一返回错误异常的类
 */
@RestController
public class ErrorController {
    @RequestMapping("/error/403")
    public String error(){
        return "访问的页面权限不足!";
    }
}

修改fromlog页面

1.修改权限规则:开放/login请求

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //配置认证方式 token,设置httpBasic模式
        //拦截全部请求进入httpBasic模式
//        http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();
        // /adddMember:拦截的规则 addMember:拦截的名称
        http.authorizeRequests().antMatchers("/addMember").hasAnyAuthority("addMember")
                .antMatchers("/delMember").hasAnyAuthority("delMember")
                .antMatchers("/updateMember").hasAnyAuthority("updateMember")
                .antMatchers("/showMember").hasAnyAuthority("showMember")
//                并且关闭csrf 设置跳转到自定义login页面  放开权限
                .antMatchers("/login").permitAll()
//                设置自定义登录页面
                .antMatchers("/**").fullyAuthenticated()
                .and().formLogin().loginPage("/login")
                .and().csrf().disable();
    }

2.编写LoginController,并将ErrorController放入Controller层

@Controller//此处注解是返回页面(配合视图解析器)
public class LoginController {
    @RequestMapping("/login")
    public String login() {
        return "login";
    }
}

3.在资源包中新建temolates文件夹新建文件login.ftl

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
</head>
<body>

<h1>每特教育--权限控制登陆系统</h1>
<form action="/login" method="post">
    <span>用户名称</span><input type="text" name="username"/> <br>
    <span>用户密码</span><input type="password" name="password"/> <br>
    <input type="submit" value="登陆">

</form>
<#if RequestParameters['error']??>
    用户名称或者密码错误
</#if>
</body>
</html>

4.编辑yml文件

spring:
  freemarker:
    settings:
      classic_compatible: true #处理空值
      datetime_format: yyy-MM-dd HH:mm
      number_format: 0.##
    suffix: .ftl
    template-loader-path:
      - classpath:/templates 

5.添加maven依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值