赞
踩
Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。
它是用于保护基于Spring的应用程序的实际标准。
Spring Security是一个框架,致力于为Java应用程序提供身份验证和授权。
与所有Spring项目一样,Spring Security的真正强大之处在于可以轻松扩展以满足自定义要求
springboot对于springSecurity提供了自动化配置方案,可以使用更少的配置来使用springsecurity
而在项目开发中,主要用于对用户的认证和授权
官网:https://spring.io/projects/spring-security
Apache Shiro是一个强大且易用的Java安全框架,能够非常清晰的处理身份验证、授权、管理会话以及密码加密。
利用其易于理解的API,可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。
Shiro 主要分为两个部分就是认证和授权,就是查询数据库做相应的判断,Shiro是一个框架,其中的内容需要自己的去构建,前后是自己的,中间是Shiro帮我们去搭建和配置好的。
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。
它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC(控制反转),DI( 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
众所周知,想要对对Web资源进行保护,最好的办法莫过于Filter,要想对方法调用进行保护,最好的办法莫过于AOP。所以Spring Security在我们进行用户认证以及授予权限的时候,通过各种各样的拦截器来控制权限的访问,从而实现安全。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency>
#端口号配置
server.port=8081
#登录时可以使用的账号密码
#spring.security.user.name=zhenghuisheng
#spring.security.user.password=123456
#数据库连接基本参数
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/security?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=zhs03171812
#日志输出,使用默认的控制台输出
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
package com.zhenghuisheng.demo.pojo; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @NoArgsConstructor @AllArgsConstructor public class Users implements Serializable { //设置为自增 @TableId(type = IdType.AUTO) private Integer id; private String username; private String password; }
package com.zhenghuisheng.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zhenghuisheng.demo.pojo.Users;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper extends BaseMapper<Users> {
}
//增加扫描的配置文件
@MapperScan("com.zhenghuisheng.demo.mapper")
该注解开启之后可以通过注解实现用户的权限登录
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnable = true,prePostEnable = true)
package com.zhenghuisheng.demo; import com.zhenghuisheng.demo.mapper.UserMapper; import com.zhenghuisheng.demo.pojo.Users; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class DemoApplicationTests { @Autowired private UserMapper usermapper; @Test void contextLoads() { } @Test public void userInsert(){ Users users = new Users(); users.setUsername("admin"); users.setPassword("123456"); usermapper.insert(users); System.out.println(users + "输出成功"); } }
package com.zhenghuisheng.demo.controller; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/test") public class HelloSecurity { @GetMapping("/login") public String Hello(){ return "hello world"; } @RequestMapping("/index") public String toLogin(){ return "登录成功"; } //使用注解测试用户权限 @GetMapping("/secured") @Secured({"ROLE_admins","ROLE_manager"}) public String secured(){ return "secured login successful"; } }
package com.zhenghuisheng.demo.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl; import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; import javax.sql.DataSource; @Configuration public class SecurityTest extends WebSecurityConfigurerAdapter { @Autowired //UserDetailsService:用于查询数据库名和数据库密码的过程 private UserDetailsService userDetailService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder()); } @Bean PasswordEncoder passwordEncoder(){ //返回一个具体的实现类 return new BCryptPasswordEncoder(); } }
login.html:登录界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录界面</title>
</head>
<body>
<form action="/user/login" method="post">
姓名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="checkbox" name="remember-me" title="记住密码">自动登录
<input type="submit" value="登录">
</form>
</body>
</html>
success.html:登录成功后跳转的页面,并在界面中有一个退出文件,可以在一下的config中设置退出的路径以及退出后跳转的路径,原理和session的删除一致,只不过内部帮我们优化了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>登录成功</h2>
<a href="/logout">退出</a>
</body>
</html>
unauth.html:403没有权限问时的页面,当用户登录成功却没有权限时,即会跳转到该路径
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>没有权限访问</h1>
</body>
</html>
//自定义用户的操作,如登录页面等 @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() .loginPage("/login.html") //设置登录页面 .loginProcessingUrl("/user/login") //登录访问路径 .defaultSuccessUrl("/success.html").permitAll() //登录成功后的跳转路径 .and().authorizeRequests() .antMatchers("/","/test/login","/user/login").permitAll() //设置哪些路径可以访问,不需要认证 .antMatchers("/test/login").hasAuthority("admins") //授权,只有当用户为admins的时候,才能访问该路径 .anyRequest().authenticated() //所有请求都能访问 // .and().rememberMe().tokenRepository(persistentTokenRepository()) //记住我,并设置操作数据库的对象 // .tokenValiditySeconds(60) //有效时长 // .userDetailsService(userDetailService) .and().csrf().disable(); //关闭crsf防护 //配置没有权限访问跳转的自定义页面 http.exceptionHandling().accessDeniedPage("/unauth.html"); //配置退出 http.logout().logoutUrl("/logout") //退出 .logoutSuccessUrl("/test/login") // 退出成功所返回的路径 .permitAll(); }
.antMatchers("/test/login").hasAuthority("admins") //授权,
只有当用户为admins的时候,才能访问该路径,这就相当于增加了一道令牌token。而在数据库中,每个用户都有每个用户的职位,如经理,管理员,员工等
List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admins");
在这个"ROLE_admins"参数即为员工的职责,如果员工的职责与增加令牌token中能通过的角色一直时,则该员工可以访问该路径,否则不行,即实现了授权机制
而如果在使用hasRole方法和hasAnyRole方法时,看上面的图片就知道了,这个源码是有多无聊,自动在角色前面增加了一个 “ROLE_”。当然如果使用hasAnyAuthority方法和hasAuthority方法就不需要了。
这里是因为使用的注解开发了,在controller中使用了@Secured,当然也能使用@PreAuthorize和@PostAuthorize了!
运行后直接输入:http://localhost:8081/login.html
账号密码为数据库中的值,登录成功后
在进行注解测试,看能否测试成功,这里发现也能成功!
最后退出测试,即删除session,
http.logout().logoutUrl("/logout") //退出
.logoutSuccessUrl("/test/login") // 退出成功所返回的路径
.permitAll();
点击退出之后
再去访问 /test/index 发现已经不能访问了,没有权限访问,即session已经删除,则验证成功!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。