SpringSecurity简单实用

很早之前就学习了解过Spring-Security框架,但是因为做项目使用的是Apache-Shiro框架,所以时间久了也就忘了。这里针对此次学习和总结到的框架的基本知识点进行重点总结,方便以后开发,也希望给你遇到的问题提供一定的帮助。

应用场景

企业级角色权限控制
授权认证Oauth2.0协议
安全防护(防止跨站点请求)
Session攻击
容易整合SpringMVC使用等

首先感谢教给我干活的老师以及网上的朋友们,没有你们,我也不可能好多东西整合那么顺利,谢谢你们的干货。话不多少, 直接上代码。

环境是jdk1.8+springboot2.x进行整合的。

SecuriyConfig

这里是Spring-Security的配置类

package com.burgess.net.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.password.NoOpPasswordEncoder;
import org.springframework.stereotype.Component;

import com.burgess.net.handler.MyAuthenticationFailureHandler;
import com.burgess.net.handler.MyAuthenticationSuccessHandler;

/**
 * 配置类
 * @ClassName:   SecuriyCOnfig  
 * @Description: TODO
 * @author       BurgessLee
 * @date         2019年7月15日  
 *
 */
@SuppressWarnings("deprecation")
@Component
@EnableWebSecurity//必须有
public class SecuriyConfig extends WebSecurityConfigurerAdapter {
	
	//登录认证失败处理的类
	@Autowired
	private MyAuthenticationFailureHandler failureHandler;
	//登录认证成功处理使用的类
	@Autowired
	private MyAuthenticationSuccessHandler successHandler;
	
	//配置认证用户信息权限
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		//对某一个请求针对某一个用户指定权限
		//添加admin用户
		auth.inMemoryAuthentication().withUser("admin").password("123456")
			.authorities("addOrder","showOrder","updateOrder","deleteOrder");
		//添加另外一个用户
		auth.inMemoryAuthentication().withUser("userAdd").password("123456")
			.authorities("showOrder", "addOrder");
		//如果想实现动态账号与数据库进行关联,那么查询数据库就可以了
	}
	
	/**
	 * 实现原理:
	 * 	如何控制权限
	 * 	给每一个请求路径,分配一个权限名称,然后账号只要关联该名称,就可以有访问权限
	 * <p>Title: configure</p>  
	 * <p>Description: </p>  
	 * @param http
	 * @throws Exception  
	 * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
	 */
	//配置拦截请求资源
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//配置使用httpBasic模式拦截所有请求
//		http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();
		//配置使用formLogin模式拦截所有请求
//		http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().formLogin();
		
		//权限控制
		http.authorizeRequests()
			.antMatchers("/showOrder").hasAuthority("showOrder")
			.antMatchers("/addOrder").hasAuthority("addOrder")
			.antMatchers("/updateOrder").hasAuthority("updateOrder")
			.antMatchers("/deleteOrder").hasAuthority("deleteOrder")
			//登录所有请求都可以
			.antMatchers("/login").permitAll()
			.antMatchers("/**").fullyAuthenticated().and().formLogin()
			//自定义更改登录页面
			.loginPage("/login")
			//处理成功或者失败的自定义的handler
			.successHandler(successHandler).failureHandler(failureHandler)
			//禁用csrf攻击,要不然需要token才可以
			.and().csrf().disable();
	}
	
	//!!!!httpBasic模式下需要有下面bean的注入,否则启动项目登录会报错
	@Bean
	public static NoOpPasswordEncoder passwordEncoder() {
		return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
	}
}

MyAuthenticationFailureHandler 

这里是认证失败的时候,会调用方法,具体是通过spring容器注入到对应的拦截方法中的。 

package com.burgess.net.handler;

import java.io.IOException;

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

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

/**
 * 用户登录成功还是失败判断,这个是认证失败的时候的处理类
 * @ClassName:   MyAuthenticationFailureHandler  
 * @Description: TODO
 * @author       BurgessLee
 * @date         2019年7月15日  
 *
 */
//认证失败
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

	public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException auth)
			throws IOException, ServletException {
		System.out.println("登陆失败!");
		res.sendRedirect("http://mayikt.com");

	}

}

MyAuthenticationSuccessHandler

这里是认证成功,然后调用处理的类,这里也是通过Spring容器注入到对应的拦截方法中的。

package com.burgess.net.handler;

import java.io.IOException;

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

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

/**
 * 用户登录成功还是失败判断,这个是认证成功的时候的处理类
 * @ClassName:   MyAuthenticationSuccessHandler  
 * @Description: 认证成功
 * @author       BurgessLee
 * @date         2019年7月15日  
 *
 */
// 认证成功
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication arg2)
			throws IOException, ServletException {
		System.out.println("用户认证成功");
		res.sendRedirect("/");
	}

}

错误处理页面

比如当出现用户权限不足的时候,那么怎么自定义界面的呢?请看下面代码。

WebServerAutoConfiguration 

这个一个配置类,用来重写一些/error页面出现错误的时候具体怎么处理请求,跳转到那个RequestMapping。

package com.burgess.net.config;

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

/**
 * 自定义 WEB 服务器参数 可以配置默认错误页面
 * @ClassName:   WebServerAutoConfiguration  
 * @Description: TODO
 * @author       BurgessLee
 * @date         2019年7月15日  
 *
 */
@Configuration
public class WebServerAutoConfiguration {
	@Bean
	public ConfigurableServletWebServerFactory webServerFactory() {
		TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
		ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400");
		ErrorPage errorPage401 = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401");
		ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, "/error/403");
		ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
		ErrorPage errorPage415 = new ErrorPage(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "/error/415");
		ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
		factory.addErrorPages(errorPage400, errorPage401, errorPage403, errorPage404, errorPage415, errorPage500);
		return factory;
	}
}

ErrorController

这里是自定义一个Error处理的Controller,里面主要写了一个错误请求的处理,也就是当http状态码为403的时候对应的RequestMapping的处理方法。 

package com.burgess.net.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 跳转错误403页面
 * @ClassName:   ErrorController  
 * @Description: TODO
 * @author       BurgessLee
 * @date         2019年7月15日  
 *
 */
@Controller
public class ErrorController {

	// 403权限不足页面
	@RequestMapping("/error/403")
	public String error() {
		return "/error/403";
	}

}

以上就是针对此次Spring-Security基本使用的一些知识点的整理和总结。

最后再次感谢给予我良好引导网友们以及讲师。对于上面整理的内容,如果有什么问题,欢迎留言。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值