Spring Security是如何完成身份认证的?

1 用户名和密码被过滤器获取到,封装成Authentication,通常情况下是UsernamePasswordAuthenticationToken这个实现类。

2 AuthenticationManager 身份管理器负责验证这个Authentication

3 认证成功后,AuthenticationManager身份管理器返回一个被填充满了信息的(包括上面提到的权限信息,身份信息,细节信息,但密码通常会被移除)Authentication实例。

4 SecurityContextHolder安全上下文容器将第3步填充了信息的Authentication,通过SecurityContextHolder.getContext().setAuthentication(…)方法,设置到其中。

这是一个抽象的认证流程,而整个过程中,如果不纠结于细节,其实只剩下一个AuthenticationManager 是我们没有接触过的了,这个身份管理器我们在后面的小节介绍。将上述的流程转换成代码,便是如下的流程:

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 AuthenticationException {
	if (auth.getName().equals(auth.getCredentials())) {
	return new UsernamePasswordAuthenticationToken(auth.getName(),
		auth.getCredentials(), AUTHORITIES);
	}
	throw new BadCredentialsException("Bad Credentials");
}
}

注意:上述这段代码只是为了让大家了解Spring Security的工作流程而写的,不是什么源码。在实际使用中,整个流程会变得更加的复杂,但是基本思想,和上述代码如出一辙。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security是一个功能强大的框架,用于在Spring Boot应用程序中实现用户认证和授权管理。以下是实现用户认证的一般步骤: 1. 添加Spring Security依赖:在项目的pom.xml文件中添加Spring Security的依赖项。 2. 创建用户实体类:创建一个用户实体类,用于存储用户的身份验证信息,例如用户名和密码。 3. 创建用户存储库:创建一个用户存储库接口,用于从数据库或其他数据源中检索用户信息。 4. 实现用户服务:创建一个用户服务类,实现UserDetailsService接口,并重写loadUserByUsername方法,用于根据用户名从用户存储库中获取用户信息。 5. 配置Spring Security:创建一个配置类,继承WebSecurityConfigurerAdapter,并重写configure方法,用于配置Spring Security的行为。 6. 配置用户认证:在configure方法中,使用AuthenticationManagerBuilder配置用户认证方式,例如使用内存存储、数据库存储或自定义认证方式。 7. 配置登录页面:在configure方法中,使用formLogin方法配置登录页面的URL和登录成功后的跳转URL。 8. 配置访问控制:在configure方法中,使用authorizeRequests方法配置不同URL路径的访问权限,例如需要认证才能访问的URL和不需要认证的URL。 9. 实现自定义登录页面:如果需要自定义登录页面,可以创建一个登录页面的控制器,并在configure方法中使用loginPage方法配置自定义登录页面的URL。 10. 实现自定义认证成功处理器:如果需要在认证成功后执行一些自定义操作,可以创建一个认证成功处理器,并在configure方法中使用successHandler方法配置自定义认证成功处理器。 11. 实现自定义认证失败处理器:如果需要在认证失败后执行一些自定义操作,可以创建一个认证失败处理器,并在configure方法中使用failureHandler方法配置自定义认证失败处理器。 以下是一个示例代码,演示了如何使用Spring Security实现用户认证: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasAnyRole("ADMIN", "USER") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home") .permitAll() .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/login") .permitAll(); } } ``` 请注意,上述代码只是一个示例,实际的配置可能因应用程序的需求而有所不同。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值