springboot应用中可采用spring security实现 用户身份验证,登录拦截,鉴权和攻击防护 功能。
在springboot应用中使用spring security,需先在项目中引入spring security 构件包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Springsecurity本身只支持用户名密码认证,默认以session形式实现。有以下几个核心概念:
1.用户详情接口UserDetails:定义了认证主体用户的基本信息,像用户名、密码、过期时间、权限角色等,需实现,可根据情况添加属性;
2.用户详情服务接口UserDetailsService:定义了通过用户名来加载用户详情对象的方法,需实现,可根据情况选择用户数据源;
3.认证管理器AuthenticationManager:用来管理认证信息的,springsecurity自带,在配置类中注入即可;
4.认证信息类Authentication:认证信息,里面包含了认证通过了的对象和密码,在认证通过后, 由AuthenticationManager创建;
5.安全上下文SecurityContext :在上下文中存储Authentication对象,可通过SecurityContextHolder类获取;
6.认证成功处理接口AuthenticationSuccessHandler:可选的,定义认证成功后系统需执行的内容;
7.认证失败处理接口AuthenticationEntryPoint:定义认证失败后系统需执行的内容,需实现;
8.退出系统处理接口LogoutSuccessHandler:定义用户登出后系统需执行的内容,需实现;
9.用户名密码过滤器UsernamePasswordAuthenticationFilter:默认自动使用。
使用时,在Springsecurity配置类中配置AuthenticationManager,AuthenticationSuccessHandler,AuthenticationEntryPoint,LogoutSuccessHandler;然后在登录接口中认证并生成认证信息对象放入
SecurityContext 中,这样登录后的用户就可以正常访问系统了,未登录成功的会被系统拦截;
现代企业web应用一般都是面向多端、跨域调用的分布式系统,在这样的需求场景下,可结合JWT技术来实现安全认证功能。
JWT介绍:
JWT:Json Web Token.一串字符,由三部分构成:
Head:
声明类型,这里是jwt
声明加密的算法 通常直接使用 HMAC SHA256
如:
{
‘typ’: ‘JWT’,
‘alg’: ‘HS256’
}
此部分进行base64加密,得到token的第一部分。
Payload:载荷就是存放有效信息的地方。可被解密,不建议放敏感信息。
标准中注册的声明(建议但不强制使用)
公共的声明(一般添加用户的相关信息或其他业务需要的必要信息)
私有的声明(提供者和消费者所共同定义的声明)
如:
{
“sub”: “1234567890”,
“name”: “John Doe”,
“admin”: true
}
此部分进行base64加密,得到token的第二部分。
Signature:是一个签证信息,
=header中声明的算法HMACSHA*(header (base64后的).payload (base64后的),secret);
此部分signature值作为token的第三部分。
最终JWT的token值为:header(base64).payload(base64).signature
使用一般是在httprequest的请求头中添加一个键值:Authorization: 'Bearer ’ + token
JWT技术的token方案会在springsecurity的原认证流程中,加入token的生成和解析环节,并要求客户端的请求头中带有token值。会需要在springsecurity的配置类中新增一个过滤器,在用户名密码过滤器前做解析token获得认证信息。
一个springsecurity的配置类样例:
package com.*.*.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.*.security.filter.JwtAuthenticationTokenFilter;
import com.*.security.handle.AuthenticationEntryPointImpl;
import com.*.security.handle.LogoutSuccessHandlerImpl;
/**
* spring security配置
*
* @author nick
*/
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
/**
* 自定义用户认证逻辑
*/
@Autowired
private UserDetailsService userDetailsService;
/**
* 认证失败处理类
*/
@Autowired
private AuthenticationEntryPointImpl unauthorizedHandler;
/**
* 退出处理类
*/
@Autowired
private LogoutSuccessHandlerImpl logoutSuccessHandler;
/**
* token认证过滤器
*/
@Autowired
private JwtAuthenticationTokenFilter authenticationTokenFilter;
/**
* 解决 无法直接注入 AuthenticationManager
*
* @return
* @throws Exception
*/
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception
{
return super.authenticationManagerBean();
}
/**
* anyRequest | 匹配所有请求路径
* access | SpringEl表达式结果为true时可以访问
* anonymous | 匿名可以访问
* denyAll | 用户不能访问
* fullyAuthenticated | 用户完全认证可以访问(非remember-me下自动登录)
* hasAnyAuthority | 如果有参数,参数表示权限,则其中任何一个权限可以访问
* hasAnyRole | 如果有参数,参数表示角色,则其中任何一个角色可以访问
* hasAuthority | 如果有参数,参数表示权限,则其权限可以访问
* hasIpAddress | 如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
* hasRole | 如果有参数,参数表示角色,则其角色可以访问
* permitAll | 用户可以任意访问
* rememberMe | 允许通过remember-me登录的用户访问
* authenticated | 用户登录后可访问
*/
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception
{
httpSecurity
// CRSF禁用,因为不使用session
.csrf().disable()
// 认证失败处理类
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
// 基于token,所以不需要session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 过滤请求
.authorizeRequests()
// 对于登录login 验证码captchaImage 允许匿名访问
.antMatchers("/login", "/sendCode", "/checkCode", "/addUser","/getCode","/retrievePwd").anonymous()
.antMatchers(
HttpMethod.GET,
"/*.html",
"/**/*.html",
"/**/*.css",
"/**/*.js"
).permitAll()
// 限定某个角色才能访问的资源
.antMatchers("/admin/**").hasRole("ADMIN")
// 除上面外的所有请求全部需要身份认证
.anyRequest().authenticated()
.and()
.headers().frameOptions().disable();
httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
// 添加JWT filter
httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
}
/**
* 强散列哈希加密实现
*/
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder()
{
return new BCryptPasswordEncoder();
}
/**
* 身份认证接口
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
}
如果配置类上添加了@EnableGlobalMethodSecurity(prePostEnabled = true)注解,还可以通过在接口方法上加以下注解来控制权限:
@PreAuthorize 在访问之前就进行权限判断
@PostAuthorize 在请求之后进行判断,如果返回值不满足条件,会抛出异常,但是方法本身是已经执行过了的。
@PreFilter 在方法执行之前,用于过滤集合中的值。
@PostFilter 会对返回的集合进行过滤。
带代码演示的部分可参考:https://www.cnblogs.com/dl610455894/p/14072960.html