[3天速成Spring Security] - 04 Spring Security安全配置简介

继承WebSecurityConfigurerAdapter类可以实现安全配置,其中常用的配置内容是HttpSecurityWebSecurity

HttpSecurity的配置

代码实现

  • 继承WebSecurityConfigurerAdapter,重写configure(HttpSecurity)方法
  • 实例代码
@Override
protected void configure(HttpSecurity http) throws Exception {
	// TODO...
}

代码分析

  • 查看方法基类默认实现,当没有重写该方法时,此默认配置则会生效
protected void configure(HttpSecurity http) throws Exception {
	this.logger.debug("Using default configure(HttpSecurity). "
				+ "If subclassed this will potentially override subclass configure(HttpSecurity).");
	http.authorizeRequests((requests) -> requests.anyRequest().authenticated()); // 任何请求都会进行认证
	http.formLogin(); // 启用内建的登录页面m
	http.httpBasic(); // 使用HTTP Basic Auth进行认证
}
  • 如果希望启用Security的调试功能且输出日志,则可以给@EnableWebSecurity(debug=true)参数启用。【默认不启用】
    在这里插入图片描述
  • 启用后则每当有API访问时都可以在控制台看到完整的请求内容【请求信息,参与的Filter Chain】
    在这里插入图片描述

配置Security用户名及密码

  • 在application.properties中配置登录用户名,密码及角色
spring.security.user.name=jack
spring.security.user.password=12345678
spring.security.user.roles=USER,ADMIN
  • 配置后,Spring Security就不会再为我们生成随机密码了

WebSecurity的配置

代码实现

  • 继承WebSecurityConfigurerAdapter,重写configure(WebSecurity)方法
  • 实例代码
@Override
public void configure(WebSecurity web) throws Exception {
	// TODO...
}
  • 与HttpSecurity的区别
    • 任何请求进入HttpSecurity configure的方法时都会启动过滤器链,但是启动过滤器链是很昂贵的操作,有时候并不期待经过过滤器链。当我们希望有的API不经过过滤器链的处理就允许或拒绝时,则需要在HttpSecurity的configure方法中实现。

代码分析

  • 当希望test开头的API请求不通过过滤器链时可以通过如下配置
@Override
public void configure(WebSecurity web) throws Exception {
	web.ignoring().mvcMatchers("/test/**");
}
  • 当用户访问/test/开头的API时,则会直接放行,不会经过过滤器链进行安全检查。通常作用于静态文件的路径等等…
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值