SpringSecurity认证提供程序示例详解

1.简介

创新互联不只是一家网站建设的网络公司;我们对营销、技术、服务都有自己独特见解,公司采取“创意+综合+营销”一体化的方式为您提供更专业的服务!我们经历的每一步也许不一定是最完美的,但每一步都有值得深思的意义。我们珍视每一份信任,关注我们的网站建设、做网站质量和服务品质,在得到用户满意的同时,也能得到同行业的专业认可,能够为行业创新发展助力。未来将继续专注于技术创新,服务升级,满足企业一站式成都全网营销推广需求,让再小的品牌网站设计也能产生价值!

本教程将介绍如何在Spring Security中设置身份验证提供程序,与使用简单UserDetailsService的标准方案相比,提供了额外的灵活性。

2. The Authentication Provider

Spring Security提供了多种执行身份验证的选项 - 所有这些都遵循简单的规范 - 身份验证请求由Authentication Provider处理,并且返回具有完整凭据的完全身份验证的对象。

标准和最常见的实现是DaoAuthenticationProvider - 它从一个简单的只读用户DAO检索用户详细信息 - UserDetailsService。此UserDetailsService只能访问用户名,用来检索完整的用户实体 - 在很多情况下,这就足够了。

更多常见的场景仍然需要访问完整的身份验证请求才能执行身份验证过程。例如,在针对某些外部第三方服务(例如Crowd)进行身份验证时,将需要来自身份验证请求的用户名和密码。

对于这些更高级的方案,我们需要定义自定义身份验证提供程序:

@Component
public class CustomAuthenticationProvider
 implements AuthenticationProvider {
 
 @Override
 public Authentication authenticate(Authentication authentication) 
  throws AuthenticationException {
 
  String name = authentication.getName();
  String password = authentication.getCredentials().toString();
   
  if (shouldAuthenticateAgainstThirdPartySystem()) {
 
   // use the credentials
   // and authenticate against the third-party system
   return new UsernamePasswordAuthenticationToken(
    name, password, new ArrayList<>());
  } else {
   return null;
  }
 }
 
 @Override
 public boolean supports(Class<?> authentication) {
  return authentication.equals(
   UsernamePasswordAuthenticationToken.class);
 }
}

请注意,在返回的Authentication对象上设置的授予权限是空的 - 这是因为权限当然是特定于应用程序的。

3.注册Authentication Provider

既然定义了身份验证提供程序,我们需要使用可用的命名空间支持在XML安全配置中指定它:

<?xml version="1.0" encoding="UTF-8"?>

 
 
  
  
 
 
 
  
 
 

4. Java Configuration

接下来,我们来看看相应的Java配置:

@Configuration
@EnableWebSecurity
@ComponentScan("org.baeldung.security")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
 @Autowired
 private CustomAuthenticationProvider authProvider;
 
 @Override
 protected void configure(
  AuthenticationManagerBuilder auth) throws Exception {
 
  auth.authenticationProvider(authProvider);
 }
 
 @Override
 protected void configure(HttpSecurity http) throws Exception {
  http.authorizeRequests().anyRequest().authenticated()
   .and()
   .httpBasic();
 }
}

5. 测试认证

无论是否在后端使用此自定义身份验证提供程序,从客户端请求身份验证基本相同 - 我们可以使用简单的curl命令发送经过身份验证的请求:

curl --header "Accept:application/json" -i --user user1:user1Pass 
 http://localhost:8080/spring-security-custom/api/foo/1

请注意 - 出于本示例的目的 - 我们已使用基本身份验证保护REST API。

我们从服务器返回预期的200 OK

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=B8F0EFA81B78DE968088EBB9AFD85A60; Path=/spring-security-custom/; HttpOnly
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sun, 02 Jun 2013 17:50:40 GMT

六,总结

在本文中,我们讨论了Spring Security的自定义身份验证提供程序的示例。

可以在GitHub项目中找到本教程的完整实现 - 这是一个基于Maven的项目,因此它应该很容易导入和运行。

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对创新互联的支持。


分享题目:SpringSecurity认证提供程序示例详解
标题网址:http://myzitong.com/article/igpchc.html