Spring Security调研记录【一】--实现基本认证与Url权限控制

Spring Security只通过配置即可实现基于页面的认证与Url权限控制,但默认的实现是从内存或数据库表中获取用户名与密码,如果希望与本公司用户管理系统对接,则需要重新实现UserDetailsService接口。

UserDetailsService仅有一个方法:UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,根据用户名获取用户认证信息与权限信息,以UserDetails对象返回。

      

        具体实现如下所示:


 一、Maven依赖配置(pom.xml)

	
                ...
		4.0.1.RELEASE	
	
        
                ...
                
			org.springframework.security
			spring-security-web
			${org.springframework-security-version}
		
		
			org.springframework.security
			spring-security-config
			${org.springframework-security-version}
		

	


        二、Web.xml配置

	
		springSecurityFilterChain
		org.springframework.web.filter.DelegatingFilterProxy
	

	
		springSecurityFilterChain
		/*
	

三、Spring Context配置



	
	
	
	
		
		
		
		
		
		
		
	

	

	
		
			
		
	
	
	
		
	


四、login.jsp

<%@page contentType="text/html" pageEncoding="UTF-8" isErrorPage="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>




登录


	
	

Invalid username and password.

You have been logged out.

 

 

value="${_csrf.token}" />

五、 UserDetailsService接口实现

public class WinssageUserDetailsService implements UserDetailsService {
	
	
	BCryptPasswordEncoder bcryptPasswordEncoder;
	
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		
		List grantedAuths = new ArrayList();
		grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));

		boolean enables = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		String password=bcryptPasswordEncoder.encode("123456");
		User userdetail = new User(username, password, enables,
				accountNonExpired, credentialsNonExpired, accountNonLocked,
				grantedAuths);
		return userdetail;
	}

	public BCryptPasswordEncoder getBcryptPasswordEncoder() {
		return bcryptPasswordEncoder;
	}

	public void setBcryptPasswordEncoder(BCryptPasswordEncoder bcryptPasswordEncoder) {
		this.bcryptPasswordEncoder = bcryptPasswordEncoder;
	}

}

注:本UserDetailsService接口实现只为做演示作用




你可能感兴趣的:(Spring,Security)