ssm框架整合spring security思路与过程

ssm框架整合spring security思路

1.拷贝spring security 依赖到parent管理

<!-- spring-security依赖 -->
		<spring-security.version>4.2.10.RELEASE</spring-security.version>
<!-- spring-security依赖包 -->
			<dependency>
				<groupId>org.springframework.security</groupId>
				<artifactId>spring-security-web</artifactId>
				<version>${spring-security.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework.security</groupId>
				<artifactId>spring-security-config</artifactId>
				<version>${spring-security.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework.security</groupId>
				<artifactId>spring-security-taglibs</artifactId>
				<version>${spring-security.version}</version>
			</dependency>

2.在service 加入无版本的依赖

<!-- spring-security依赖包 -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
		</dependency>

3.web.xml加入spring security过滤器

<!-- springSecurity过滤器 -->
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

			整合的时候遇到的问题
No bean named 'springSecurityFilterChain' available//原因就是spring扫描的时候扫描不到

4.编写config文件//被spring扫描

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.access.AccessDeniedHandler;

@Configuration//把该类当成一个xml文件
@EnableWebSecurity//启用spring-security
//开启细粒度
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class AtcrowdfundingSecurityConfig extends WebSecurityConfigurerAdapter{
	@Autowired
	private UserDetailsService userDetailsService;
	
	//认证和授权	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		//基于数据库认证
		auth.userDetailsService(userDetailsService);
	}
	//配置信息
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
		//放开一些资源
		.antMatchers("/static/**","welcome.jsp","/login").permitAll()
		.anyRequest().authenticated();
		//修改登录配置信息
		http.formLogin()
		.loginPage("/login")
		.usernameParameter("loginacct")
		.passwordParameter("userpswd")
		.loginProcessingUrl("/doLogin")
		.defaultSuccessUrl("/main");
		//禁用跨站请求伪造
		http.csrf().disable();
		//权限不够时做出的相应
		http.exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() {
			
			@Override
			public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
				String header = request.getHeader("X-Requested-With");
				//异步
				if("XMLHttpRequest".equals(header)) {
					response.getWriter().print("403");
				}else {
					request.getRequestDispatcher("/WEB-INF/jsp/admin/error403.jsp").forward(request, response);
				}
			}
		});
		
	}
	
}

5.配置开发资源(已经写在了步骤4中)
6.配置登录信息(已经写在了步骤4中)
7.禁用SCRF(已经写在了步骤4中)
8.认证和授权(已经写在了步骤4中)

	// 登录时打印异常的
${SPRING_SECURITY_LAST_EXCEPTION.message}
实现UserDetailsService 接口,这是才是真正执行认证和授权
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
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;
import org.springframework.stereotype.Component;

import com.atguigu.atcrowdfunding.bean.TAdmin;
import com.atguigu.atcrowdfunding.bean.TAdminExample;
import com.atguigu.atcrowdfunding.bean.TPermission;
import com.atguigu.atcrowdfunding.bean.TRole;
import com.atguigu.atcrowdfunding.mapper.TAdminMapper;
import com.atguigu.atcrowdfunding.mapper.TPermissionMapper;
import com.atguigu.atcrowdfunding.mapper.TRoleMapper;

@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {
	@Autowired
	private TAdminMapper adminMapper;
	@Autowired
	private TRoleMapper roleMapper;
	@Autowired
	private TPermissionMapper permissionMapper;
	
	//真正执行认证和授权
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		TAdminExample example = new TAdminExample();
		example.createCriteria().andLoginacctEqualTo(username);
		List<TAdmin> admins = adminMapper.selectByExample(example);
		//有该账号
		TAdmin admin=null;
		if(admins!=null&&admins.size()==1) {
			admin = admins.get(0);
		}
		//查询用户拥有的角色
		List<TRole> roles = roleMapper.queryRoleByAdminId(admin.getId());
		//查询用户拥有的权限
		List<TPermission> permissions = permissionMapper.queryPermissionByAdminId(admin.getId());
		Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
		for (TRole role : roles) {
			authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
		}//SimpleGrantedAuthority干嘛的,待探索!!!
		for (TPermission permission : permissions) {
			authorities.add(new SimpleGrantedAuthority(permission.getName()));
		}
		return new User(admin.getLoginacct(), admin.getUserpswd(), authorities);
	}

}

9.回显用户名:

1.先加入标签
<%@taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
2.然后在回显的地方写上
<security:authentication property="name"/>

10.细粒度控制权限

//在配置文件当中开启细粒度
@EnableGlobalMethodSecurity(prePostEnabled=true)
//在controller的相应方法中添加上
@PreAuthorize("hasRole('PM-项目经理') AND hasAuthority('user:add')") 
//会出现问题,因为配置文件被springmvc扫描,而相应方法被sping扫描,然后我们需要都被springmvc扫描,步骤如下:
1.注销sping Ioc容器,
<!-- 创建Spring IOC容器 -->
	<!-- needed for ContextLoaderListener -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:/spring/spring-*.xml</param-value>
	</context-param>

	<!-- Bootstraps the root web application context before servlet initialization -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	2.将spring的配置文件交给springmvc
	<!-- 核心控制器 -->
	<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
			classpath*:/spring/springmvc.xml
			classpath*:/spring/spring-*.xml
			</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值