前言
spring security是spring生态系统中最强大的安全框架,为java应用提供了全面的安全解决方案。它提供了认证、授权、防护等核心功能,广泛应用于企业级应用开发。本文将从基础概念到实战应用,全面讲解spring security的核心知识点。
一、spring security概述
1.1 什么是spring security
spring security是一个功能强大且高度可定制的身份验证和访问控制框架,它为java应用提供:
- 身份认证(authentication)
- 授权(authorization)
- 防护常见攻击(csrf、session fixation等)
- 与spring生态无缝集成
spring security核心架构 ┌─────────────────────────────────────────┐ │ security filter chain │ │ ┌───────────────────────────────────┐ │ │ │ usernamepasswordauthfilter │ │ │ │ basicauthenticationfilter │ │ │ │ oauth2authenticationfilter │ │ │ │ exceptiontranslationfilter │ │ │ │ filtersecurityinterceptor │ │ │ └───────────────────────────────────┘ │ │ ↓ │ │ ┌───────────────────────────────────┐ │ │ │ authentication manager │ │ │ └───────────────────────────────────┘ │ │ ↓ │ │ ┌───────────────────────────────────┐ │ │ │ authentication provider │ │ │ └───────────────────────────────────┘ │ │ ↓ │ │ ┌───────────────────────────────────┐ │ │ │ userdetailsservice │ │ │ └───────────────────────────────────┘ │ └─────────────────────────────────────────┘
1.2 核心概念
核心组件说明 ┌──────────────────────┬────────────────────────┐ │ 组件 │ 说明 │ ├──────────────────────┼────────────────────────┤ │ authentication │ 认证信息(用户凭证) │ │ securitycontext │ 安全上下文(存储认证) │ │ userdetails │ 用户详情接口 │ │ userdetailsservice │ 加载用户数据 │ │ grantedauthority │ 授权信息(角色/权限) │ │ accessdecisionmanager│ 访问决策管理器 │ └──────────────────────┴────────────────────────┘
二、快速开始
2.1 添加依赖
<!-- spring boot项目 -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-security</artifactid>
</dependency>
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>2.2 基础配置
/**
* spring security基础配置
*/
@configuration
@enablewebsecurity
public class securityconfig {
@bean
public securityfilterchain securityfilterchain(httpsecurity http) throws exception {
http
// 配置授权规则
.authorizehttprequests(auth -> auth
.requestmatchers("/public/**").permitall() // 公开接口
.requestmatchers("/admin/**").hasrole("admin") // 需要admin角色
.anyrequest().authenticated() // 其他需要认证
)
// 配置表单登录
.formlogin(form -> form
.loginpage("/login") // 自定义登录页
.defaultsuccessurl("/home") // 登录成功跳转
.permitall()
)
// 配置登出
.logout(logout -> logout
.logouturl("/logout")
.logoutsuccessurl("/login?logout")
.permitall()
);
return http.build();
}
/**
* 配置用户详情服务
*/
@bean
public userdetailsservice userdetailsservice() {
// 内存用户(仅用于测试)
userdetails user = user.builder()
.username("user")
.password(passwordencoder().encode("password"))
.roles("user")
.build();
userdetails admin = user.builder()
.username("admin")
.password(passwordencoder().encode("admin"))
.roles("admin", "user")
.build();
return new inmemoryuserdetailsmanager(user, admin);
}
/**
* 密码编码器
*/
@bean
public passwordencoder passwordencoder() {
return new bcryptpasswordencoder();
}
}2.3 基础使用
/**
* 测试controller
*/
@restcontroller
public class testcontroller {
@getmapping("/public/hello")
public string publichello() {
return "公开接口,无需认证";
}
@getmapping("/user/profile")
public string userprofile() {
return "用户信息,需要认证";
}
@getmapping("/admin/dashboard")
public string admindashboard() {
return "管理后台,需要admin角色";
}
@getmapping("/current-user")
public string currentuser(authentication authentication) {
return "当前用户: " + authentication.getname();
}
}三、认证(authentication)
3.1 自定义userdetailsservice
/**
* 自定义用户详情服务
*/
@service
public class customuserdetailsservice implements userdetailsservice {
@autowired
private userrepository userrepository;
@override
public userdetails loaduserbyusername(string username) throws usernamenotfoundexception {
// 从数据库加载用户
com.example.entity.user user = userrepository.findbyusername(username)
.orelsethrow(() -> new usernamenotfoundexception("用户不存在: " + username));
// 转换为spring security的userdetails
return org.springframework.security.core.userdetails.user.builder()
.username(user.getusername())
.password(user.getpassword())
.authorities(getauthorities(user))
.accountexpired(!user.isaccountnonexpired())
.accountlocked(!user.isaccountnonlocked())
.credentialsexpired(!user.iscredentialsnonexpired())
.disabled(!user.isenabled())
.build();
}
/**
* 获取用户权限
*/
private collection<? extends grantedauthority> getauthorities(com.example.entity.user user) {
return user.getroles().stream()
.map(role -> new simplegrantedauthority("role_" + role.getname()))
.collect(collectors.tolist());
}
}
/**
* 用户实体
*/
@entity
@table(name = "users")
@data
public class user {
@id
@generatedvalue(strategy = generationtype.identity)
private long id;
@column(unique = true, nullable = false)
private string username;
@column(nullable = false)
private string password;
private string email;
private boolean enabled = true;
private boolean accountnonexpired = true;
private boolean accountnonlocked = true;
private boolean credentialsnonexpired = true;
@manytomany(fetch = fetchtype.eager)
@jointable(
name = "user_roles",
joincolumns = @joincolumn(name = "user_id"),
inversejoincolumns = @joincolumn(name = "role_id")
)
private set<role> roles = new hashset<>();
}
/**
* 角色实体
*/
@entity
@table(name = "roles")
@data
public class role {
@id
@generatedvalue(strategy = generationtype.identity)
private long id;
@column(unique = true, nullable = false)
private string name;
private string description;
}3.2 自定义认证提供者
/**
* 自定义认证提供者
*/
@component
public class customauthenticationprovider implements authenticationprovider {
@autowired
private userdetailsservice userdetailsservice;
@autowired
private passwordencoder passwordencoder;
@override
public authentication authenticate(authentication authentication)
throws authenticationexception {
string username = authentication.getname();
string password = authentication.getcredentials().tostring();
// 加载用户
userdetails user = userdetailsservice.loaduserbyusername(username);
// 验证密码
if (!passwordencoder.matches(password, user.getpassword())) {
throw new badcredentialsexception("密码错误");
}
// 额外的业务校验
if (!user.isenabled()) {
throw new disabledexception("账户已禁用");
}
if (!user.isaccountnonlocked()) {
throw new lockedexception("账户已锁定");
}
// 创建认证令牌
return new usernamepasswordauthenticationtoken(
user, password, user.getauthorities()
);
}
@override
public boolean supports(class<?> authentication) {
return usernamepasswordauthenticationtoken.class.isassignablefrom(authentication);
}
}3.3 登录接口
/**
* 登录控制器
*/
@restcontroller
@requestmapping("/auth")
public class authcontroller {
@autowired
private authenticationmanager authenticationmanager;
@autowired
private jwttokenprovider jwttokenprovider;
/**
* 用户登录
*/
@postmapping("/login")
public responseentity<?> login(@requestbody loginrequest request) {
try {
// 认证
authentication authentication = authenticationmanager.authenticate(
new usernamepasswordauthenticationtoken(
request.getusername(),
request.getpassword()
)
);
// 设置到安全上下文
securitycontextholder.getcontext().setauthentication(authentication);
// 生成jwt token
string token = jwttokenprovider.generatetoken(authentication);
return responseentity.ok(new loginresponse(token, "登录成功"));
} catch (badcredentialsexception e) {
return responseentity.status(httpstatus.unauthorized)
.body(new errorresponse("用户名或密码错误"));
} catch (disabledexception e) {
return responseentity.status(httpstatus.forbidden)
.body(new errorresponse("账户已禁用"));
}
}
/**
* 用户注册
*/
@postmapping("/register")
public responseentity<?> register(@requestbody registerrequest request) {
// 实现注册逻辑
return responseentity.ok("注册成功");
}
}
@data
class loginrequest {
private string username;
private string password;
}
@data
@allargsconstructor
class loginresponse {
private string token;
private string message;
}
@data
@allargsconstructor
class errorresponse {
private string message;
}
@data
class registerrequest {
private string username;
private string password;
private string email;
}四、授权(authorization)
4.1 基于url的授权
/**
* url授权配置
*/
@configuration
@enablewebsecurity
public class urlauthorizationconfig {
@bean
public securityfilterchain securityfilterchain(httpsecurity http) throws exception {
http
.authorizehttprequests(auth -> auth
// 公开接口
.requestmatchers("/", "/public/**", "/auth/**").permitall()
// 需要认证
.requestmatchers("/user/**").authenticated()
// 角色授权
.requestmatchers("/admin/**").hasrole("admin")
.requestmatchers("/manager/**").hasanyrole("admin", "manager")
// 权限授权
.requestmatchers("/api/users/**").hasauthority("user_manage")
.requestmatchers("/api/posts/**").hasanyauthority("post_read", "post_write")
// 使用spel表达式
.requestmatchers("/api/account/**").access(
new webexpressionauthorizationmanager(
"hasrole('user') and #username == authentication.name"
)
)
// 其他请求需要认证
.anyrequest().authenticated()
);
return http.build();
}
}4.2 基于方法的授权
/**
* 启用方法级安全
*/
@configuration
@enablemethodsecurity(
prepostenabled = true, // 启用@preauthorize/@postauthorize
securedenabled = true, // 启用@secured
jsr250enabled = true // 启用@rolesallowed
)
public class methodsecurityconfig {
}
/**
* 方法级授权示例
*/
@service
public class userservice {
@autowired
private userrepository userrepository;
/**
* @preauthorize:方法执行前检查权限
*/
@preauthorize("hasrole('admin')")
public list<user> getallusers() {
return userrepository.findall();
}
/**
* 基于参数的权限检查
*/
@preauthorize("#userid == authentication.principal.id or hasrole('admin')")
public user getuserbyid(long userid) {
return userrepository.findbyid(userid).orelse(null);
}
/**
* 复杂表达式
*/
@preauthorize("hasrole('user') and #user.username == authentication.name")
public void updateuser(user user) {
userrepository.save(user);
}
/**
* @postauthorize:方法执行后检查权限
*/
@postauthorize("returnobject.username == authentication.name or hasrole('admin')")
public user finduser(long id) {
return userrepository.findbyid(id).orelse(null);
}
/**
* @secured:基于角色的简单授权
*/
@secured({"role_admin", "role_manager"})
public void deleteuser(long userid) {
userrepository.deletebyid(userid);
}
/**
* @rolesallowed:jsr-250标准
*/
@rolesallowed("admin")
public void resetpassword(long userid, string newpassword) {
user user = userrepository.findbyid(userid).orelsethrow();
user.setpassword(newpassword);
userrepository.save(user);
}
/**
* @prefilter:过滤方法参数
*/
@prefilter("filterobject.owner == authentication.name")
public void deleteitems(list<item> items) {
items.foreach(item -> system.out.println("删除: " + item.getname()));
}
/**
* @postfilter:过滤返回结果
*/
@postfilter("filterobject.owner == authentication.name")
public list<item> getitems() {
// 返回所有数据,spring security会过滤
return arrays.aslist(
new item("item1", "user1"),
new item("item2", "user2"),
new item("item3", "user1")
);
}
}
@data
@allargsconstructor
class item {
private string name;
private string owner;
}4.3 自定义权限评估器
/**
* 自定义权限评估器
*/
@component("permissionevaluator")
public class custompermissionevaluator implements permissionevaluator {
@autowired
private userrepository userrepository;
@override
public boolean haspermission(authentication authentication, object targetdomainobject,
object permission) {
if (authentication == null || targetdomainobject == null || !(permission instanceof string)) {
return false;
}
string targettype = targetdomainobject.getclass().getsimplename().touppercase();
return hasprivilege(authentication, targettype, permission.tostring());
}
@override
public boolean haspermission(authentication authentication, serializable targetid,
string targettype, object permission) {
if (authentication == null || targettype == null || !(permission instanceof string)) {
return false;
}
return hasprivilege(authentication, targettype.touppercase(), permission.tostring());
}
private boolean hasprivilege(authentication auth, string targettype, string permission) {
string username = auth.getname();
user user = userrepository.findbyusername(username).orelse(null);
if (user == null) {
return false;
}
// 检查用户权限
return user.getroles().stream()
.flatmap(role -> role.getpermissions().stream())
.anymatch(p -> p.getname().equals(targettype + "_" + permission));
}
}
/**
* 使用自定义权限评估器
*/
@service
public class documentservice {
/**
* 使用haspermission检查权限
*/
@preauthorize("haspermission(#document, 'edit')")
public void editdocument(document document) {
system.out.println("编辑文档: " + document.gettitle());
}
@preauthorize("haspermission(#documentid, 'document', 'delete')")
public void deletedocument(long documentid) {
system.out.println("删除文档: " + documentid);
}
}
@data
class document {
private long id;
private string title;
private string owner;
}五、jwt认证
5.1 jwt工具类
/**
* jwt token提供者
*/
@component
public class jwttokenprovider {
@value("${jwt.secret:mysecretkey}")
private string jwtsecret;
@value("${jwt.expiration:86400000}") // 24小时
private long jwtexpiration;
/**
* 生成token
*/
public string generatetoken(authentication authentication) {
userdetails userdetails = (userdetails) authentication.getprincipal();
date now = new date();
date expirydate = new date(now.gettime() + jwtexpiration);
return jwts.builder()
.setsubject(userdetails.getusername())
.setissuedat(now)
.setexpiration(expirydate)
.signwith(signaturealgorithm.hs512, jwtsecret)
.compact();
}
/**
* 从token获取用户名
*/
public string getusernamefromtoken(string token) {
claims claims = jwts.parser()
.setsigningkey(jwtsecret)
.parseclaimsjws(token)
.getbody();
return claims.getsubject();
}
/**
* 验证token
*/
public boolean validatetoken(string token) {
try {
jwts.parser().setsigningkey(jwtsecret).parseclaimsjws(token);
return true;
} catch (signatureexception ex) {
system.err.println("invalid jwt signature");
} catch (malformedjwtexception ex) {
system.err.println("invalid jwt token");
} catch (expiredjwtexception ex) {
system.err.println("expired jwt token");
} catch (unsupportedjwtexception ex) {
system.err.println("unsupported jwt token");
} catch (illegalargumentexception ex) {
system.err.println("jwt claims string is empty");
}
return false;
}
}5.2 jwt认证过滤器
/**
* jwt认证过滤器
*/
public class jwtauthenticationfilter extends onceperrequestfilter {
@autowired
private jwttokenprovider tokenprovider;
@autowired
private userdetailsservice userdetailsservice;
@override
protected void dofilterinternal(httpservletrequest request,
httpservletresponse response,
filterchain filterchain)
throws servletexception, ioexception {
try {
// 从请求头获取token
string jwt = getjwtfromrequest(request);
if (stringutils.hastext(jwt) && tokenprovider.validatetoken(jwt)) {
// 从token获取用户名
string username = tokenprovider.getusernamefromtoken(jwt);
// 加载用户详情
userdetails userdetails = userdetailsservice.loaduserbyusername(username);
// 创建认证对象
usernamepasswordauthenticationtoken authentication =
new usernamepasswordauthenticationtoken(
userdetails, null, userdetails.getauthorities()
);
authentication.setdetails(
new webauthenticationdetailssource().builddetails(request)
);
// 设置到安全上下文
securitycontextholder.getcontext().setauthentication(authentication);
}
} catch (exception ex) {
logger.error("could not set user authentication in security context", ex);
}
filterchain.dofilter(request, response);
}
/**
* 从请求头提取token
*/
private string getjwtfromrequest(httpservletrequest request) {
string bearertoken = request.getheader("authorization");
if (stringutils.hastext(bearertoken) && bearertoken.startswith("bearer ")) {
return bearertoken.substring(7);
}
return null;
}
}5.3 jwt配置
/**
* jwt安全配置
*/
@configuration
@enablewebsecurity
public class jwtsecurityconfig {
@autowired
private jwtauthenticationentrypoint jwtauthentrypoint;
@bean
public jwtauthenticationfilter jwtauthenticationfilter() {
return new jwtauthenticationfilter();
}
@bean
public securityfilterchain securityfilterchain(httpsecurity http) throws exception {
http
// 禁用csrf(使用jwt不需要)
.csrf(csrf -> csrf.disable())
// 禁用session
.sessionmanagement(session -> session
.sessioncreationpolicy(sessioncreationpolicy.stateless)
)
// 异常处理
.exceptionhandling(exception -> exception
.authenticationentrypoint(jwtauthentrypoint)
)
// 授权配置
.authorizehttprequests(auth -> auth
.requestmatchers("/auth/**").permitall()
.anyrequest().authenticated()
);
// 添加jwt过滤器
http.addfilterbefore(
jwtauthenticationfilter(),
usernamepasswordauthenticationfilter.class
);
return http.build();
}
@bean
public authenticationmanager authenticationmanager(
authenticationconfiguration authconfig) throws exception {
return authconfig.getauthenticationmanager();
}
}
/**
* jwt认证入口点(处理认证失败)
*/
@component
public class jwtauthenticationentrypoint implements authenticationentrypoint {
@override
public void commence(httpservletrequest request,
httpservletresponse response,
authenticationexception authexception)
throws ioexception {
response.setcontenttype("application/json;charset=utf-8");
response.setstatus(httpservletresponse.sc_unauthorized);
map<string, object> error = new hashmap<>();
error.put("status", 401);
error.put("error", "unauthorized");
error.put("message", authexception.getmessage());
error.put("path", request.getservletpath());
objectmapper mapper = new objectmapper();
response.getwriter().write(mapper.writevalueasstring(error));
}
}六、实战案例
6.1 案例1:多租户权限隔离
/**
* 租户上下文
*/
public class tenantcontext {
private static final threadlocal<string> currenttenant = new threadlocal<>();
public static void setcurrenttenant(string tenant) {
currenttenant.set(tenant);
}
public static string getcurrenttenant() {
return currenttenant.get();
}
public static void clear() {
currenttenant.remove();
}
}
/**
* 租户过滤器
*/
public class tenantfilter extends onceperrequestfilter {
@override
protected void dofilterinternal(httpservletrequest request,
httpservletresponse response,
filterchain filterchain)
throws servletexception, ioexception {
try {
// 从请求头获取租户id
string tenantid = request.getheader("x-tenant-id");
if (tenantid != null) {
tenantcontext.setcurrenttenant(tenantid);
}
filterchain.dofilter(request, response);
} finally {
tenantcontext.clear();
}
}
}
/**
* 租户权限评估器
*/
@component
public class tenantpermissionevaluator {
/**
* 检查用户是否属于当前租户
*/
public boolean belongstotenant(authentication authentication) {
string currenttenant = tenantcontext.getcurrenttenant();
if (currenttenant == null) {
return false;
}
userdetails user = (userdetails) authentication.getprincipal();
// 从用户信息中获取租户id并比较
return true; // 简化实现
}
}
/**
* 使用租户权限
*/
@restcontroller
@requestmapping("/api/tenants")
public class tenantcontroller {
@preauthorize("@tenantpermissionevaluator.belongstotenant(authentication)")
@getmapping("/data")
public list<tenantdata> gettenantdata() {
string tenantid = tenantcontext.getcurrenttenant();
return arrays.aslist(new tenantdata(tenantid, "数据"));
}
}
@data
@allargsconstructor
class tenantdata {
private string tenantid;
private string data;
}6.2 案例2:动态权限管理
/**
* 动态权限服务
*/
@service
public class dynamicpermissionservice {
@autowired
private permissionrepository permissionrepository;
/**
* 检查动态权限
*/
public boolean haspermission(string username, string resource, string action) {
// 从数据库查询用户权限
list<permission> permissions = permissionrepository.findbyusername(username);
return permissions.stream()
.anymatch(p -> p.getresource().equals(resource) &&
p.getaction().equals(action));
}
}
/**
* 权限实体
*/
@entity
@table(name = "permissions")
@data
class permission {
@id
@generatedvalue(strategy = generationtype.identity)
private long id;
private string username;
private string resource;
private string action;
}
/**
* 动态权限拦截器
*/
@component
@aspect
public class dynamicpermissionaspect {
@autowired
private dynamicpermissionservice permissionservice;
@around("@annotation(requirepermission)")
public object checkpermission(proceedingjoinpoint joinpoint,
requirepermission requirepermission)
throws throwable {
authentication auth = securitycontextholder.getcontext().getauthentication();
string username = auth.getname();
boolean haspermission = permissionservice.haspermission(
username,
requirepermission.resource(),
requirepermission.action()
);
if (!haspermission) {
throw new accessdeniedexception("权限不足");
}
return joinpoint.proceed();
}
}
/**
* 自定义权限注解
*/
@target(elementtype.method)
@retention(retentionpolicy.runtime)
@interface requirepermission {
string resource();
string action();
}
/**
* 使用动态权限
*/
@restcontroller
@requestmapping("/api/users")
public class dynamicpermissioncontroller {
@requirepermission(resource = "user", action = "create")
@postmapping
public string createuser(@requestbody user user) {
return "创建用户成功";
}
@requirepermission(resource = "user", action = "delete")
@deletemapping("/{id}")
public string deleteuser(@pathvariable long id) {
return "删除用户成功";
}
}6.3 案例3:oauth2社交登录
/**
* oauth2配置
*/
@configuration
@enablewebsecurity
public class oauth2securityconfig {
@bean
public securityfilterchain securityfilterchain(httpsecurity http) throws exception {
http
.authorizehttprequests(auth -> auth
.requestmatchers("/", "/login/**", "/oauth2/**").permitall()
.anyrequest().authenticated()
)
.oauth2login(oauth2 -> oauth2
.loginpage("/login")
.userinfoendpoint(userinfo -> userinfo
.userservice(oauth2userservice())
)
.successhandler(oauth2authenticationsuccesshandler())
);
return http.build();
}
@bean
public oauth2userservice<oauth2userrequest, oauth2user> oauth2userservice() {
return new customoauth2userservice();
}
@bean
public authenticationsuccesshandler oauth2authenticationsuccesshandler() {
return new oauth2authenticationsuccesshandler();
}
}
/**
* 自定义oauth2用户服务
*/
public class customoauth2userservice
extends defaultoauth2userservice {
@autowired
private userrepository userrepository;
@override
public oauth2user loaduser(oauth2userrequest userrequest) {
oauth2user oauth2user = super.loaduser(userrequest);
// 处理oauth2用户信息
return processoauth2user(userrequest, oauth2user);
}
private oauth2user processoauth2user(oauth2userrequest userrequest,
oauth2user oauth2user) {
string registrationid = userrequest.getclientregistration()
.getregistrationid();
string email = oauth2user.getattribute("email");
// 查找或创建用户
user user = userrepository.findbyemail(email)
.orelseget(() -> {
user newuser = new user();
newuser.setemail(email);
newuser.setusername(oauth2user.getattribute("name"));
newuser.setenabled(true);
return userrepository.save(newuser);
});
return new customoauth2user(user, oauth2user.getattributes());
}
}
/**
* oauth2成功处理器
*/
public class oauth2authenticationsuccesshandler
extends simpleurlauthenticationsuccesshandler {
@autowired
private jwttokenprovider tokenprovider;
@override
public void onauthenticationsuccess(httpservletrequest request,
httpservletresponse response,
authentication authentication)
throws ioexception {
// 生成jwt token
string token = tokenprovider.generatetoken(authentication);
// 重定向到前端,携带token
string targeturl = "http://localhost:3000/oauth2/redirect?token=" + token;
getredirectstrategy().sendredirect(request, response, targeturl);
}
}6.4 案例4:验证码登录
/**
* 验证码服务
*/
@service
public class captchaservice {
@autowired
private redistemplate<string, string> redistemplate;
/**
* 生成验证码
*/
public string generatecaptcha(string mobile) {
string code = string.format("%06d", new random().nextint(999999));
// 存储到redis,5分钟过期
redistemplate.opsforvalue().set(
"captcha:" + mobile, code, 5, timeunit.minutes
);
// 实际应用中,这里调用短信服务发送验证码
system.out.println("验证码: " + code);
return code;
}
/**
* 验证验证码
*/
public boolean verifycaptcha(string mobile, string code) {
string storedcode = redistemplate.opsforvalue().get("captcha:" + mobile);
return code.equals(storedcode);
}
}
/**
* 验证码认证token
*/
public class captchaauthenticationtoken extends abstractauthenticationtoken {
private final string mobile;
private string captcha;
public captchaauthenticationtoken(string mobile, string captcha) {
super(null);
this.mobile = mobile;
this.captcha = captcha;
setauthenticated(false);
}
public captchaauthenticationtoken(string mobile,
collection<? extends grantedauthority> authorities) {
super(authorities);
this.mobile = mobile;
setauthenticated(true);
}
@override
public object getcredentials() {
return captcha;
}
@override
public object getprincipal() {
return mobile;
}
public string getmobile() {
return mobile;
}
}
/**
* 验证码认证提供者
*/
@component
public class captchaauthenticationprovider implements authenticationprovider {
@autowired
private captchaservice captchaservice;
@autowired
private userdetailsservice userdetailsservice;
@override
public authentication authenticate(authentication authentication)
throws authenticationexception {
captchaauthenticationtoken token = (captchaauthenticationtoken) authentication;
string mobile = token.getmobile();
string captcha = (string) token.getcredentials();
// 验证验证码
if (!captchaservice.verifycaptcha(mobile, captcha)) {
throw new badcredentialsexception("验证码错误");
}
// 加载用户
userdetails user = userdetailsservice.loaduserbyusername(mobile);
return new captchaauthenticationtoken(mobile, user.getauthorities());
}
@override
public boolean supports(class<?> authentication) {
return captchaauthenticationtoken.class.isassignablefrom(authentication);
}
}
/**
* 验证码登录接口
*/
@restcontroller
@requestmapping("/auth")
public class captchaauthcontroller {
@autowired
private captchaservice captchaservice;
@autowired
private authenticationmanager authenticationmanager;
@autowired
private jwttokenprovider jwttokenprovider;
/**
* 发送验证码
*/
@postmapping("/captcha/send")
public responseentity<?> sendcaptcha(@requestparam string mobile) {
captchaservice.generatecaptcha(mobile);
return responseentity.ok("验证码已发送");
}
/**
* 验证码登录
*/
@postmapping("/captcha/login")
public responseentity<?> loginwithcaptcha(@requestbody captchaloginrequest request) {
try {
authentication authentication = authenticationmanager.authenticate(
new captchaauthenticationtoken(request.getmobile(), request.getcaptcha())
);
string token = jwttokenprovider.generatetoken(authentication);
return responseentity.ok(new loginresponse(token, "登录成功"));
} catch (authenticationexception e) {
return responseentity.status(httpstatus.unauthorized)
.body(new errorresponse(e.getmessage()));
}
}
}
@data
class captchaloginrequest {
private string mobile;
private string captcha;
}七、安全最佳实践
7.1 csrf防护
/**
* csrf配置
*/
@configuration
public class csrfconfig {
@bean
public securityfilterchain securityfilterchain(httpsecurity http) throws exception {
http
// 启用csrf保护
.csrf(csrf -> csrf
// 忽略某些url
.ignoringrequestmatchers("/api/**")
// 使用cookie存储token
.csrftokenrepository(cookiecsrftokenrepository.withhttponlyfalse())
);
return http.build();
}
}7.2 密码策略
/**
* 密码编码器配置
*/
@configuration
public class passwordconfig {
/**
* 使用bcrypt编码器
*/
@bean
public passwordencoder passwordencoder() {
return new bcryptpasswordencoder(12); // 强度为12
}
/**
* 密码验证规则
*/
public boolean isvalidpassword(string password) {
// 至少8位
if (password.length() < 8) {
return false;
}
// 包含大写字母、小写字母、数字、特殊字符
string regex = "^(?=.*[a-z])(?=.*[a-z])(?=.*\\d)(?=.*[@$!%*?&])[a-za-z\\d@$!%*?&]{8,}$";
return password.matches(regex);
}
}7.3 会话管理
/**
* 会话管理配置
*/
@configuration
public class sessionconfig {
@bean
public securityfilterchain securityfilterchain(httpsecurity http) throws exception {
http
.sessionmanagement(session -> session
// 会话创建策略
.sessioncreationpolicy(sessioncreationpolicy.if_required)
// 最大会话数
.maximumsessions(1)
// 阻止新会话
.maxsessionspreventslogin(true)
// 会话过期url
.expiredurl("/login?expired")
);
return http.build();
}
}八、总结
核心知识点回顾
spring security核心要点
│
├── 核心概念
│ ├── authentication(认证)
│ ├── authorization(授权)
│ ├── securitycontext(安全上下文)
│ └── filterchain(过滤器链)
│
├── 认证方式
│ ├── 表单登录
│ ├── http basic
│ ├── jwt token
│ ├── oauth2
│ └── 验证码登录
│
├── 授权机制
│ ├── url授权
│ ├── 方法授权
│ ├── 表达式授权
│ └── 自定义权限评估
│
├── 高级特性
│ ├── 多租户隔离
│ ├── 动态权限
│ ├── 社交登录
│ └── 验证码认证
│
└── 最佳实践
├── csrf防护
├── 密码策略
├── 会话管理
└── 安全配置spring security是一个功能强大的安全框架,掌握其核心概念和使用方法对于构建安全的企业级应用至关重要。在实际应用中,需要根据业务需求选择合适的认证和授权策略,并遵循安全最佳实践。
到此这篇关于spring security入门到实战应用的文章就介绍到这了,更多相关spring security使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论