SpringSecurity3.1入门教程(四)

一.前言

前面三篇介绍了security,磨刀不误砍柴工,现在就开始上代码吧。本文的项目demo地址可以在文章尾部看到。

二.DEMO

1.web.xml



	
	    org.springframework.web.context.ContextLoaderListener
	
	
	    contextConfigLocation
	    classpath:/resources/spring-security.xml
	
	    
	
		
			org.springframework.web.util.IntrospectorCleanupListener
		
	
	
	
	  
      
            org.springframework.web.util.Log4jConfigListener   
        
  
  
    log4jConfigLocation
    classpath:/resources/log4j.properties
  
  
    log4jRefreshInterval
    6000
  
	
	
  	
		
			org.springframework.security.web.session.HttpSessionEventPublisher 
		
	

	
	
		1
	
	
	
		encodingFilter
		
			org.springframework.web.filter.CharacterEncodingFilter
		
		
			encoding
			UTF-8
		
	
	
		encodingFilter
		/*
	
	
		springSecurityFilterChain
		org.springframework.web.filter.DelegatingFilterProxy
	
	
		springSecurityFilterChain
		/*
	

2.spring-security.xml



    
     
	
        
		   
		 
		
		
		
		
		 
		
        	
   		
   		
   		

   
	
	
		 
		
		
		  
		
		
	

	
		
	             
	
	
	
	
		
			
			
		
	



    





   
    
    
        
            ROLE_ADMIN > ROLE_USER
            ROLE_MANAGER > ROLE_USER
        
    
    

	
	
	
   	
	
	
	
	
	
	  
 	    
    
    
 		 
	

3.UserDetailsService

package com.zsj;

import java.io.IOException;
import java.io.Reader;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class MyUserDetialsService implements UserDetailsService {

	@Override
	public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		UserDetails userDetails=null;
		UserInfo user=null;
		try {
			 user=(UserInfo) findByName(name);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(user==null){
			throw new UsernameNotFoundException("该用户并不存在");
		}else{
			Collection authorities = new ArrayList<>();
			//这里我就直接赋值ROLE_ADMIN了,真正项目是要从数据库获取角色
			authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
			userDetails=new User(user.getUserName(),user.getPassword()+"",authorities);
			System.out.println(userDetails);
		}
		return userDetails;
	}
//为简化项目,直接上恶心的原始mybatis吧,不和spring集成了,这里也可以换成你设计的查找用户的DAO。
 public UserInfo findByName(String name) throws IOException{
	String config="resources/mybatis-config.xml";
	Reader reader=Resources.getResourceAsReader(config);//Resources 类为从类路径中加载资源
	SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
	SqlSession session = sessionFactory.openSession();
	 /**
     * 映射sql的标识字符串,
     * com.dao.DeptDao是deptMapper.xml文件中mapper标签的namespace属性的值,
     * findByDeptNum是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
     */
	String statement = "com.zsj.UserDao.findByUserName";//请注意这里是点分,不是正斜杠
	String param = "zhou";
	UserInfo user = session.selectOne(statement, param);//执行DeptDao中的findByDeptNum方法,方法参数为"D001"
	System.out.println(user.getPassword());
	return user;
}
}

4.login.jsp

<%@page language="java" import="java.util.*" pageEncoding="UTF-8"%>



登录



j_spring_security_check" method="POST">  
用户: 'j_username'>
密码:
记住我

5.运作流程

(1).网址输入http://localhost:8080/TestSecurity

(2)由于security拦截器拦截作用,改请求会被拦截,由于没有登录认证,会被定向到登录页面

(3)登录页面输入账号密码,请求跳转到主页,该请求又被拦截,会拦截器会调用认证管理器,认证供应器来认证用户,认证成功则接着验证授权,认证和授权都通过才可以进入主页

6.结尾

如需项目DEMO的源码,请到下面地址下载:http://download.csdn.net/detail/u012557538/9373827

学习博客:

http://haohaoxuexi.iteye.com/blog/2157769
http://wiki.jikexueyuan.com/project/spring-security/authenticationProvider.html
http://www.mossle.com/docs/auth/html/index.html


你可能感兴趣的:(SpringSecurity)