- 浏览: 755061 次
- 性别:
- 来自: 郑州
文章分类
- 全部博客 (396)
- JAVA (50)
- ORACLE (22)
- HIBERNATE (1)
- SPRING (26)
- STRUTS (4)
- OTHERS (0)
- MYSQL (11)
- Struts2 (16)
- JS (33)
- Tomcat (6)
- DWR (1)
- JQuery (26)
- JBoss (0)
- SQL SERVER (0)
- XML (10)
- 生活 (3)
- JSP (11)
- CSS (5)
- word (1)
- MyEclipse (7)
- JSTL (1)
- JEECMS (2)
- Freemarker (8)
- 页面特效 (1)
- EXT (2)
- Web前端 js库 (2)
- JSON http://www.json.org (3)
- 代码收集 (1)
- 电脑常识 (6)
- MD5加密 (0)
- Axis (0)
- Grails (1)
- 浏览器 (1)
- js调试工具 (1)
- WEB前端 (5)
- JDBC (2)
- PowerDesigner (1)
- OperaMasks (1)
- CMS (1)
- Java开源大全 (2)
- 分页 (28)
- Eclipse插件 (1)
- Proxool (1)
- Jad (1)
- Java反编译 (2)
- 报表 (6)
- JSON (14)
- FCKeditor (9)
- SVN (1)
- ACCESS (1)
- 正则表达式 (3)
- 数据库 (1)
- Flex (3)
- pinyin4j (2)
- IBATIS (3)
- probe (1)
- JSP & Servlet (1)
- 飞信 (0)
- AjaxSwing (0)
- AjaxSwing (0)
- Grid相关 (1)
- HTML (5)
- Guice (4)
- Warp framework (1)
- warp-persist (1)
- 服务器推送 (3)
- eclipse (1)
- JForum (5)
- 工具 (1)
- Python (1)
- Ruby (1)
- SVG (3)
- Joda-Time日期时间工具 (1)
- JDK (3)
- Pushlet (2)
- JSP & Servlet & FTP (1)
- FTP (6)
- 时间与效率 (4)
- 二维码 (1)
- 条码/二维码 (1)
最新评论
-
ctrlc:
你这是从web服务器上传到FTP服务器上的吧,能从用户电脑上上 ...
jsp 往 FTP 上传文件问题 -
annybz:
说的好抽象 为什么代码都有两遍。这个感觉没有第一篇 和第二篇 ...
Spring源代码解析(三):Spring JDBC -
annybz:
...
Spring源代码解析(一):IOC容器 -
jie_20:
你确定你有这样配置做过测试? 请不要转载一些自己没有测试的文档 ...
Spring2.0集成iReport报表技术概述 -
asd51731:
大哥,limit传-1时出错啊,怎么修改啊?
mysql limit 使用方法
简单分析一下Spring Acegi的源代码实现:
Servlet.Filter的实现
AuthenticationProcessingFilter启动Web页面的验证过程 -
在AbstractProcessingFilter定义了整个验证过程的模板:
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
- throws IOException, ServletException {
- //这里检验是不是符合ServletRequest /SevletResponse的要求
- if (!(request instanceof HttpServletRequest)) {
- throw new ServletException( "Can only process HttpServletRequest" );
- }
- if (!(response instanceof HttpServletResponse)) {
- throw new ServletException( "Can only process HttpServletResponse" );
- }
- HttpServletRequest httpRequest = (HttpServletRequest) request;
- HttpServletResponse httpResponse = (HttpServletResponse) response;
- //根据HttpServletRequest和 HttpServletResponse来进行验证
- if (requiresAuthentication(httpRequest, httpResponse)) {
- if (logger.isDebugEnabled()) {
- logger.debug( "Request is to process authentication" );
- }
- //这里定义Acegi中的 Authentication对象来持有相关的用户验证信息
- Authentication authResult;
- try {
- onPreAuthentication(httpRequest, httpResponse);
- //这里的具体验证过程委托给子类完成,比如 AuthenticationProcessingFilter来完成基于Web页面的用户验证
- authResult = attemptAuthentication(httpRequest);
- } catch (AuthenticationException failed) {
- // Authentication failed
- unsuccessfulAuthentication(httpRequest, httpResponse, failed);
- return ;
- }
- // Authentication success
- if (continueChainBeforeSuccessfulAuthentication) {
- chain.doFilter(request, response);
- }
- //完成验证后的后续工作,比如跳转到相应的页面
- successfulAuthentication(httpRequest, httpResponse, authResult);
- return ;
- }
- chain.doFilter(request, response);
- }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //这里检验是不是符合ServletRequest/SevletResponse的要求 if (!(request instanceof HttpServletRequest)) { throw new ServletException("Can only process HttpServletRequest"); } if (!(response instanceof HttpServletResponse)) { throw new ServletException("Can only process HttpServletResponse"); } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; //根据HttpServletRequest和HttpServletResponse来进行验证 if (requiresAuthentication(httpRequest, httpResponse)) { if (logger.isDebugEnabled()) { logger.debug("Request is to process authentication"); } //这里定义Acegi中的Authentication对象来持有相关的用户验证信息 Authentication authResult; try { onPreAuthentication(httpRequest, httpResponse); //这里的具体验证过程委托给子类完成,比如AuthenticationProcessingFilter来完成基于Web页面的用户验证 authResult = attemptAuthentication(httpRequest); } catch (AuthenticationException failed) { // Authentication failed unsuccessfulAuthentication(httpRequest, httpResponse, failed); return; } // Authentication success if (continueChainBeforeSuccessfulAuthentication) { chain.doFilter(request, response); } //完成验证后的后续工作,比如跳转到相应的页面 successfulAuthentication(httpRequest, httpResponse, authResult); return; } chain.doFilter(request, response); }
在AuthenticationProcessingFilter中的具体验证过程是这样的:
- public Authentication attemptAuthentication(HttpServletRequest request)
- throws AuthenticationException {
- //这里从HttpServletRequest中得到用户验 证的用户名和密码
- String username = obtainUsername(request);
- String password = obtainPassword(request);
- if (username == null ) {
- username = "" ;
- }
- if (password == null ) {
- password = "" ;
- }
- //这里根据得到的用户名和密码去构造一个 Authentication对象提供给AuthenticationManager进行验证,里面包含了用户的用户名和密码信息
- UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
- // Place the last username attempted into HttpSession for views
- request.getSession().setAttribute(ACEGI_SECURITY_LAST_USERNAME_KEY, username);
- // Allow subclasses to set the "details" property
- setDetails(request, authRequest);
- //这里启动AuthenticationManager进行 验证过程
- return this .getAuthenticationManager().authenticate(authRequest);
- }
public Authentication attemptAuthentication(HttpServletRequest request) throws AuthenticationException { //这里从HttpServletRequest中得到用户验证的用户名和密码 String username = obtainUsername(request); String password = obtainPassword(request); if (username == null) { username = ""; } if (password == null) { password = ""; } //这里根据得到的用户名和密码去构造一个Authentication对象提供给AuthenticationManager进行验证,里面包含了用户的用户名和密码信息 UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); // Place the last username attempted into HttpSession for views request.getSession().setAttribute(ACEGI_SECURITY_LAST_USERNAME_KEY, username); // Allow subclasses to set the "details" property setDetails(request, authRequest); //这里启动AuthenticationManager进行验证过程 return this.getAuthenticationManager().authenticate(authRequest); }
在Acegi框架中,进行验证管理的主要类是AuthenticationManager,我们看看它是怎样进行验证管理的 -
验证的调用入口是authenticate在AbstractAuthenticationManager的实现中:
//这是进行验证的函数,
返回一个Authentication对象来记录验证的结果,其中包含了用户的验证信息,权限配置等,同时这个Authentication会以后被授权
模块使用
- //如果验证失败,那么在验证过程中会直接抛出异常
- public final Authentication authenticate(Authentication authRequest)
- throws AuthenticationException {
- try { //这里是实际的验证处理,我们下面使用ProviderManager来说明具体的验证过程,传入的参数 authRequest里面已经包含了从HttpServletRequest中得到的用户输入的用户名和密码
- Authentication authResult = doAuthentication(authRequest);
- copyDetails(authRequest, authResult);
- return authResult;
- } catch (AuthenticationException e) {
- e.setAuthentication(authRequest);
- throw e;
- }
- }
//如果验证失败,那么在验证过程中会直接抛出异常 public final Authentication authenticate(Authentication authRequest) throws AuthenticationException { try {//这里是实际的验证处理,我们下面使用ProviderManager来说明具体的验证过程,传入的参数authRequest里面已经包含了从HttpServletRequest中得到的用户输入的用户名和密码 Authentication authResult = doAuthentication(authRequest); copyDetails(authRequest, authResult); return authResult; } catch (AuthenticationException e) { e.setAuthentication(authRequest); throw e; } }
在ProviderManager中进行实际的验证工作,假设这里使用数据库来存取用户信息:
- public Authentication doAuthentication(Authentication authentication)
- throws AuthenticationException {
- //这里取得配置好的provider链的迭代器,在配置的时 候可以配置多个provider,这里我们配置的是DaoAuthenticationProvider来说明, 它使用数据库来保存用户的用户名和密码 信息。
- Iterator iter = providers.iterator();
- Class toTest = authentication.getClass();
- AuthenticationException lastException = null ;
- while (iter.hasNext()) {
- AuthenticationProvider provider = (AuthenticationProvider) iter.next();
- if (provider.supports(toTest)) {
- logger.debug( "Authentication attempt using " + provider.getClass().getName());
- //这个result包含了验证中得到的结果 信息
- Authentication result = null ;
- try { //这里是provider进行验证处理的过程
- result = provider.authenticate(authentication);
- sessionController.checkAuthenticationAllowed(result);
- } catch (AuthenticationException ae) {
- lastException = ae;
- result = null ;
- }
- if (result != null ) {
- sessionController.registerSuccessfulAuthentication(result);
- publishEvent( new AuthenticationSuccessEvent(result));
- return result;
- }
- }
- }
- if (lastException == null ) {
- lastException = new ProviderNotFoundException(messages.getMessage( "ProviderManager.providerNotFound" ,
- new Object[] {toTest.getName()}, "No AuthenticationProvider found for {0}" ));
- }
- // 这里发布事件来通知上下文的监听器
- String className = exceptionMappings.getProperty(lastException.getClass().getName());
- AbstractAuthenticationEvent event = null ;
- if (className != null ) {
- try {
- Class clazz = getClass().getClassLoader().loadClass(className);
- Constructor constructor = clazz.getConstructor( new Class[] {
- Authentication. class , AuthenticationException. class
- });
- Object obj = constructor.newInstance( new Object[] {authentication, lastException});
- Assert.isInstanceOf(AbstractAuthenticationEvent. class , obj, "Must be an AbstractAuthenticationEvent" );
- event = (AbstractAuthenticationEvent) obj;
- } catch (ClassNotFoundException ignored) {}
- catch (NoSuchMethodException ignored) {}
- catch (IllegalAccessException ignored) {}
- catch (InstantiationException ignored) {}
- catch (InvocationTargetException ignored) {}
- }
- if (event != null ) {
- publishEvent(event);
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug( "No event was found for the exception " + lastException.getClass().getName());
- }
- }
- // Throw the exception
- throw lastException;
- }
public Authentication doAuthentication(Authentication authentication) throws AuthenticationException { //这里取得配置好的provider链的迭代器,在配置的时候可以配置多个provider,这里我们配置的是DaoAuthenticationProvider来说明, 它使用数据库来保存用户的用户名和密码信息。 Iterator iter = providers.iterator(); Class toTest = authentication.getClass(); AuthenticationException lastException = null; while (iter.hasNext()) { AuthenticationProvider provider = (AuthenticationProvider) iter.next(); if (provider.supports(toTest)) { logger.debug("Authentication attempt using " + provider.getClass().getName()); //这个result包含了验证中得到的结果信息 Authentication result = null; try {//这里是provider进行验证处理的过程 result = provider.authenticate(authentication); sessionController.checkAuthenticationAllowed(result); } catch (AuthenticationException ae) { lastException = ae; result = null; } if (result != null) { sessionController.registerSuccessfulAuthentication(result); publishEvent(new AuthenticationSuccessEvent(result)); return result; } } } if (lastException == null) { lastException = new ProviderNotFoundException(messages.getMessage("ProviderManager.providerNotFound", new Object[] {toTest.getName()}, "No AuthenticationProvider found for {0}")); } // 这里发布事件来通知上下文的监听器 String className = exceptionMappings.getProperty(lastException.getClass().getName()); AbstractAuthenticationEvent event = null; if (className != null) { try { Class clazz = getClass().getClassLoader().loadClass(className); Constructor constructor = clazz.getConstructor(new Class[] { Authentication.class, AuthenticationException.class }); Object obj = constructor.newInstance(new Object[] {authentication, lastException}); Assert.isInstanceOf(AbstractAuthenticationEvent.class, obj, "Must be an AbstractAuthenticationEvent"); event = (AbstractAuthenticationEvent) obj; } catch (ClassNotFoundException ignored) {} catch (NoSuchMethodException ignored) {} catch (IllegalAccessException ignored) {} catch (InstantiationException ignored) {} catch (InvocationTargetException ignored) {} } if (event != null) { publishEvent(event); } else { if (logger.isDebugEnabled()) { logger.debug("No event was found for the exception " + lastException.getClass().getName()); } } // Throw the exception throw lastException; }
我们下面看看在DaoAuthenticationProvider是怎样从数据库中取出对应的验证信息进行用户验证的,在它的基类
AbstractUserDetailsAuthenticationProvider定义了验证的处理模板:
- public Authentication authenticate(Authentication authentication)
- throws AuthenticationException {
- Assert.isInstanceOf(UsernamePasswordAuthenticationToken. class , authentication,
- messages.getMessage( "AbstractUserDetailsAuthenticationProvider.onlySupports" ,
- "Only UsernamePasswordAuthenticationToken is supported" ));
- // 这里取得用户输入的用户名
- String username = (authentication.getPrincipal() == null ) ? "NONE_PROVIDED" : authentication.getName();
- // 如果配置了缓存,从缓存中去取以前存入的用户验证信 息 - 这里是UserDetail,是服务器端存在数据库里的用户信息,这样就不用每次都去数据库中取了
- boolean cacheWasUsed = true ;
- UserDetails user = this .userCache.getUserFromCache(username);
- //没有取到,设置标志位,下面会把这次取到的服务器端用户信 息存入缓存中去
- if (user == null ) {
- cacheWasUsed = false ;
- try { //这里是调用UserDetailService去取用户数据库里信息的地方
- user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
- } catch (UsernameNotFoundException notFound) {
- if (hideUserNotFoundExceptions) {
- throw new BadCredentialsException(messages.getMessage(
- "AbstractUserDetailsAuthenticationProvider.badCredentials" , "Bad credentials" ));
- } else {
- throw notFound;
- }
- }
- Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract" );
- }
- if (!user.isAccountNonLocked()) {
- throw new LockedException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.locked" ,
- "User account is locked" ));
- }
- if (!user.isEnabled()) {
- throw new DisabledException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.disabled" ,
- "User is disabled" ));
- }
- if (!user.isAccountNonExpired()) {
- throw new AccountExpiredException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.expired" ,
- "User account has expired" ));
- }
- // This check must come here, as we don't want to tell users
- // about account status unless they presented the correct credentials
- try { //这里是验证过程,在retrieveUser中从数据库中得到用户的信息,在 additionalAuthenticationChecks中进行对比用户输入和服务器端的用户信息
- //如果验证通过,那么构造一个 Authentication对象来让以后的授权使用,如果验证不通过,直接抛出异常结束鉴权过程
- additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);
- } catch (AuthenticationException exception) {
- if (cacheWasUsed) {
- // There was a problem, so try again after checking
- // we're using latest data (ie not from the cache)
- cacheWasUsed = false ;
- user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
- additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);
- } else {
- throw exception;
- }
- }
- if (!user.isCredentialsNonExpired()) {
- throw new CredentialsExpiredException(messages.getMessage(
- "AbstractUserDetailsAuthenticationProvider.credentialsExpired" , "User credentials have expired" ));
- }
- //根据前面的缓存结果决定是不是要把当前的用户信息存入缓存 以供下次验证使用
- if (!cacheWasUsed) {
- this .userCache.putUserInCache(user);
- }
- Object principalToReturn = user;
- if (forcePrincipalAsString) {
- principalToReturn = user.getUsername();
- }
- //最后返回Authentication记录了验证结果供以 后的授权使用
- return createSuccessAuthentication(principalToReturn, authentication, user);
- }
- //这是是调用UserDetailService去加载服务器端用户信息的地方,从什么地方加载 要看设置,这里我们假设由JdbcDaoImp来从数据中进行加载
- protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
- throws AuthenticationException {
- UserDetails loadedUser;
- //这里调用UserDetailService去从数据库中 加载用户验证信息,同时返回从数据库中返回的信息,这些信息放到了UserDetails对象中去了
- try {
- loadedUser = this .getUserDetailsService().loadUserByUsername(username);
- } catch (DataAccessException repositoryProblem) {
- throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
- }
- if (loadedUser == null ) {
- throw new AuthenticationServiceException(
- "UserDetailsService returned null, which is an interface contract violation" );
- }
- return loadedUser;
- }
public Authentication authenticate(Authentication authentication) throws AuthenticationException { Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported")); // 这里取得用户输入的用户名 String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName(); // 如果配置了缓存,从缓存中去取以前存入的用户验证信息 - 这里是UserDetail,是服务器端存在数据库里的用户信息,这样就不用每次都去数据库中取了 boolean cacheWasUsed = true; UserDetails user = this.userCache.getUserFromCache(username); //没有取到,设置标志位,下面会把这次取到的服务器端用户信息存入缓存中去 if (user == null) { cacheWasUsed = false; try {//这里是调用UserDetailService去取用户数据库里信息的地方 user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication); } catch (UsernameNotFoundException notFound) { if (hideUserNotFoundExceptions) { throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } else { throw notFound; } } Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract"); } if (!user.isAccountNonLocked()) { throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked")); } if (!user.isEnabled()) { throw new DisabledException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled")); } if (!user.isAccountNonExpired()) { throw new AccountExpiredException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired")); } // This check must come here, as we don't want to tell users // about account status unless they presented the correct credentials try {//这里是验证过程,在retrieveUser中从数据库中得到用户的信息,在additionalAuthenticationChecks中进行对比用户输入和服务器端的用户信息 //如果验证通过,那么构造一个Authentication对象来让以后的授权使用,如果验证不通过,直接抛出异常结束鉴权过程 additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication); } catch (AuthenticationException exception) { if (cacheWasUsed) { // There was a problem, so try again after checking // we're using latest data (ie not from the cache) cacheWasUsed = false; user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication); additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication); } else { throw exception; } } if (!user.isCredentialsNonExpired()) { throw new CredentialsExpiredException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.credentialsExpired", "User credentials have expired")); } //根据前面的缓存结果决定是不是要把当前的用户信息存入缓存以供下次验证使用 if (!cacheWasUsed) { this.userCache.putUserInCache(user); } Object principalToReturn = user; if (forcePrincipalAsString) { principalToReturn = user.getUsername(); } //最后返回Authentication记录了验证结果供以后的授权使用 return createSuccessAuthentication(principalToReturn, authentication, user); } //这是是调用UserDetailService去加载服务器端用户信息的地方,从什么地方加载要看设置,这里我们假设由JdbcDaoImp来从数据中进行加载 protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { UserDetails loadedUser; //这里调用UserDetailService去从数据库中加载用户验证信息,同时返回从数据库中返回的信息,这些信息放到了UserDetails对象中去了 try { loadedUser = this.getUserDetailsService().loadUserByUsername(username); } catch (DataAccessException repositoryProblem) { throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } if (loadedUser == null) { throw new AuthenticationServiceException( "UserDetailsService returned null, which is an interface contract violation"); } return loadedUser; }
下面我们重点分析一下JdbcDaoImp这个类来看看具体是怎样从数据库中得到用户信息的:
- public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
- //~ Static fields/initializers =====================================================================================
- //这里是预定义好的对查询语句,对应于默认的数据库表结构, 也可以自己定义查询语句对应特定的用户数据库验证表的设计
- public static final String DEF_USERS_BY_USERNAME_QUERY =
- "SELECT username,password,enabled FROM users WHERE username = ?" ;
- public static final String DEF_AUTHORITIES_BY_USERNAME_QUERY =
- "SELECT username,authority FROM authorities WHERE username = ?" ;
- //~ Instance fields ================================================================================================
- //这里使用Spring JDBC来进行数据库操作
- protected MappingSqlQuery authoritiesByUsernameMapping;
- protected MappingSqlQuery usersByUsernameMapping;
- private String authoritiesByUsernameQuery;
- private String rolePrefix = "" ;
- private String usersByUsernameQuery;
- private boolean usernameBasedPrimaryKey = true ;
- //~ Constructors ===================================================================================================
- //在初始化函数中把查询语句设置为预定义的SQL语句
- public JdbcDaoImpl() {
- usersByUsernameQuery = DEF_USERS_BY_USERNAME_QUERY;
- authoritiesByUsernameQuery = DEF_AUTHORITIES_BY_USERNAME_QUERY;
- }
- //~ Methods ========================================================================================================
- protected void addCustomAuthorities(String username, List authorities) {}
- public String getAuthoritiesByUsernameQuery() {
- return authoritiesByUsernameQuery;
- }
- public String getRolePrefix() {
- return rolePrefix;
- }
- public String getUsersByUsernameQuery() {
- return usersByUsernameQuery;
- }
- protected void initDao() throws ApplicationContextException {
- initMappingSqlQueries();
- }
- /**
- * Extension point to allow other MappingSqlQuery objects to be substituted in a subclass
- */
- protected void initMappingSqlQueries() {
- this .usersByUsernameMapping = new UsersByUsernameMapping(getDataSource());
- this .authoritiesByUsernameMapping = new AuthoritiesByUsernameMapping(getDataSource());
- }
- public boolean isUsernameBasedPrimaryKey() {
- return usernameBasedPrimaryKey;
- }
- //这里是取得数据库用户信息的具体过程
- public UserDetails loadUserByUsername(String username)
- throws UsernameNotFoundException, DataAccessException {
- //根据用户名在用户表中得到用户信息,包括用户名, 密码和用户是否有效的信息
- List users = usersByUsernameMapping.execute(username);
- if (users.size() == 0 ) {
- throw new UsernameNotFoundException( "User not found" );
- }
- //取集合中的第一个作为有效的用户对象
- UserDetails user = (UserDetails) users.get( 0 ); // contains no GrantedAuthority[]
- //这里在权限表中去取得用户的权限信息,同样的返回 一个权限集合对应于这个用户
- List dbAuths = authoritiesByUsernameMapping.execute(user.getUsername());
- addCustomAuthorities(user.getUsername(), dbAuths);
- if (dbAuths.size() == 0 ) {
- throw new UsernameNotFoundException( "User has no GrantedAuthority" );
- }
- //这里根据得到的权限集合来配置返回的User对象 供以后使用
- GrantedAuthority[] arrayAuths = (GrantedAuthority[]) dbAuths.toArray( new GrantedAuthority[dbAuths.size()]);
- String returnUsername = user.getUsername();
- if (!usernameBasedPrimaryKey) {
- returnUsername = username;
- }
- return new User(returnUsername, user.getPassword(), user.isEnabled(), true , true , true , arrayAuths);
- }
- public void setAuthoritiesByUsernameQuery(String queryString) {
- authoritiesByUsernameQuery = queryString;
- }
- public void setRolePrefix(String rolePrefix) {
- this .rolePrefix = rolePrefix;
- }
- public void setUsernameBasedPrimaryKey( boolean usernameBasedPrimaryKey) {
- this .usernameBasedPrimaryKey = usernameBasedPrimaryKey;
- }
- public void setUsersByUsernameQuery(String usersByUsernameQueryString) {
- this .usersByUsernameQuery = usersByUsernameQueryString;
- }
- //~ Inner Classes ==================================================================================================
- /**
- * 这里是调用Spring JDBC的数据库操作,具体可以参考对 JDBC的分析,这个类的作用是把数据库查询得到的记录集合转换为对象集合 - 一个很简单的O/R实现
- */
- protected class AuthoritiesByUsernameMapping extends MappingSqlQuery {
- protected AuthoritiesByUsernameMapping(DataSource ds) {
- super (ds, authoritiesByUsernameQuery);
- declareParameter( new SqlParameter(Types.VARCHAR));
- compile();
- }
- protected Object mapRow(ResultSet rs, int rownum)
- throws SQLException {
- String roleName = rolePrefix + rs.getString( 2 );
- GrantedAuthorityImpl authority = new GrantedAuthorityImpl(roleName);
- return authority;
- }
- }
- /**
- * Query object to look up a user.
- */
- protected class UsersByUsernameMapping extends MappingSqlQuery {
- protected UsersByUsernameMapping(DataSource ds) {
- super (ds, usersByUsernameQuery);
- declareParameter( new SqlParameter(Types.VARCHAR));
- compile();
- }
- protected Object mapRow(ResultSet rs, int rownum)
- throws SQLException {
- String username = rs.getString( 1 );
- String password = rs.getString( 2 );
- boolean enabled = rs.getBoolean( 3 );
- UserDetails user = new User(username, password, enabled, true , true , true ,
- new GrantedAuthority[] { new GrantedAuthorityImpl( "HOLDER" )});
- return user;
- }
- }
- }
public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService { //~ Static fields/initializers ===================================================================================== //这里是预定义好的对查询语句,对应于默认的数据库表结构,也可以自己定义查询语句对应特定的用户数据库验证表的设计 public static final String DEF_USERS_BY_USERNAME_QUERY = "SELECT username,password,enabled FROM users WHERE username = ?"; public static final String DEF_AUTHORITIES_BY_USERNAME_QUERY = "SELECT username,authority FROM authorities WHERE username = ?"; //~ Instance fields ================================================================================================ //这里使用Spring JDBC来进行数据库操作 protected MappingSqlQuery authoritiesByUsernameMapping; protected MappingSqlQuery usersByUsernameMapping; private String authoritiesByUsernameQuery; private String rolePrefix = ""; private String usersByUsernameQuery; private boolean usernameBasedPrimaryKey = true; //~ Constructors =================================================================================================== //在初始化函数中把查询语句设置为预定义的发表评论
-
Spring--quartz中cronExpression配置说明
2011-12-02 18:28 0quartz中cronExpression配置说明 字段 ... -
使用Spring的jdbcTemplate进一步简化JDBC操作
2011-12-02 09:20 1266先看applicationContext.xml配置文件: ... -
Spring MVC:使用SimpleUrlHandlerMapping的一个简单例子
2011-12-01 11:26 967实现一个控制器ShirdrnCon ... -
最简单的Spring MVC入门示例
2010-05-19 14:29 1529应一位朋友的要求,写一个最简单的spring示例,使用s ... -
Spring源代码解析(十):Spring Acegi框架授权的实现
2010-03-18 12:48 1525我们从FilterSecurityIntercep ... -
Spring源代码解析(八):Spring驱动Hibernate的实现
2010-03-18 12:41 1447O/R工具出现之后,简化了许多复杂的信息持久化的开发。Spri ... -
Spring源代码解析(七):Spring AOP中对拦截器调用的实现
2010-03-18 12:40 1422前面我们分析了Spring AOP实现中得到Proxy对象的过 ... -
Spring源代码解析(六):Spring声明式事务处理
2010-03-18 12:37 1098我们看看Spring中的事务处理的代码,使用Spring管理事 ... -
Spring源代码解析(五):Spring AOP获取Proxy
2010-03-18 12:36 1324下面我们来看看Spring的AOP的一些相关代码是怎么得到Pr ... -
Spring源代码解析(四):Spring MVC
2010-03-18 12:35 7744下面我们对Spring MVC框架代码进行分析,对于web ... -
Spring源代码解析(三):Spring JDBC
2010-03-18 12:33 1698下面我们看看Spring JDBC相关的实现, 在Spri ... -
Spring源代码解析(二):IoC容器在Web容器中的启动
2010-03-18 12:32 1449上面我们分析了IOC容器本身的实现,下面我们看看在典型的web ... -
Spring源代码解析(一):IOC容器
2010-03-18 12:30 2673在Spring中,IOC容器的重要地位我们就不多说了,对于Sp ... -
使用Spring的JdbcTemplate和BeanPropertyRowMapper完成的JDBC
2010-03-18 12:08 2248先道要加上两个包:Spring2.5下面的: spring. ... -
使用Spring的SimpleJdbcTemplate完成DAO操作
2010-03-18 12:06 1511l SimpleJdbcTemplate内部包含了 ... -
使用Spring的NamedParameterJdbcTemplate完成DAO操作
2010-03-18 12:05 1428NamedParameterJdbcTemplate内部包含了 ... -
Spring in Action 学习笔记—第四章 征服数据库(转)
2010-03-18 12:03 1255Spring2.0正式版(http://www.springf ... -
Spring管理JDBC连接
2010-03-18 11:59 1692在Spring中,JdbcTemplate是经常被使用的类来帮 ... -
Spring JDBC数据库操作类
2010-03-18 09:26 16461.JdbcTemplate 在Spring中, ... -
Spring JdbcTemplate 批量插入或更新操作
2010-03-18 09:19 5284用 JdbcTemplate 进行批量插入或更新操作 ...
相关推荐
在Spring_Acegi框架鉴权的实现中,我们主要关注的是如何处理用户的登录验证以及在验证成功或失败后系统如何响应。 首先,Spring_Acegi通过实现Servlet的`Filter`接口来介入HTTP请求的生命周期。`...
Spring源代码解析1:IOC容器.doc Spring源代码解析2:IoC容器在Web容器中的启动.doc Spring源代码解析3:...Spring源代码解析9:Spring Acegi框架鉴权的实现.doc Spring源代码解析10:Spring Acegi框架授权的实现.doc
Spring源代码解析1:IOC容器;Spring源代码解析2:IoC容器在Web容器中的启动;Spring源代码解析3:Spring JDBC ;...Spring源代码解析9:Spring Acegi框架鉴权的实现 Spring源代码解析10:Spring Acegi框架授权的实现
Spring源代码解析(一):IOC容器 Spring源代码解析(二):IoC容器在Web容器中的启动 Spring源代码解析(三)...Spring源代码解析(九):Spring Acegi框架鉴权的实现 Spring源代码解析(十):Spring Acegi框架授权的实现
在Spring源代码解析9中,我们关注的是如何实现这个过程,特别是涉及用户账户状态检查和密码验证的部分。这部分代码展示了Spring Acegi如何与数据库交互来获取并验证用户信息。 首先,`Assert.notNull(user, ...
在Spring框架中,Acegi(现在已经并入Spring Security)是一个强大的安全管理组件,它提供了认证和授权功能。在本文中,我们将深入探讨Spring_Acegi框架如何实现授权机制,特别是通过`FilterSecurityInterceptor`来...
Spring源代码解析(一)Spring中的事务处理.doc Spring源代码解析(二):ioc容器在Web容器中的启动....Spring源代码解析(九):Spring Acegi框架鉴权的实现.doc Spring源代码解析(十):Spring Acegi框架授权的实现.doc
7. **Spring Acegi安全框架**:"spring源代码解析(九):Spring Acegi框架鉴权的实现.doc"和"Spring源代码解析(十):Spring Acegi框架授权的实现.doc"介绍了Spring的安全组件,如何实现用户身份验证和权限控制。...
Acegi是一个专门为SpringFramework应用提供安全机制的开放源代码项目,全称为Acegi Security System for Spring,当前版本为 0.8.3。它使用了Spring的方式提供了安全和认证安全服务,包括使用Bean Context,拦截器和...
这篇源代码解析主要关注Spring Acegi中AuthenticationProcessingFilter的实现,它是Web页面验证的核心部分。AuthenticationProcessingFilter是Servlet Filter接口的实现,主要用于在请求到达目标资源之前进行身份...
Acegi框架的这种设计使安全控制变得简单且灵活,能够在不侵入业务代码的情况下实现安全策略。然而,尽管Acegi非常强大,它也有不足之处,如学习曲线较陡峭,配置复杂,对于初学者来说可能较为困难。此外,随着Spring...
本书从源代码的角度对Spring的内核和各个主要功能模块的架构、设计和实现原理进行了深入剖析。你不仅能从本书中参透Spring框架的优秀架构和设计思想,还能从Spring优雅的实现源码中一窥Java语言的精髓。本书在开篇...
《Spring技术内幕:深入解析Spring架构与设计原理(第2版)》从源代码的角度对Spring的内核和各个主要功能模块的架构、设计和实现原理进行了深入剖析。你不仅能从本书中参透Spring框架的出色架构和设计思想,还能从...
Acegi Security基于Spring AOP(面向切面编程)原理,允许开发者通过声明式的方式定义安全策略,无需编写大量的安全代码。它主要由以下组件组成: 1. **AuthenticationManager**: 负责用户身份验证,包括用户名和...
Spring 源代码分析系列涵盖了多个关键模块,包括事务处理、IoC容器、JDBC、MVC、AOP以及与Hibernate和Acegi安全框架的集成。以下是对这些知识点的详细阐述: 1. **Spring 事务处理**:Spring 提供了声明式事务管理...
揭开Spring源代码的神秘面纱,展示系统阅读开源软件源代码的方法和秘诀。 如果你正在思考下面这些问题,也许《Spring技术内幕:深入解析Spring架构与设计原理》就是你想要的! 掌握Spring的架构原理与设计思想...
揭开Spring源代码的神秘面纱,展示系统阅读开源软件源代码的方法和秘诀。 如果你正在思考下面这些问题,也许《Spring技术内幕:深入解析Spring架构与设计原理》就是你想要的! 掌握Spring的架构原理与设计思想...
Spring技术内幕:深入解析Spring架构与设计原理(第2版)》是国内唯一一本系统分析Spring源代码的著作,也是Spring领域的问鼎之作,由业界拥有10余年开发经验的资深Java专家亲自执笔,Java开发者社区和Spring开发者...