学习若依框架----之----authenticationManager.authenticate()调用UserDetailsServiceImpl.loadUserByUsername过程

 authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));

这个方法会调用UserDetailsServiceImpl.loadUserByUsername,此过程中调用的流程如下:
1. AuthenticationManager是个接口,ProviderManager是他的实现类。
authenticationManager.authenticate()调用其实就是ProviderManager.authenticate()
2. ProviderManager.authenticate()的代码如下:

 public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Class<? extends Authentication> toTest = authentication.getClass();
        AuthenticationException lastException = null;
        AuthenticationException parentException = null;
        Authentication result = null;
        Authentication parentResult = null;
        int currentPosition = 0;
        int size = this.providers.size();
        Iterator var9 = this.getProviders().iterator();

        while(var9.hasNext()) {
            AuthenticationProvider provider = (AuthenticationProvider)var9.next();
            if (provider.supports(toTest)) {
                if (logger.isTraceEnabled()) {
                    Log var10000 = logger;
                    String var10002 = provider.getClass().getSimpleName();
                    ++currentPosition;
                    var10000.trace(LogMessage.format("Authenticating request with %s (%d/%d)", var10002, currentPosition, size));
                }

------注意这里-------
                try {
                    result = provider.authenticate(authentication);
                    if (result != null) {
                        this.copyDetails(authentication, result);
                        break;
                    }
                } catch (InternalAuthenticationServiceException | AccountStatusException var14) {
                    this.prepareException(var14, authentication);
                    throw var14;
                } catch (AuthenticationException var15) {
                    lastException = var15;
                }
            }
        }

        if (result == null && this.parent != null) {
            try {
                parentResult = this.parent.authenticate(authentication);
                result = parentResult;
            } catch (ProviderNotFoundException var12) {
            } catch (AuthenticationException var13) {
                parentException = var13;
                lastException = var13;
            }
        }

        if (result != null) {
            if (this.eraseCredentialsAfterAuthentication && result instanceof CredentialsContainer) {
                ((CredentialsContainer)result).eraseCredentials();
            }

            if (parentResult == null) {
                this.eventPublisher.publishAuthenticationSuccess(result);
            }

            return result;
        } else {
            if (lastException == null) {
                lastException = new ProviderNotFoundException(this.messages.getMessage("ProviderManager.providerNotFound", new Object[]{toTest.getName()}, "No AuthenticationProvider found for {0}"));
            }

            if (parentException == null) {
                this.prepareException((AuthenticationException)lastException, authentication);
            }

            throw lastException;
        }
    }

3. ProviderManager代码中找到provider.authenticate(authentication);
代码中使用 ------注意这里----- 标注了。
4. provider.authenticate(authentication)是AuthenticationProvider.authenticate(authentication)方法。
5. AuthenticationProvider也是一个接口,他的实现类是AbstractUserDetailsAuthenticationProvider。
6. AbstractUserDetailsAuthenticationProvider的子类是DaoAuthenticationProvider。
7. 在DaoAuthenticationProvider中调用了UserDetailsService
代码中使用 ------注意这里----- 标注了。

protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        this.prepareTimingAttackProtection();
---------注意这里-------------
        try {
            UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username);
            if (loadedUser == null) {
                throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
            } else {
                return loadedUser;
            }
        } catch (UsernameNotFoundException var4) {
            this.mitigateAgainstTimingAttack(authentication);
            throw var4;
        } catch (InternalAuthenticationServiceException var5) {
            throw var5;
        } catch (Exception var6) {
            throw new InternalAuthenticationServiceException(var6.getMessage(), var6);
        }
    }

8. UserDetailsService 代码如下:

public interface UserDetailsService {
    UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}

9. 写一个UserDetailsServiceImpl实现类,实现UserDetailsService ,并重写loadUserByUsername()

@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        SysUser user = userService.selectUserByUserName(username);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户:{} 不存在.", username);
            throw new ServiceException("登录用户:" + username + " 不存在");
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录用户:{} 已被删除.", username);
            throw new ServiceException("对不起,您的账号:" + username + " 已被删除");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户:{} 已被停用.", username);
            throw new ServiceException("对不起,您的账号:" + username + " 已停用");
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }

10. 到此结束 。
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));就调用了UserDetailsServiceImpl.loadUserByUsername的方法。
其中的过程想要了解的建议参考AuthenticationManager 验证原理分析AuthenticationManager 的 authentication 过程

  • 14
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
可以使用Spring Security CAS扩展来实现。在pom.xml文件中添加以下依赖项: ``` <dependency> <groupId>org.springframework.security.extensions</groupId> <artifactId>spring-security-cas</artifactId> <version>1.0.7.RELEASE</version> </dependency> ``` 然后在application.properties文件中添加以下配置: ``` # CAS server URL cas.server.url=https://cas.example.com/cas # CAS server login URL cas.server.login.url=https://cas.example.com/cas/login # CAS server logout URL cas.server.logout.url=https://cas.example.com/cas/logout # CAS service URL cas.service.url=http://localhost:8080/login/cas # CAS service name cas.service.name=MyApp # CAS service login URL cas.service.login.url=http://localhost:8080/login # CAS service logout URL cas.service.logout.url=http://localhost:8080/logout # CAS service validate URL cas.service.validate.url=https://cas.example.com/cas/serviceValidate # CAS service ticket parameter name cas.service.ticket.parameterName=ticket # CAS service renew parameter name cas.service.renew.parameterName=renew # CAS service gateway parameter name cas.service.gateway.parameterName=gateway # CAS service artifact parameter name cas.service.artifact.parameterName=artifact # CAS service proxy callback URL cas.service.proxy.callbackUrl=http://localhost:8080/proxyCallback # CAS service proxy callback parameter name cas.service.proxy.callbackParameterName=pgtIou # CAS service proxy granting ticket parameter name cas.service.proxy.grantingTicket.parameterName=pgtIou # CAS service proxy granting ticket storage class cas.service.proxy.grantingTicket.storageClass=org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl # CAS service proxy granting ticket storage file cas.service.proxy.grantingTicket.storageFile=/tmp/cas-proxy-granting-tickets # CAS service proxy granting ticket storage clean interval cas.service.proxy.grantingTicket.storageCleanInterval=3600000 # CAS service proxy granting ticket storage clean up cas.service.proxy.grantingTicket.storageCleanUp=true # CAS service proxy granting ticket storage clean up interval cas.service.proxy.grantingTicket.storageCleanUpInterval=3600000 # CAS service proxy granting ticket storage clean up max age cas.service.proxy.grantingTicket.storageCleanUpMaxAge=7200000 ``` 然后在Spring Boot应用程序中添加以下配置类: ``` @Configuration @EnableWebSecurity @EnableCasSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CasAuthenticationEntryPoint casAuthenticationEntryPoint; @Autowired private CasAuthenticationProvider casAuthenticationProvider; @Autowired private SingleSignOutFilter singleSignOutFilter; @Autowired private CasAuthenticationFilter casAuthenticationFilter; @Autowired private CasProperties casProperties; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .exceptionHandling() .authenticationEntryPoint(casAuthenticationEntryPoint) .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/") .addLogoutHandler(new SingleSignOutHandler(casProperties.getServer().getLogoutUrl())) .and() .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class) .addFilter(casAuthenticationFilter); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(casAuthenticationProvider); } @Bean public ServiceProperties serviceProperties() { ServiceProperties serviceProperties = new ServiceProperties(); serviceProperties.setService(casProperties.getService().getUrl()); serviceProperties.setSendRenew(false); return serviceProperties; } @Bean public CasAuthenticationEntryPoint casAuthenticationEntryPoint() { CasAuthenticationEntryPoint casAuthenticationEntryPoint = new CasAuthenticationEntryPoint(); casAuthenticationEntryPoint.setLoginUrl(casProperties.getServer().getLoginUrl()); casAuthenticationEntryPoint.setServiceProperties(serviceProperties()); return casAuthenticationEntryPoint; } @Bean public CasAuthenticationProvider casAuthenticationProvider() { CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider(); casAuthenticationProvider.setAuthenticationUserDetailsService(new UserDetailsServiceImpl()); casAuthenticationProvider.setServiceProperties(serviceProperties()); casAuthenticationProvider.setTicketValidator(new Cas30ServiceTicketValidator(casProperties.getServer().getUrl())); casAuthenticationProvider.setKey("casAuthenticationProviderKey"); return casAuthenticationProvider; } @Bean public SingleSignOutFilter singleSignOutFilter() { SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); singleSignOutFilter.setCasServerUrlPrefix(casProperties.getServer().getUrl()); singleSignOutFilter.setIgnoreInitConfiguration(true); return singleSignOutFilter; } @Bean public CasAuthenticationFilter casAuthenticationFilter() { CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter(); casAuthenticationFilter.setAuthenticationManager(authenticationManager()); casAuthenticationFilter.setFilterProcessesUrl("/login/cas"); return casAuthenticationFilter; } } ``` 最后,在Spring Boot应用程序中添加以下服务类: ``` @Service public class UserDetailsServiceImpl implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> { @Override public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException { String username = token.getName(); List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER"); return new User(username, "", authorities); } } ``` 现在,您可以使用Spring Boot应用程序调用CAS客户端自动配置支持来解析票据。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XuDream

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值