Spring Secuirty与SSH整合

项目下载:点击下载

maven项目下载:点击下载

项目说明: Spring Security+SSH,通过数据库给用户授权认证


spring Security配置文件

spring-security.xml配置如下:



    
    
    
    
    
    
    
        
        
        
        
        
    
    
        
    
    
        
    
    
        
    

说明:

authentication-manager需要authencation-provider提供支持验证,不清楚的可以参考如下文章:http://wiki.jikexueyuan.com/project/spring-security/authenticationProvider.html

通过自己实现自己实现的UserDetaisServiceImpl类,需要实现UserDetailsService  接口,并实现其loadUserByUsername方法,来处理用户认证.

UserDetaisServiceImpl类代码如下:

package com.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.dao.UserDetailsDaoImpl;
import com.pojo.Role;
import com.pojo.User;

public class UserDetaisServiceImpl implements UserDetailsService {
	private UserDetailsDaoImpl userDetailsDaoImpl;

	public UserDetailsDaoImpl getUserDetailsDaoImpl() {
		return userDetailsDaoImpl;
	}

	public void setUserDetailsDaoImpl(UserDetailsDaoImpl userDetailsDaoImpl) {
		this.userDetailsDaoImpl = userDetailsDaoImpl;
	}

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		User user = userDetailsDaoImpl.findUser(username);
		List authorities = null;
		if (user != null) {
			authorities = buildUserAuthority(user.getRoles());
			return new org.springframework.security.core.userdetails.User(
					user.getUsername(), user.getPassword(), authorities);
		}
		return null;
	}

	// 获取用户权限并转换成spring security能处理的权限类
	private List buildUserAuthority(Set roles) {
		List authorities = new ArrayList();
		for (Role role : roles) {
			authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
		}
		return authorities;
	}

}

Action处理类

主要处理业务方法如下:

	public void login() {
		try {
			UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
					username, password);
			// 认证验证,内部会调用 UserDetailsServiceImpl.loadUserByUsername()验证
			Authentication authentication = authenticationManager
					.authenticate(token);
			SecurityContextHolder.getContext()
					.setAuthentication(authentication);
			this.getSession().setAttribute("SPRING_SECURITY_CONTEXT",
					SecurityContextHolder.getContext());
			this.getOut().print("success");
		} catch (Exception e) {
			e.printStackTrace();
			this.getOut().print("error");
		}
	}
首先理解这段代码,我们要先知道认证过程,可以参考如下文章:http://wiki.jikexueyuan.com/project/spring-security/certification.html

UsernamePasswordAuthenticationToken 封装username和password,然后通过 authenticationManager认证授权得到新的Authentication对象,并保存到SecurityContext中,将SecurityContext保存到session中即可完成认证。

你可能感兴趣的:(web后端,ssh,Spring,security,mavn)