org.springframework.security.authentication.AuthenticationManager.authenticate()方法的使用及代码示例

x33g5p2x  于2022-01-15 转载在 其他  
字(12.9k)|赞(0)|评价(0)|浏览(474)

本文整理了Java中org.springframework.security.authentication.AuthenticationManager.authenticate()方法的一些代码示例,展示了AuthenticationManager.authenticate()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。AuthenticationManager.authenticate()方法的具体详情如下:
包路径:org.springframework.security.authentication.AuthenticationManager
类名称:AuthenticationManager
方法名:authenticate

AuthenticationManager.authenticate介绍

[英]Attempts to authenticate the passed Authentication object, returning a fully populated Authentication object (including granted authorities) if successful.

An AuthenticationManager must honour the following contract concerning exceptions:

  • A DisabledException must be thrown if an account is disabled and the AuthenticationManager can test for this state.
  • A LockedException must be thrown if an account is locked and the AuthenticationManager can test for account locking.
  • A BadCredentialsException must be thrown if incorrect credentials are presented. Whilst the above exceptions are optional, an AuthenticationManager must always test credentials.
    Exceptions should be tested for and if applicable thrown in the order expressed above (i.e. if an account is disabled or locked, the authentication request is immediately rejected and the credentials testing process is not performed). This prevents credentials being tested against disabled or locked accounts.
    [中]尝试对传递的身份验证对象进行身份验证,如果成功,则返回完全填充的Authentication对象(包括授予的权限)。
    AuthenticationManager必须遵守以下有关例外情况的合同:
    *如果帐户被禁用并且AuthenticationManager可以测试此状态,则必须抛出DisabledException。
    *如果帐户被锁定,AuthenticationManager可以测试帐户锁定,则必须抛出LockedException。
    *如果提供了不正确的凭据,则必须引发BadCredentialsException。尽管上述例外情况是可选的,AuthenticationManager必须始终测试凭据。
    应测试异常,如果适用,应按照上述顺序抛出异常(即,如果帐户被禁用或锁定,则会立即拒绝身份验证请求,并且不会执行凭据测试过程)。这将防止针对禁用或锁定的帐户测试凭据。

代码示例

代码示例来源:origin: weibocom/motan

@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public TokenTransfer authenticate(@RequestParam("username") String username, @RequestParam("password") String password) {
  UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
  Authentication authentication = authManager.authenticate(authenticationToken);
  SecurityContextHolder.getContext().setAuthentication(authentication);
  UserDetails userDetails = userDetailsService.loadUserByUsername(username);
  return new TokenTransfer(TokenUtils.createToken(userDetails));
}

代码示例来源:origin: spring-projects/spring-security

public Collection<? extends GrantedAuthority> attemptAuthentication(String username,
    String password) throws RemoteAuthenticationException {
  UsernamePasswordAuthenticationToken request = new UsernamePasswordAuthenticationToken(
      username, password);
  try {
    return authenticationManager.authenticate(request).getAuthorities();
  }
  catch (AuthenticationException authEx) {
    throw new RemoteAuthenticationException(authEx.getMessage());
  }
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void authenticateWhenSuccessThenSucces() {
  when(delegate.authenticate(any())).thenReturn(authentication);
  when(authentication.isAuthenticated()).thenReturn(true);
  Authentication result = manager.authenticate(authentication).block();
  assertThat(result).isEqualTo(authentication);
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void authenticationEventPublisherBeanUsedByDefault() {
  this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
  assertThat(this.listener.getEvents()).hasSize(1);
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void authenticateWhenReturnNotAuthenticatedThenError() {
  when(delegate.authenticate(any())).thenReturn(authentication);
  Authentication result = manager.authenticate(authentication).block();
  assertThat(result).isNull();
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void delegateUsesExisitingAuthentication() {
  String username = "user";
  String password = "password";
  when(this.uds.loadUserByUsername(username)).thenReturn(PasswordEncodedUser.user());
  AuthenticationManager authenticationManager = this.adapter.authenticationManager;
  assertThat(authenticationManager).isNotNull();
  Authentication auth = authenticationManager.authenticate(
      new UsernamePasswordAuthenticationToken(username, password));
  verify(this.uds).loadUserByUsername(username);
  assertThat(auth.getPrincipal()).isEqualTo(PasswordEncodedUser.user());
}

代码示例来源:origin: spring-projects/spring-security

@Test(expected = RemoteAuthenticationException.class)
public void testFailedAuthenticationReturnsRemoteAuthenticationException() {
  RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl();
  AuthenticationManager am = mock(AuthenticationManager.class);
  when(am.authenticate(any(Authentication.class))).thenThrow(
      new BadCredentialsException(""));
  manager.setAuthenticationManager(am);
  manager.attemptAuthentication("rod", "password");
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void getAuthenticationWhenAuthenticationManagerBeanThenAuthenticates() throws Exception {
  UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
  this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class, AuthenticationManagerBeanConfig.class).autowire();
  AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
  when(authentication.authenticate(token)).thenReturn(TestAuthentication.authenticatedUser());
  assertThat(authentication.authenticate(token).getName()).isEqualTo(token.getName());
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void getAuthenticationWhenUserDetailsServiceBeanThenAuthenticationManagerUsesUserDetailsServiceBean() throws Exception {
  this.spring.register(UserDetailsServiceBeanConfig.class).autowire();
  UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class);
  AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
  when(uds.loadUserByUsername("user")).thenReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user());
  am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
  assertThatThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")))
    .isInstanceOf(AuthenticationException.class);
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void getAuthenticationWhenConfiguredThenBootNotTrigger() throws Exception {
  this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class).autowire();
  AuthenticationConfiguration config = this.spring.getContext().getBean(AuthenticationConfiguration.class);
  config.setGlobalAuthenticationConfigurers(Arrays.asList(new ConfiguresInMemoryConfigurerAdapter(), new BootGlobalAuthenticationConfigurerAdapter()));
  AuthenticationManager authenticationManager = config.getAuthenticationManager();
  authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
  assertThatThrownBy(() -> authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("boot", "password")))
    .isInstanceOf(AuthenticationException.class);
}

代码示例来源:origin: spring-projects/spring-security

private void setUpAuthenticationResult(ClientRegistration registration) {
    OAuth2AuthorizationCodeAuthenticationToken authentication =
        new OAuth2AuthorizationCodeAuthenticationToken(registration, success(), noScopes(), refreshToken());
    when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authentication);
  }
}

代码示例来源:origin: spring-projects/spring-security

@Test    // http@authentication-manager-ref
public void configureWhenAuthenticationManagerProvidedThenVerifyUse() throws Exception {
  AuthenticationManagerRefConfig.AUTHENTICATION_MANAGER = mock(AuthenticationManager.class);
  this.spring.register(AuthenticationManagerRefConfig.class).autowire();
  this.mockMvc.perform(formLogin());
  verify(AuthenticationManagerRefConfig.AUTHENTICATION_MANAGER, times(1)).authenticate(any(Authentication.class));
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void getAuthenticationManagerWhenProtectedPasswordEncoderBeanThenUsed() throws Exception {
  this.spring.register(PasswordEncoderGlobalConfig.class).autowire();
  AuthenticationManager manager = this.spring.getContext()
    .getBean(AuthenticationConfiguration.class).getAuthenticationManager();
  Authentication auth = manager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
  assertThat(auth.getName()).isEqualTo("user");
  assertThat(auth.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsOnly("ROLE_USER");
}

代码示例来源:origin: spring-projects/spring-security

@Test
  public void testSuccessfulAuthentication() {
    RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl();
    AuthenticationManager am = mock(AuthenticationManager.class);
    when(am.authenticate(any(Authentication.class))).thenReturn(
        new TestingAuthenticationToken("u", "p", "A"));
    manager.setAuthenticationManager(am);

    manager.attemptAuthentication("rod", "password");
  }
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void isSupportedByAuthenticationProviderElement() {
  setContext("<authentication-manager>" + "  <authentication-provider>"
      + "    <jdbc-user-service data-source-ref='dataSource'/>"
      + "  </authentication-provider>" + "</authentication-manager>"
      + DATA_SOURCE);
  AuthenticationManager mgr = (AuthenticationManager) appContext
      .getBean(BeanIds.AUTHENTICATION_MANAGER);
  mgr.authenticate(new UsernamePasswordAuthenticationToken("rod", "koala"));
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void configureWhenOverrideAuthenticationManagerBeanThenAuthenticationManagerBeanRegistered() throws Exception {
  this.spring.register(SecurityConfig.class).autowire();
  AuthenticationManager authenticationManager = this.spring.getContext().getBean(AuthenticationManager.class);
  Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
  assertThat(authentication.isAuthenticated()).isTrue();
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void getAuthenticationWhenGlobalAuthenticationConfigurerAdapterThenAuthenticates() throws Exception {
  UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
  this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class, UserGlobalAuthenticationConfigurerAdapter.class).autowire();
  AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
  assertThat(authentication.authenticate(token).getName()).isEqualTo(token.getName());
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void getAuthenticationWhenAuthenticationProviderAndUserDetailsBeanThenAuthenticationProviderUsed() throws Exception {
  this.spring.register(AuthenticationProviderBeanAndUserDetailsServiceConfig.class).autowire();
  AuthenticationProvider ap = this.spring.getContext().getBean(AuthenticationProvider.class);
  AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
  when(ap.supports(any())).thenReturn(true);
  when(ap.authenticate(any())).thenReturn(TestAuthentication.authenticatedUser());
  am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void getAuthenticationWhenUserDetailsServiceAndPasswordManagerThenManagerUsed() throws Exception {
  UserDetails user = new User("user", "{noop}password",
      AuthorityUtils.createAuthorityList("ROLE_USER"));
  this.spring.register(UserDetailsPasswordManagerBeanConfig.class).autowire();
  UserDetailsPasswordManagerBeanConfig.Manager manager = this.spring.getContext().getBean(UserDetailsPasswordManagerBeanConfig.Manager.class);
  AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
  when(manager.loadUserByUsername("user")).thenReturn(User.withUserDetails(user).build(), User.withUserDetails(user).build());
  when(manager.updatePassword(any(), any())).thenReturn(user);
  am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
  verify(manager).updatePassword(eq(user), startsWith("{bcrypt}"));
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void methodSecurityAuthenticationManagerPublishesEvent() {
  this.spring.register(InMemoryAuthWithGlobalMethodSecurityConfig.class).autowire();
  try {
    this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("foo", "bar"));
  } catch(AuthenticationException e) {}
  assertThat(this.events.getEvents()).extracting(Object::getClass).containsOnly((Class) AuthenticationFailureBadCredentialsEvent.class);
}

相关文章

微信公众号

最新文章

更多

AuthenticationManager类方法