- 使用 Spring Initializr 创建 Spring Boot 应用程序
- 在Spring Boot中配置Cassandra
- 在 Spring Boot 上配置 Tomcat 连接池
- 将Camel消息路由到嵌入WildFly的Artemis上
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yl</groupId>
<artifactId>securitydemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>securitydemo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<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>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</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>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/min/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`password` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`enabled` tinyint(1) NULL DEFAULT NULL,
`locked` tinyint(1) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'root', '$2a$10$O8G0X/sUPAA76MV7U3BwY.3Uo8/QMBcqK678Rwkoz.fowbce.CLtO', 1, 0);
INSERT INTO `user` VALUES (2, 'admin', '$2a$10$O8G0X/sUPAA76MV7U3BwY.3Uo8/QMBcqK678Rwkoz.fowbce.CLtO', 1, 0);
INSERT INTO `user` VALUES (3, 'tom', '$2a$10$O8G0X/sUPAA76MV7U3BwY.3Uo8/QMBcqK678Rwkoz.fowbce.CLtO', 1, 0);
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`description` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES (1, 'ROLE_db', '数据库管理员');
INSERT INTO `role` VALUES (2, 'ROLE_admin', '系统管理员');
INSERT INTO `role` VALUES (3, 'ROLE_user', '用户');
DROP TABLE IF EXISTS `user_role_ref`;
CREATE TABLE `user_role_ref` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NULL DEFAULT NULL,
`role_id` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user_role_ref
-- ----------------------------
INSERT INTO `user_role_ref` VALUES (1, 1, 1);
INSERT INTO `user_role_ref` VALUES (2, 1, 2);
INSERT INTO `user_role_ref` VALUES (3, 2, 2);
INSERT INTO `user_role_ref` VALUES (4, 3, 3);
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=root
package com.yl.securitydemo.model;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class User implements UserDetails {
private Integer id;
private String username;
private String password;
private Boolean enabled;
private Boolean locked;
private List<Role> roles;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> list = new ArrayList<>();
for (Role role : roles) {
list.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
}
return list;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
// 账户是否未过期
@Override
public boolean isAccountNonExpired() {
return true;
}
// 账户是否未锁定
@Override
public boolean isAccountNonLocked() {
return !locked;
}
// 凭证是否未过期
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return enabled;
}
public void setPassword(String password) {
this.password = password;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", enabled=" + enabled +
", locked=" + locked +
'}';
}
}
package com.yl.securitydemo.model;
import java.io.Serializable;
public class Role implements Serializable {
private Integer id;
private String name;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
}
package com.yl.securitydemo.model;
import java.io.Serializable;
public class UserRoleRef implements Serializable {
private Integer id;
private Integer userId;
private Integer roleId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
@Override
public String toString() {
return "UserRoleRef{" +
"id=" + id +
", userId=" + userId +
", roleId=" + roleId +
'}';
}
}
package com.yl.securitydemo.mapper;
import com.yl.securitydemo.model.Role;
import com.yl.securitydemo.model.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
User loadUserByUsername(String username);
List<Role> getRolesByUserId(Integer userId);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yl.securitydemo.mapper.UserMapper">
<select id="loadUserByUsername" resultType="com.yl.securitydemo.model.User">
select * from user where username = #{username}
</select>
<select id="getRolesByUserId" resultType="com.yl.securitydemo.model.Role">
select * from role where id in (select role_id from user_role_ref where user_id = #{userId})
</select>
</mapper>
package com.yl.securitydemo.service;
import com.yl.securitydemo.mapper.UserMapper;
import com.yl.securitydemo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
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.Service;
@Service
public class UserService implements UserDetailsService {
@Autowired
UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.loadUserByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("用户名不存在");
}
user.setRoles(userMapper.getRolesByUserId(user.getId()));
return user;
}
}
package com.yl.securitydemo.controller;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
@RestController
public class KaptchaController {
@Autowired
Producer producer;
@GetMapping("/hello")
public String hello() {
return "hello";
}
//生成验证码
@GetMapping("/getVerifyCode")
public void getVerifyCode(HttpServletResponse response, HttpSession session) throws Exception{
response.setContentType("image/jpeg");
String text = producer.createText();
session.setAttribute("vf",text);
BufferedImage image = producer.createImage(text);
try(ServletOutputStream sos = response.getOutputStream()) {
ImageIO.write(image,"jpg",sos);
}
}
}
package com.yl.securitydemo.config;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class VerifyCodeConfig {
@Bean
Producer producer() {
Properties properties = new Properties();
properties.setProperty("kaptcha.image.width","150");
properties.setProperty("kaptcha.image.height","50");
properties.setProperty("kaptcha.textproducer.char.string","0123456789");
properties.setProperty("kaptcha.textproducer.char.length","4");
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(new Config(properties));
return defaultKaptcha;
}
}
package com.yl.securitydemo.config;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
public class MyAuthenticationProvider extends DaoAuthenticationProvider {
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
//校验密码前先校验验证码
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String code = request.getParameter("code");
String vf = (String)request.getSession().getAttribute("vf");
if (code == null || vf == null || !code.equals(vf)) {
throw new AuthenticationServiceException("验证码错误");
}
//校验密码
super.additionalAuthenticationChecks(userDetails, authentication);
}
}
package com.yl.securitydemo.config;
import com.yl.securitydemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
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.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
MyAuthenticationProvider myAuthenticationProvider() {
MyAuthenticationProvider provider = new MyAuthenticationProvider();
provider.setPasswordEncoder(passwordEncoder());
provider.setUserDetailsService(userService);
return provider;
}
@Override
@Bean
protected AuthenticationManager authenticationManager() throws Exception {
return new ProviderManager(myAuthenticationProvider());
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/getVerifyCode")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("login success");
}
})
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("login fail");
}
})
.permitAll()
.and()
.csrf().disable();
}
}
1.不携带验证码,登陆失败
2.携带错误验证码,登录失败
3.携带正确的验证码,登录成功
我在网上找到了这个很棒的小代码,但它似乎没有在正确删除空格后比较两个字符串?我知道一些js,但这里的任何错误都超出了我的理解范围。希望有人知道这个问题的答案。 注意:它似乎还根据 channel 的数
如何使用 requirejs 导入 recaptcha。我已经尝试了几件事,但没有任何效果。 我需要这样做,以便能够在加载后使用 reCaptcha 的渲染方法自行渲染它。 require.confi
我可以做些什么来尝试解决之前一直有效但现在在尝试访问 javascript 文件时返回 404 的重新验证码问题。 我不认为这是编码问题,因为他们今天下午就起来了。 值得一提的是,我的两个使用 re-
好的,我们在生产中实现了 Recaptcha。我们收到错误是因为它无法到达使用该服务所需的 IP 地址。我们为 IP 地址打开一个端口以到达 Google。没问题。我们这样做并显式配置该 IP 地址以
我正在使用 Robot Framework + Selenium2Library 为 Web 编写验收测试。关键是 web 包含一些我无法自动化的输入字段 (CAPTCHA),并且我无法告诉我的供应商
我正在尝试实现验证码。我正在使用 jquery (ajax) 调用验证脚本 (http://www.google.com/recaptcha/api/verify)。这将数据类型限制为 JSONP,G
我在站点中使用 scrapy 提交表单 https://www.barefootstudent.com/jobs (任何进入页面的链接等http://www.barefootstudent.com/l
我经营一个游戏网站,所以我有很多用户登录,他们可以每两分钟做一次某些事情。 我在某些地方有一个 CAPTCHA 系统,对于某些东西,它总是要求输入代码,而对于其他东西,它会每 10 分钟询问一次。 我
thinkphp中的验证码是可以直接调用的,非常方便,我们看一下 Think 文件夹下 有一个名为verify.class.php的文件 首先 我们要有一个模
我正在实现一个在注册表单上带有验证码的网站;我的第一次。我已经阅读了数十篇关于支持和反对论点以及所有各种实现的帖子。我对这一切很满意,但对我来说这是必要的邪恶。 我不明白的是为什么人们会在整个网络上的
我正在使用 Sitecore 8 update 3,目前我向 WFFM 表单添加了验证码并按下音频,但显示错误如下: [ArgumentNullException: Value cannot be n
我正在对我已经完成的网络系统部分进行一小部分升级,其中之一是确保我的 Google reCaptcha 的安全性正确。 目前,我使用此代码: //reCaptcha $Url = "https://w
我正在对我已经完成的网络系统部分进行一小部分升级,其中之一是确保我的 Google reCaptcha 的安全性正确。 目前,我使用此代码: //reCaptcha $Url = "https://w
我对制作 3D 验证码很感兴趣,我让它使用一种字体,如下所示: import string from matplotlib.font_manager import findSystemFonts im
大家。我是jquery初学者,想请教几个问题。 我正在为表单提交测试编写一个简单的数学验证码,我想每次按下“重置按钮”时生成一组新的随机数。 但是当我用谷歌搜索解决方案时,大多数人都在尝试重新加载页面
我的网站上有一个验证码,我认为样式被其他一些 css 覆盖了,正如您在下面的验证码底部看到的那样,它有点偏离.. 在 firebug 中发现 CSS 覆盖的最佳方法是什么?已经看了一段时间了,似乎无法
我在 Google Play 上有一个 PNR 查询应用程序。它工作得很好。但最近 Indian Railwys 在他们的 PNR 查询部分添加了验证码,因此我无法将正确的数据传递到服务器以获得正确的
我被指派为 joomla 中的自定义组件创建验证码验证,但我不知道如何正确地完成它。 我知道有许多可用的验证码插件,例如 recaptcha,但我需要使用公司创建的自定义验证码。 它在 session
本文实例讲述了php/JS实现的生成随机密码(验证码)功能。分享给大家供大家参考,具体如下: PHP写法: ?
我正在关注关于电话授权的 React Native firebase 文档 ( https://rnfirebase.io/docs/v5.x.x/auth/phone-auth ),并且对是否需要(
我是一名优秀的程序员,十分优秀!