Spring Security 实现身份认证

本文详细介绍了Spring Security的身份认证过程,包括用户登录、验证、建立安全上下文等步骤,并探讨了在Web应用中实现身份认证的具体流程和关键组件,如ExceptionTranslationFilter、AuthenticationEntryPoint和AuthenticationManager的作用。同时,解释了在不同应用场景下如何在请求间保存SecurityContext。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   Spring Security可以运行在不同的身份认证环境中,当我们推荐用户使用Spring Security进行身份认证但并不推荐集成到容器管理的身份认证中时,但当你集成到自己的身份认证系统时,它依然是支持的。


    1. Spring Security中的身份认证是什么?


    现在让我们考虑一下每个人都熟悉的标准身份认证场景:


    (1)用户打算使用用户名和密码登陆系统


    (2)系统验证用户名和密码合法


    (3)得到用户信息的上下文(角色等信息)


    (4)为用户建立一个安全上下文


    (5)用户接下来可能执行一些权限访问机制下的受保护的操作,检查与当前安全上下文有关的必须的权限


    上面前三步是身份认证的过程,接下来看看身份认证的详细过程:


    (1)用户名和密码获得之后组合成 UsernamePasswordAuthenticationToken 的实例(前文讨论过的Authentication接口的实例)


    (2)将该令牌传递给 AuthenticationManager 实例进行验证


    (3)验证成功后,AuthenticationManager 会返回填充好的 Authentication 实例


    (4)通过调用 SecurityContextHolder.getContext().setAuthentication(...) 建立安全上下文的实例,传递到返回的身份认证对象上


    下面是进行身份认证的代码片段:

import org.springframework.security.authentication.*;
import org.springframework.security.core.*;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

public class AuthenticationExample {

private static AuthenticationManager am = new SampleAuthenticationManager();

public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(true) {
System.out.println("Please enter your username:");
String name = in.readLine();
System.out.println("Please enter your password:");
String password = in.readLine();
try {
Authentication request = new UsernamePasswordAuthenticationToken(name, password);
Authentication result = am.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
break;
} catch(AuthenticationException e) {
System.out.println("Authentication failed: " + e.getMessage());
}
}
System.out.println("Successfully authenticated. Security context contains: " +
SecurityContextHolder.getContext().getAuthentication());
}
}

class SampleAuthenticationManager implements AuthenticationManager {

static final List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();

static {
AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
}

public Authentication authenticate(Authentication auth) throws

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值