`
raymond.chen
  • 浏览: 1426575 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

在Springboot2中整合Spring Security安全框架

 
阅读更多

Spring Security框架

为基于Spring的企业应用系统提供声明式的安全訪问控制解决方式的安全框架,应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。

 

1、创建pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.seasy</groupId>
  <artifactId>springmvc-test</artifactId>
  <version>1.0.0</version>
  <packaging>war</packaging>
  
  <parent>
  	<groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-parent</artifactId> 
    <version>2.0.8.RELEASE</version> 
  </parent>

  <properties>
  		<java.version>1.8</java.version>
    	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  
  <dependencies>
    <dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- spring security -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    
	<!-- 解析jsp文件:Springboot内嵌的Tomcat默认不支持jsp -->
	<dependency>
	    <groupId>org.apache.tomcat.embed</groupId>
	    <artifactId>tomcat-embed-jasper</artifactId>
	</dependency>
	<dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>jstl</artifactId>
	</dependency>
	<dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
    </dependency>
	<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
    </dependency>
  </dependencies>
  
  <build>
    <finalName>springboot-test</finalName>
  </build>
</project>

 

2、创建UserDetails实现类

public class UserDetailsImpl implements UserDetails {
	private String username;
	private String password;
	private List<GrantedAuthority> authorities = new ArrayList<>();
	
	public UserDetailsImpl(String username, String password, 
			List<GrantedAuthority> authorities){
		this.username = username;
		this.password = password;
		this.authorities = authorities;
	}
	
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return authorities;
	}

	@Override
	public String getPassword() {
		return password;
	}

	@Override
	public String getUsername() {
		return username;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}
}

 

3、创建UserDetailsService实现类

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
	/**
	 * 根据用户名获取对应的用户信息
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		String password = username;
        
		UserDetailsImpl user 
			= new UserDetailsImpl(username, password, 
					AuthorityUtils.commaSeparatedStringToAuthorityList(username));
		
		return user;
	}	
}

 

4、创建AuthenticationProvider实现类

@Component
public class DefaultAuthenticationProvider implements AuthenticationProvider {
	@Autowired
    private UserDetailsService userDetailsService;
	
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		//登录输入的信息
		String username = (String) authentication.getPrincipal();
		String password = (String) authentication.getCredentials();
		
		//用户信息合法性认证
		UserDetailsImpl userDetails = (UserDetailsImpl) userDetailsService.loadUserByUsername(username);
        if (userDetails == null) {
              throw new UsernameNotFoundException("用户名不存在");
        }
        
        if (!userDetails.getPassword().equals(password)) {
            throw new BadCredentialsException("密码不正确");
        }
        
        //授权信息
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        
        return new UsernamePasswordAuthenticationToken(userDetails, password, authorities);
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return true;
	}
}

 

5、创建WebSecurityConfigurerAdapter类的子类

@Configuration
@EnableWebSecurity(debug=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
	private static final String LOGIN_PAGE = "/login.jsp";
	private static final String LOGIN_FAILURE_PAGE = "/login.jsp?error=Y";
	
	@Autowired
    private AuthenticationProvider provider;

	@Autowired
	private AccessDeniedHandler accessDeniedHandler;
	
	/**
	 * 认证
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		//添加自定义的认证提供者
		auth.authenticationProvider(provider);
	}
	
	/**
	 * 授权
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//permitAll: 表示不登录也可以访问
		//登录
		http.formLogin()
			.loginPage(LOGIN_PAGE)
			.loginProcessingUrl("/login") //要与登录页面的form表单的action值一致
			.failureUrl(LOGIN_FAILURE_PAGE) //登录失败的回调页面
			.defaultSuccessUrl("/main")
			.permitAll();
			
		//授权
		http.authorizeRequests()
			.antMatchers("/static/**", "/js/**", "/css/**", "/images/**").permitAll()
			.antMatchers("/test/**").hasAnyAuthority("test")
			.antMatchers("/admin/**").hasAnyAuthority("admin") //hasAnyAuthority不需要ROLE_前缀
			.anyRequest()
			.authenticated();
		
		//访问拒绝处理器
		http.exceptionHandling()
			.accessDeniedHandler(accessDeniedHandler);
			
		//退出
		http.logout()
			.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
			.logoutSuccessUrl(LOGIN_PAGE)
			.invalidateHttpSession(true)
			.permitAll();
		
		//关闭 跨域伪造请求限制
		http.csrf().disable();
		
		//关闭 跨域资源共享限制
		http.cors().disable();		
	}
	
	/**
	 * 密码编码器
	 */
	@Bean
	public PasswordEncoder passwordEncoder(){
		return new BCryptPasswordEncoder();
	}
}

 

6、访问拒绝处理器

@Component
public class DefaultAccessDeniedHandler implements AccessDeniedHandler {
	private String error403 = "/WEB-INF/views/error403.jsp";
	
	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response,
			AccessDeniedException accessDeniedException) throws IOException, ServletException {
		if (RequestUtil.isAjaxRequest(request)) {
			response.sendError(403);
		} else if (!response.isCommitted()) {
			if(StringUtil.isNotEmpty(error403)){
				//重定向到错误页面
				request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException);
				response.setStatus(HttpServletResponse.SC_FORBIDDEN);
				request.getRequestDispatcher(error403).forward(request, response); 
			}else{
				response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
			}
		}
	}
}

 

7、登录页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>
    <h2>自定义登录页面</h2>
    <form action='<c:url value="/login"/>'  method="post">
        <table>
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" name="password"></td>
            </tr>
            <tr>
                <td colspan="2">
                	<button type="submit">登录</button>
                </td>
            </tr>
        </table>
        
        error=${param.error}<br>
    </form>
</body>
</html>

 

8、403异常页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
    <meta charset="UTF-8">
    <title>error 403</title>
</head>
<body>
	访问出错403:<br>
	
	${requestScope.SPRING_SECURITY_403_EXCEPTION}
</body>
</html>

 

9、登录认证成功后的显示首页

     Controller类

@Controller
public class MainController{
	@GetMapping("/main")
	public String main(){
		return "main";
	}
}

  

    首页main.jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
	首页<br>
	<a href='<c:url value="/logout"/>'>退出</a><br><br>
</body>
</html>

 

10、application.properties属性文件

spring.application.name=springmvc-test

server.port=8888
server.servlet.context-path=/mvctest

#spring mvc
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

 

11、启动类

@SpringBootApplication()
public class Main{
	public static void main(String[] args){
		SpringApplication springApplication = new SpringApplication(Main.class);
		springApplication.run(args);
	}
}

 

分享到:
评论

相关推荐

    SpringBoot2.7整合SpringSecurity+Jwt+Redis+MySQL+MyBatis完整项目代码

    在本项目中,我们主要关注的是SpringBoot 2.7版本与多个技术的深度整合,包括Spring Security、JWT(JSON Web Token)、Redis缓存以及MySQL数据库,并利用MyBatis作为持久层框架。以下是对这些技术及其整合应用的...

    SpringBoot之整合Spring Security代码

    SpringBoot之整合Spring Security,SpringBoot之整合Spring SecuritySpringBoot之整合Spring SecuritySpringBoot之整合Spring Security

    SpringBoot整合权限控制SpringSecurity.docx

    总结来说,SpringBoot整合SpringSecurity提供了全面的权限控制,而Element UI的多标签页组件则优化了前端用户界面,使得在后台管理系统中可以轻松地在多个功能页面之间切换。这种结合使用的方式不仅提升了系统的安全...

    springboot - 2.7.3版本 - (九)整合security

    在Spring Boot项目中整合Spring Security,首先需要在`build.gradle`或`pom.xml`文件中添加Spring Security依赖。对于Spring Boot 2.7.3,依赖应如下所示: ```groovy dependencies { implementation 'org.spring...

    SpringBoot2.6整合SpringSecurity+JWT

    在本文中,我们将深入探讨如何在SpringBoot 2.6版本中整合Spring Security与JSON Web Token(JWT)技术。Spring Security是Spring框架的一个模块,提供了一套强大的安全控制机制,而JWT则是一种轻量级的身份验证和...

    Springboot整合Spring security+Oauth2+JWT搭建认证服务器,网关,微服务之间权限认证及授权

    4. **整合Spring Security与OAuth2**:在Spring Boot中,我们可以使用`spring-security-oauth2-autoconfigure`库来简化OAuth2的配置。通过设置`@EnableAuthorizationServer`和`@EnableResourceServer`注解,分别启动...

    springboot整合springSecurity

    以上是SpringBoot整合SpringSecurity的基础知识要点,实际应用中可能还需要结合具体的业务需求进行更细致的配置和定制。在项目开发中,确保理解并熟练运用这些知识点,能够有效提高应用的安全性和健壮性。

    SpringBoot+SpringSecurity+WebSocket

    在IT行业中,SpringBoot、SpringSecurity和WebSocket是三个非常重要的技术组件,它们分别在应用程序开发、安全管理和实时通信方面发挥着关键作用。本项目结合这三个技术,构建了一个整合的示例,旨在展示如何在...

    springboot+ spring security实现登录认证

    SpringBoot结合Spring Security实现登录认证是企业级应用开发中常见的安全框架组合,它们为Web应用程序提供了强大的安全性。本文将深入探讨这两个技术的核心概念、配置以及如何整合以实现用户登录认证功能。 ...

    springboot springsecurity动态权限控制

    在这个“springboot springsecurity动态权限控制”的主题中,我们将深入探讨如何在Spring Boot项目中集成Spring Security,实现动态权限控制,让菜单权限的管理更加灵活和高效。 首先,我们需要理解Spring Security...

    springboot整合springsecurity小demo

    SpringBoot整合SpringSecurity是一个常见的Java开发任务,它涉及到SpringBoot框架和SpringSecurity的安全管理功能。SpringBoot简化了Spring应用程序的初始设置,而SpringSecurity则提供了一套强大的安全控制方案,...

    springboot+security+cas集成demo

    2. **配置Spring Security**:在Spring Security的配置类中,设置安全策略,例如开启CAS认证,并指定CasAuthenticationFilter和CasAuthenticationEntryPoint。 3. **定义Service Provider**:在CAS服务器上,为...

    SpringSecurity素材.rar

    2. **配置SpringSecurity**:讲解如何在SpringBoot项目中引入SpringSecurity依赖,并配置相应的安全配置类。这通常涉及到定义自定义的`HttpSecurity`配置,比如设置登录页面、未授权页面、CSRF防护等。 3. **用户...

    管理系统系列--基于SpringBoot3,spring Security6,mybatis plus3.5.0的前.zip

    在本项目中,我们探讨的是一个基于最新技术栈构建的管理系统的实现,主要涉及SpringBoot 3、Spring Security 6和MyBatis Plus 3.5.0。这些技术是现代Java开发中的核心组件,用于构建高效、安全且易于维护的企业级...

    springboot+springSecurity的Demo实例

    通过这个Demo,开发者可以学习如何在SpringBoot项目中整合SpringSecurity,理解安全配置的原理,以及如何处理登录、权限控制等常见的安全问题。对于初学者来说,这是一个很好的实践起点,能够帮助他们快速掌握这两个...

    SpringBoot+Mybatis+SpringSecurity+Bootstrap+Layui开发的java web轻量级小巧视频网站系统

    SpringBoot+Mybatis+SpringSecurity+Bootstrap+Layui开发java web轻量级小巧视频网站系统 项目描述 PC端+手机端模式自适应 支持本地资源视频文件上传在线播放,同时支持在线资源链接上传(ed2k、迅雷、等资源)...

    Springboot+SpringSecurity+SpringSession+Redis+Mybatis-Plus+Swwager.zip

    本项目“Springboot+SpringSecurity+SpringSession+Redis+Mybatis-Plus+Swwager”整合了Spring Boot、Spring Security、Spring Session、Redis、Mybatis-Plus以及Swagger等技术,旨在构建一个强大的、安全的、具有...

    SpringBoot+Security+Cas

    这个Demo是为那些希望了解如何在Spring Boot应用中整合Spring Security和CAS(Central Authentication Service)服务的开发者准备的。下面将详细介绍这三个核心组件以及它们如何协同工作。 **Spring Boot** Spring ...

    springboot+security+mybatis+redis+jwt,鉴权框架搭建

    本项目集成了springboot+security+mybatis+redis+jwt用于学习security鉴权功能,其中有集成了redis,mybatis,jasypt,jwt,thymeleaf,knife4j,mybatis-plus 项目搭建已经比较成熟,能够直接进行使用,通过代码...

    SpringBoot集成Spring Security实现权限控制【完整源码+数据库】

    SpringBoot集成Spring Security是现代Java应用中常见的安全框架组合,它们为开发者提供了强大的权限管理和访问控制功能。Spring Security是一个全面的、高度可配置的安全框架,它涵盖了认证、授权以及会话管理等多个...

Global site tag (gtag.js) - Google Analytics