springboot整合springsecurity从Hello World到源码解析(三):基础配置详解

cover

cover

 

上一章我们从源码角度探究了springboot对于帮我们初始化的springsecurity默认配置,这章我们来学习下springsecurity中的基础配置

修改基础配置

  • 上一章我们已经知道,springsecurity中所有配置基本都来源于一个默认的WebSecurityConfigurerAdapter,那我们首先写一个类继承它,放弃springboot帮我们做的默认配置,
    叫SecurityConfig,为了看到更多的配置,我们加上一个注解(其实springboot已经帮我们加上),@EnableWebSecurity(debug = true),修改debug位true,
    然后打开我们的配置文件application.yml,修改spring的log信息为debug,如下:
 1server:
 2  port: 8080
 3
 4spring:
 5  freemarker:
 6    enabled: true
 7    cache: false
 8    template-loader-path: classpath:/templates/
 9    suffix: .html
10
11  security:
12    user:
13      name: user
14      password: admin
15      roles: user, admin
16logging:
17  level:
18    org.springframework.*: debug

配置详解

  • 打开SecurityConfig,首先明确我们的目的:修改原来的登陆页面,登陆成功后,跳转到我们的hello页面,所以首先添加登陆页面login.html,并且添加视图解析(和第一章一样添加controller同样效果):
 1<!DOCTYPE html>
 2<html lang="en">
 3<head>
 4    <meta charset="UTF-8">
 5    <title>login page</title>
 6</head>
 7<body>
 8This is login page from jsbintask
 9<form action="/login" method="post">
10    username: <input name="username" /><br/>
11    password: <input name="password" /><br/>
12    <button type="submit">submit</button>
13</form>
14</body>
15</html>

这里请记住这个表单提交的地址/login,写一个类WebMvcConfig实现WebMvcConfigurer(2.0以前需要继承WebMvcConfigurerAdapter),添加如下配置:

 1@Configuration
 2@EnableWebMvc
 3public class WebMvcConfig implements WebMvcConfigurer {
 4    @Override
 5    public void addViewControllers(ViewControllerRegistry registry) {
 6        registry.addViewController("/index").setViewName("login");
 7    }
 8
 9    @Override
10    public void addResourceHandlers(ResourceHandlerRegistry registry) {
11    }
12}
  • 接着继续回来SecurityConfig,首先覆盖下原方法configure(HttpSecurity http),我们看下原来实现是什么:
 1protected void configure(HttpSecurity http) throws Exception {
 2        logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");
 3
 4        http
 5            .authorizeRequests()
 6                .anyRequest().authenticated()
 7                .and()
 8            .formLogin().and()
 9            .httpBasic();
10    }

可以看出,默认配置就是所有页面全部被拦截,开启登陆表单验证以及http basic验证,我们继续查看formLogin()方法:

1public FormLoginConfigurer<HttpSecurity> formLogin() throws Exception {
2        return getOrApply(new FormLoginConfigurer<>());
3    }

熟悉的apply方法,上一章已经介绍,这是添加拦截器,FormLoginConfigurer如下:

1public FormLoginConfigurer() {
2        super(new UsernamePasswordAuthenticationFilter(), null);
3        userna
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值